package com.sipai.jspatrol.Patrol;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sipai.jspatrol.Bean.InputPoint;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Bean.PatrolLocation;
import com.sipai.jspatrol.Bean.PatrolPointContent;
import com.sipai.jspatrol.Patrol.patrolInfoAdapter.PatrolEqu;
import com.sipai.jspatrol.Patrol.patrolInfoAdapter.PatrolInfoEquAdapter;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.Bean.Patrol;
import com.sipai.jspatrol.Bean.ProPatrolPoint;
import com.sipai.jspatrol.Bean.ProcessSection;
import com.sipai.jspatrol.Fault.NewFaultActivity;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.utils.Global.GlobalVal;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.Utils;
import com.sipai.ui.CustomDialog;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.sipai.jspatrol.utils.Global.GlobalVal.Status_PartFinish;
import static com.sipai.jspatrol.utils.Global.GlobalVal.Status_Undo;


/**
 * 日常巡检任务详情
 */
public class PatrolDetailActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_content, tv_endtime, tv_add_remark, tv_name;
    private RecyclerView rc_list;
    private String remark = "";
    private Button btn_sub, btn_unfinish;
    private LinearLayout ll_add_remark;
    //    private String id;//巡检任务id
    private Patrol patrolDetail;
    private List<PatrolLocation> locations = new ArrayList<>();
    private String loc_json;
    //巡检类型
    private String patrolType;//Product("P","生产巡检"), Equipment( "E","设备巡检"), Administrator("A","管理组"),Maintenance("M","运维组");
    private List<ProPatrolPoint> points = new ArrayList<>();
    private List<PatrolEqu> equs = new ArrayList<>();
    private ProPatrolPoint sel_point;
    private ProPatrolPointAdapter adapter;
    private StaggeredGridLayoutManager manager;
    private NfcAdapter nfcAdapter;
    // 是否支持NFC功能的标签
    private boolean isNFC_support = false;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private SweetAlertDialog pDialog;
    private String status = "1";
    private LinearLayout ll_sub;
    private String content, name, endTime, result, startTime;
    private TextView tv_result,tv_worker,tv_finish_time;
    private ImageView iv_back;
    private LinearLayout ll_sub_fault;
    private String requesturl = "";
    private LinearLayoutManager equManager;
    private PatrolInfoEquAdapter equAdapter;
    private static final int REQUEST_CODE_SCAN = 23;
    private Button btn_off_line;
    private CardView cv;
    private String subTask = "";

    public static void actionStart(Context context, Patrol task) {
        Intent intent = new Intent(context, PatrolDetailActivity.class);
        intent.putExtra("task", task);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patrol_detail);
        init();
        initView();
        updatePatrolInfo();
        checkNFC();
    }

    private void updatePatrolInfo() {
        if (status.equals(GlobalVal.Status_Finish) || status.equals(Status_PartFinish) || status.equals(Status_Undo)) {
            ll_sub.setVisibility(View.GONE);
            if (nfcAdapter != null && nfcAdapter.isEnabled()) {
                // 当前Activity如果不在手机的最前端，就停止NFC设备连接的监听
                stopNFC_Listener();
            }
            tv_result.setVisibility(View.VISIBLE);
            cv.setVisibility(View.GONE);
            if (result != null && !result.isEmpty()) {
                if (status.equals(GlobalVal.Status_Finish)) {
                    tv_result.setBackgroundColor(getResources().getColor(R.color.green));
                    tv_result.setText("巡检结果:" + result);
                } else {
                    tv_result.setText("巡检结果:" + result);
                }
            } else {
                if (status.equals(GlobalVal.Status_Finish)) {
                    tv_result.setBackgroundColor(getResources().getColor(R.color.green));
                    tv_result.setText("巡检结果:未填写");
                } else {
                    tv_result.setText("巡检结果:未填写");
                }
            }
        } else {
            tv_result.setVisibility(View.GONE);
        }
        if (patrolDetail.getWorker()!=null&&!patrolDetail.getWorker().isEmpty()){
            tv_worker.setText("提交人：  "+patrolDetail.getWorker());
        }else {
            tv_worker.setVisibility(View.GONE);
        }
        if (patrolDetail.getActFinishTime()!=null&&!patrolDetail.getActFinishTime().isEmpty()){
            tv_finish_time.setText("提交时间：  "+patrolDetail.getActFinishTime().substring(0,16));
        }else {
            tv_finish_time.setVisibility(View.GONE);
        }
        tv_content.setText("内容：  " + content);
        if (endTime.length() > 15) {
            tv_endtime.setText("任务时间：  " + startTime.substring(5, 16) + " -- " + endTime.substring(5, 16));
        } else {
            tv_endtime.setText("任务时间：  " + startTime + " -- " + endTime);
        }
        tv_name.setText(name);
    }

    private void checkNFC() {
        // 获取nfc适配器，判断设备是否支持NFC功能
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            showToast(getResources().getString(R.string.no_nfc));
        } else if (!nfcAdapter.isEnabled()) {
            showToast(getResources().getString(R.string.open_nfc));
        }
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[]{ndef};// 过滤器
        mTechLists = new String[][]{
                new String[]{MifareClassic.class.getName()},
                new String[]{NfcA.class.getName()}};// 允许扫描的标签类型
    }

    private void pDialogHide() {
        if (!PatrolDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pDialog.hide();
                }
            });
        }
    }

    private void pDialogshow(final String s) {
        if (!PatrolDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pDialog.setTitleText(s);
                    pDialog.show();
                }
            });
        }
    }

    /**
     * 初始化
     */
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private String token;

    public void init() {
        SharedPreferences sharedPre = getSharedPreferences("config", MODE_PRIVATE);
        mServer = sharedPre.getString("server", "");
        mUsername = sharedPre.getString("username", "");
        mPassword = sharedPre.getString("password", "");
        mUserid = sharedPre.getString("userid", "");
        mCaption = sharedPre.getString("caption", "");
        mBizid = sharedPre.getString("bizid", "");
        token = sharedPre.getString("token", "");
        subTask=sharedPre.getString("subtask", "");
        patrolDetail = (Patrol) getIntent().getSerializableExtra("task");
        status = patrolDetail.getStatus();
        content = patrolDetail.getContent();
        name = patrolDetail.getName();
        endTime = patrolDetail.getEndTime();
        startTime = patrolDetail.getStartTime();
        result = patrolDetail.getWorkResult();
        requesturl = MethodURL.GetPatrolTaskDetail_Method;
    }

    private void initView() {
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#419DE4"));
        pDialog.setTitleText("数据上传中...");
        pDialog.setCancelable(false);
        pDialog.setCanceledOnTouchOutside(false);
        iv_back = findViewById(R.id.moudle_patrol_detail_iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_content = findViewById(R.id.moudle_patrol_detail_tv_task_content);
        tv_endtime = findViewById(R.id.moudle_patrol_detail_tv_task_endtime);
        rc_list = findViewById(R.id.moudle_patrol_detail_rcview_point);
        manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rc_list.setLayoutManager(manager);
        btn_sub = findViewById(R.id.moudle_patrol_detail_btn_sub_task);
        btn_sub.setOnClickListener(this);
        if (subTask.equals("true")){
            btn_sub.setVisibility(View.VISIBLE);
        }
        tv_result = findViewById(R.id.moudle_patrol_detail_tv_task_result);
        tv_worker = findViewById(R.id.moudle_patrol_detail_tv_worker);
        tv_finish_time = findViewById(R.id.moudle_patrol_detail_tv_finish_time);
        ll_add_remark = findViewById(R.id.moudle_patrol_detail_ll_add_remark);
        ll_add_remark.setOnClickListener(this);
        ll_sub = findViewById(R.id.moudle_patrol_detail_ll_sub);
        tv_name = findViewById(R.id.moudle_patrol_detail_tv_task_name);
        btn_unfinish = findViewById(R.id.moudle_patrol_detail_btn_unfinish);
        btn_unfinish.setOnClickListener(this);
        ll_sub_fault = findViewById(R.id.moudle_patrol_detail_ll_sub_fault);
        ll_sub_fault.setOnClickListener(this);
        btn_off_line = findViewById(R.id.moudle_patrol_detail_btn_off_line);
        btn_off_line.setOnClickListener(this);
        cv = findViewById(R.id.moudle_patrol_detail_cv);
//        List<Patrol> lll = LitePal.where("sid = ?",patrolDetail.getSid()).find(Patrol.class);
//        if (lll.size()>0){
//            btn_off_line.setVisibility(View.GONE);
//        }else {
//            btn_off_line.setVisibility(View.VISIBLE);
//        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.moudle_patrol_detail_btn_off_line:
                LitePal.deleteAll(Patrol.class);
                LitePal.deleteAll(ProPatrolPoint.class);
                LitePal.deleteAll(PatrolEqu.class);
                LitePal.deleteAll(InputPoint.class);
                LitePal.deleteAll(PatrolPointContent.class);
                getOffLineData();
                break;
            case R.id.moudle_patrol_detail_ll_add_remark:
                CustomDialog dialog = new CustomDialog(PatrolDetailActivity.this, R.style.customDialog, R.layout.edt_dialog);
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
                TextView tv_title = dialog.findViewById(R.id.moudle_edt_dialog_title);
                tv_title.setText("填写备注");
                EditText edt_content = dialog.findViewById(R.id.moudle_edt_dialog_edt);
                Button btn_cancel = dialog.findViewById(R.id.moudle_edt_dialog_btn_cancel);
                btn_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                Button btn_confirm = dialog.findViewById(R.id.moudle_edt_dialog_btn_confirm);
                btn_confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        if (edt_content.getText() != null && !edt_content.getText().toString().isEmpty()) {
                            remark = edt_content.getText().toString();
                        } else {
                            remark = "";
                        }
                    }
                });
                break;
            case R.id.moudle_patrol_detail_ll_sub_fault:
                NewFaultActivity.actionStart(PatrolDetailActivity.this,"",patrolDetail.getSid(),"");
                break;
            case R.id.moudle_patrol_detail_btn_sub_task:
//                List<Patrol> lll = LitePal.where("sid = ?",patrolDetail.getSid()).find(Patrol.class);
//                if (lll.size()>0) {
//                    Patrol pp = lll.get(0);
//                    points = pp.getPatrolRecordPatrolRoutes();
//                    int a = points.size();
//                }
//                List<ProPatrolPoint> lp = LitePal.findAll(ProPatrolPoint.class,true);
//                List<InputPoint> li = LitePal.findAll(InputPoint.class);
//                List<PatrolEqu> le = LitePal.findAll(PatrolEqu.class,true);
//                List<PatrolPointContent> ls = LitePal.findAll(PatrolPointContent.class);
                int notAll = 0;
                for (int i = 0; i < points.size(); i++) {
                    if (!points.get(i).getStatus().equals(GlobalVal.Status_Finish)) {
                        notAll = notAll + 1;
                    }
                }
                if (notAll > 0) {
                    isConfNotAll();
                } else {
                    isConfSub();
                }
                break;
            case R.id.moudle_patrol_detail_btn_unfinish:
//                UnfinishedPatrolTaskActivity.actionStart(PatrolDetailActivity.this, id, patrolType);
                break;
        }
    }

    /**
     * 获取离线数据
     */
    private void getOffLineData() {
        pDialogshow("数据下载中...");
        HashMap<String, String> map = new HashMap<>();
        map.put("patrolRecordId", patrolDetail.getSid());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetOffLineData_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                pDialogHide();
                showToast("离线数据获取失败:"+e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                pDialogHide();
                if (res != null && !res.isEmpty()) {
                    parseOfflineTask(res);
                } else {
                    showToast("任务详情获取失败");
                }
            }
        });
    }

    private void parseOfflineTask(String res) {
        try {
            JSONObject jsonObject = new JSONObject(res);
            if (jsonObject.optString("code").equals("1")){
                JSONArray array = jsonObject.getJSONArray("result");
                JSONObject jspatrol = array.getJSONObject(0);
                Patrol patrol = new Patrol();
                patrol.setSid(jspatrol.optString("id"));
                patrol.setType(jspatrol.optString("type"));
                patrol.setContent(jspatrol.optString("content"));
                patrol.setStatus(jspatrol.optString("status"));
                patrol.setStartTime(jspatrol.optString("startTime"));
                patrol.setEndTime(jspatrol.optString("endTime"));
                patrol.setName(jspatrol.optString("name"));
                //巡检执行内容
                List<ProPatrolPoint> patrolPoints = new ArrayList<>();
                JSONArray jspoint = jspatrol.getJSONArray("patrolRecordPatrolRoutes");
                for (int i=0;i<jspoint.length();i++){
                    ProPatrolPoint item = new ProPatrolPoint();
                    item.setResultId(jspoint.getJSONObject(i).optString("id"));
                    JSONObject pointj = jspoint.getJSONObject(i).getJSONObject("patrolPoint");
                    item.setName(pointj.optString("name"));
                    item.setPatrolRecordPatrolRouteId(jspoint.getJSONObject(i).optString("id"));
                    item.setSid(jspoint.getJSONObject(i).optString("patrolPointId"));
                    item.setStatus(jspoint.getJSONObject(i).optString("status"));
                    item.setPatrolPointId(jspoint.getJSONObject(i).optString("patrolPointId"));
                    item.setPatrolRecordId(jspoint.getJSONObject(i).optString("patrolRecordId"));
                    item.setTaskId(jspoint.getJSONObject(i).optString("patrolRecordId"));
                    item.setPointType(pointj.optString("type"));
                    item.setProcessSectionId(pointj.optString("processSectionId"));
                    item.setWorkerName(jspoint.getJSONObject(i).optString("workerName"));
                    item.setWorkerId(jspoint.getJSONObject(i).optString("workerId"));
                    item.setFinishDt(jspoint.getJSONObject(i).optString("finishdt"));
                    if (pointj.optString("processSection") != null && !pointj.optString("processSection").isEmpty()) {
                        JSONObject pps = pointj.getJSONObject("processSection");
                        ProcessSection psn = new ProcessSection();
                        psn.setSid(pps.optString("id"));
                        psn.setName(pps.optString("name"));
                        psn.setSname(pps.optString("sname"));
                        item.setProcessSection(psn);
                        item.setProcessSectionId(pps.optString("id"));
                        item.setProcessSectionName(pps.optString("sname"));
                    }
                    List<PatrolPointContent> patrolPointContents = new ArrayList<>();
                    JSONArray jscontents = jspoint.getJSONObject(i).getJSONArray("patrolContentsRecords");
                    if (jscontents.length()>0) {
                        for (int a = 0; a < jscontents.length(); a++) {
                            PatrolPointContent content = new PatrolPointContent();
                            content.setSid(jscontents.getJSONObject(a).optString("id"));
                            content.setContents(jscontents.getJSONObject(a).optString("contents"));
                            content.setContentsDetail(jscontents.getJSONObject(a).optString("contentsDetail"));
                            content.setStatus(jscontents.getJSONObject(a).optString("status"));
                            content.setPatrolPointId(jscontents.getJSONObject(a).optString("patrolPointId"));
                            content.setPatrolRecordId(jscontents.getJSONObject(a).optString("patrolRecordId"));
                            content.setPid(jscontents.getJSONObject(a).optString("pid"));
                            content.setType(jscontents.getJSONObject(a).optString("type"));
                            content.setEquipmentId(jscontents.getJSONObject(a).optString("equipmentId"));
                            content.setProPatrolPoint(item);
                            patrolPointContents.add(content);
                            if (content.save()){
                                Log.i("Offline", "parseOfflineTask: true");
                            }
                            content.save();
                        }
                    }
                    item.setPatrolContentsRecords(patrolPointContents);
                    //巡检填报内容
                    List<InputPoint> inputPoints = new ArrayList<>();
                    JSONArray jsinputs = jspoint.getJSONObject(i).getJSONArray("patrolMeasurePointRecords");
                    if (jsinputs.length()>0) {
                        for (int b = 0; b < jsinputs.length(); b++) {
                            InputPoint in = new InputPoint();
                            in.setSid(jsinputs.getJSONObject(b).optString("id"));
                            in.setPid(jsinputs.getJSONObject(b).optString("pid"));
                            in.setPatrolPointId(jsinputs.getJSONObject(b).optString("patrolPointId"));
                            in.setPatrolRecordId(jsinputs.getJSONObject(b).optString("patrolRecordId"));
                            in.setEquipmentId(jsinputs.getJSONObject(b).optString("equipmentId"));
                            JSONObject js = new JSONObject(jsinputs.getJSONObject(b).opt("mPoint").toString());
                            in.setAlarmmax(js.optString("alarmmax"));
                            in.setAlarmmin(js.optString("alarmmin"));
                            in.setBiztype(js.optString("biztype"));
                            in.setValuemeaning(js.optString("valuemeaning"));
                            in.setMeasuredt(js.optString("measuredt"));
                            in.setMpointcode(js.optString("mpointcode"));
                            in.setParmname(js.optString("parmname"));
                            in.setParmvalue(jsinputs.getJSONObject(b).optString("mpvalue"));
                            in.setSignalType(js.optString("signaltype"));
                            in.setSql(js.optString("sql"));
                            in.setUnit(js.optString("unit"));
                            in.setWhere(js.optString("where"));
                            in.setProPatrolPoint(item);
                            inputPoints.add(in);
                            in.save();
                            if (in.save()){
                                Log.i("Offline", "parseOfflineTask: true");
                            }
                        }
                    }
                    item.setPatrolMeasurePointRecords(inputPoints);
                    //巡检点下的设备
                    List<PatrolEqu>  patrolEqus = new ArrayList<>();
                    JSONArray jsequs = jspoint.getJSONObject(i).getJSONArray("patrolRecordPatrolEquipments");
                    if (jsequs.length()>0) {
                        for (int c = 0; c < jsequs.length(); c++) {
                            PatrolEqu equ = new PatrolEqu();
                            if (jsequs.getJSONObject(c).optString("equipmentCard")!=null&&!jsequs.getJSONObject(c).optString("equipmentCard").equals("null")) {
                                JSONObject jscard = jsequs.getJSONObject(c).getJSONObject("equipmentCard");
                                equ.setEquipmentId(jscard.optString("id"));
                                equ.setSid(jsequs.getJSONObject(c).optString("id"));
                                equ.setEquipmentName(jscard.optString("equipmentname"));
                                equ.setStatus(jsequs.getJSONObject(c).optString("status"));
                                equ.setPatrolPointId(jsequs.getJSONObject(c).optString("patrolPointId"));
                                equ.setPatrolRecordId(jsequs.getJSONObject(c).optString("patrolRecordId"));
                                equ.setEquipmentCardId(jscard.optString("equipmentcardid"));
                                equ.setManufacturers(jscard.optString("equipmentmanufacturer"));
                                equ.setType(jspatrol.optString("type"));
                                if (jscard.optString("measurePoints") != null && !jscard.optString("measurePoints").isEmpty()) {
                                    List<Measuringpoint> mps = new ArrayList<>();
                                    JSONArray aps = new JSONArray(jscard.optString("measurePoints"));
                                    if (aps.length() > 0) {
                                        for (int a = 0; a < aps.length(); a++) {
                                            Measuringpoint point = new Measuringpoint();
                                            point.setSid(aps.getJSONObject(a).optString("id"));
                                            point.setName(aps.getJSONObject(a).optString("parmName"));
                                            point.setCvalue(aps.getJSONObject(a).optString("parmValue"));
                                            point.setUnit(aps.getJSONObject(a).optString("unit"));
                                            point.setType(aps.getJSONObject(a).optString("signaltype"));
                                            point.setPatrolEqu(equ);
                                            mps.add(point);
                                            point.save();
                                        }
                                    }
                                    equ.setMeasuringpoints(mps);
                                }
                                //设备下巡检内容
                                JSONArray jsequcontents = jsequs.getJSONObject(c).getJSONArray("patrolContentsRecords");
                                List<PatrolPointContent> equContents = new ArrayList<>();
                                if (jsequcontents.length() > 0) {
                                    for (int d = 0; d < jsequcontents.length(); d++) {
                                        PatrolPointContent content = new PatrolPointContent();
                                        content.setSid(jsequcontents.getJSONObject(d).optString("id"));
                                        content.setContents(jsequcontents.getJSONObject(d).optString("contents"));
                                        content.setContentsDetail(jsequcontents.getJSONObject(d).optString("contentsDetail"));
                                        content.setStatus(jsequcontents.getJSONObject(d).optString("status"));
                                        content.setPatrolPointId(jsequcontents.getJSONObject(d).optString("patrolPointId"));
                                        content.setPatrolRecordId(jsequcontents.getJSONObject(d).optString("patrolRecordId"));
                                        content.setPid(jsequcontents.getJSONObject(d).optString("pid"));
                                        content.setType(jsequcontents.getJSONObject(d).optString("type"));
                                        content.setEquipmentId(jsequcontents.getJSONObject(d).optString("equipmentId"));
                                        content.setPatrolEqu(equ);
                                        equContents.add(content);
                                        content.save();
                                    }
                                }
                                equ.setPatrolContentsRecords(equContents);
                                //设备下填报内容
                                JSONArray jsequinpoints = jsequs.getJSONObject(c).getJSONArray("patrolMeasurePointRecords");
                                List<InputPoint> equinpoints = new ArrayList<>();
                                if (jsequinpoints.length() > 0) {
                                    for (int e = 0; e < jsequinpoints.length(); e++) {
                                        InputPoint in = new InputPoint();
                                        in.setSid(jsequinpoints.getJSONObject(e).optString("id"));
                                        in.setPid(jsequinpoints.getJSONObject(e).optString("pid"));
                                        in.setPatrolPointId(jsequinpoints.getJSONObject(e).optString("patrolPointId"));
                                        in.setPatrolRecordId(jsequinpoints.getJSONObject(e).optString("patrolRecordId"));
                                        in.setEquipmentId(jsequinpoints.getJSONObject(e).optString("equipmentId"));
                                        JSONObject js = new JSONObject(jsequinpoints.getJSONObject(e).optString("mPoint"));
                                        in.setAlarmmax(js.optString("alarmmax"));
                                        in.setAlarmmin(js.optString("alarmmin"));
                                        in.setBiztype(js.optString("biztype"));
                                        in.setValuemeaning(js.optString("valuemeaning"));
                                        in.setMeasuredt(js.optString("measuredt"));
                                        in.setMpointcode(js.optString("mpointcode"));
                                        in.setParmname(js.optString("parmname"));
                                        in.setParmvalue(jsequinpoints.getJSONObject(e).optString("mpvalue"));
                                        in.setSignalType(js.optString("signaltype"));
                                        in.setSql(js.optString("sql"));
                                        in.setUnit(js.optString("unit"));
                                        in.setWhere(js.optString("where"));
                                        in.setPatrolEqu(equ);
                                        equinpoints.add(in);
                                        in.save();
                                    }
                                }
                                equ.setPatrolMeasurePointRecords(equinpoints);
                                equ.setProPatrolPoint(item);
                                patrolEqus.add(equ);
                                equ.save();
                            }
                        }
                    }
                    item.setPatrolRecordPatrolEquipments(patrolEqus);
                    item.setPatrol(patrol);
                    patrolPoints.add(item);
                    item.save();
                }
                patrol.setPatrolRecordPatrolRoutes(patrolPoints);
                patrol.save();
                showToast("离线任务缓存成功！");
            }else {
                showToast("任务详情获取失败");
            }
        } catch (JSONException e) {
            showToast("任务详情获取失败");
            e.printStackTrace();
        }
    }

    private void isConfNotAll() {
        if (!PatrolDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolDetailActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("检测到尚有巡检点未巡检，是否确认提交任务？")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    if(remark!=null&&!remark.isEmpty()&&!remark.replaceAll(" +","").isEmpty()) {
                                        subTask();
                                    }else {
                                        showToast("请在备注中填写未巡检完整原因后再提交！");
                                    }
                                }
                            }).setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private void isConfSub() {
        if (!PatrolDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolDetailActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("是否确认提交任务？")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    subTask();
                                }
                            }).setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private void subTask() {
        pDialogshow("数据上传中...");
        locations = LitePal.where("insdt > ? and insdt < ?",startTime,endTime).find(PatrolLocation.class);
        Gson gson = new Gson();
        loc_json = "{\"re1\":" + gson.toJson(locations) + "}";
        List<Patrol> lll = LitePal.where("sid = ?",patrolDetail.getSid()).find(Patrol.class);
        if (lll.size()>0){
            subOfflineData();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("id", patrolDetail.getSid());
        map.put("workResult", remark);
        map.put("workerId", mUserid);
        map.put("json", loc_json);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.SubPatrolTask_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                pDialogHide();
                showToast("失败:"+e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                pDialogHide();
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    if (jsonObject.opt("code").toString().equals("1")) {
//                        subContent();
                        successDialog();
                    } else {
                        if (jsonObject.optString("msg").contains("时间内")) {
                            showToast(jsonObject.optString("msg"));
                        }else {
                            showToast("提交失败！");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void subOfflineData() {
        List<Patrol> lll = LitePal.where("sid = ?",patrolDetail.getSid()).find(Patrol.class);
        if (lll.size()>0) {
            Patrol pp = lll.get(0);
            pp.setWorkResult(remark);
            points = pp.getPatrolRecordPatrolRoutes();
            for (int i=0;i<points.size();i++){
                points.get(i).setPatrolContentsRecords(points.get(i).getPatrolContentsRecords());
                points.get(i).setPatrolMeasurePointRecords(points.get(i).getPatrolMeasurePointRecords());
                List<PatrolEqu> equs = points.get(i).getPatrolRecordPatrolEquipments();
                for (int a=0;a<equs.size();a++){
                    equs.get(a).setPatrolMeasurePointRecords(equs.get(a).getPatrolMeasurePointRecords());
                    equs.get(a).setPatrolContentsRecords(equs.get(a).getPatrolContentsRecords());
                }
                points.get(i).setPatrolRecordPatrolEquipments(equs);
            }
            pp.setPatrolRecordPatrolRoutes(points);
            pp.setWorkerId(mUserid);
            Gson gson = new Gson();
            String json = gson.toJson(pp);
            HashMap<String, String> map = new HashMap<>();
            map.put("json", json);
            map.put("isLimited","true");
            OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.SubOfflinePatrolTask_Method)).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    pDialogHide();
                    showToast("失败:"+e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    pDialogHide();
                    try {
                        JSONObject jsonObject = new JSONObject(res);
                        if (jsonObject.opt("code").toString().equals("1")) {
//                            successDialog();
                        } else {
                            showToast("失败");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private void showToast(String s) {
        if (!PatrolDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(PatrolDetailActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void successDialog() {
        if (!PatrolDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolDetailActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("提交成功！")
                            .setConfirmText("确认")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    finish();
                                }
                            }).show();
                }
            });
        }
    }

    private void getTaskDetail() {
        pDialogshow("数据加载中...");
        HashMap<String, String> map = new HashMap<>();
        map.put("patrolRecordId", patrolDetail.getSid());
        map.put("type", patrolDetail.getType());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, requesturl)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                pDialogHide();
                showToast("失败:"+e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                pDialogHide();
                if (res != null && !res.isEmpty()) {
                    points = parsePoints(res);
                    updateList();
                } else {
                    showToast("任务详情获取失败");
                }
            }
        });
    }

    private List<PatrolEqu> parsePatrolEqu(String response) {
        List<PatrolEqu> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray array = new JSONArray(jsonObject.optString("result"));
            for (int i = 0; i < array.length(); i++) {
                PatrolEqu item = new PatrolEqu();
                JSONObject js = array.getJSONObject(i).getJSONObject("equipmentCard");
                item.setEquipmentId(js.optString("id"));
                item.setEquipmentName(js.optString("equipmentname"));
                item.setStatus(array.getJSONObject(i).optString("status"));
                item.setPatrolPointId(array.getJSONObject(i).optString("patrolPointId"));
                item.setPatrolRecordId(array.getJSONObject(i).optString("patrolRecordId"));
                item.setEquipmentCardId(js.optString("equipmentcardid"));
                item.setManufacturers(js.optString("equipmentmanufacturer"));
                if (array.getJSONObject(i).optString("measurePoints") != null && !array.getJSONObject(i).optString("measurePoints").isEmpty()) {
                    List<Measuringpoint> mps = new ArrayList<>();
                    JSONArray aps = new JSONArray(array.getJSONObject(i).optString("measurePoints"));
                    for (int a = 0; a < aps.length(); a++) {
                        Measuringpoint point = new Measuringpoint();
                        point.setSid(aps.getJSONObject(a).optString("id"));
                        point.setName(aps.getJSONObject(a).optString("parmName"));
                        point.setCvalue(aps.getJSONObject(a).optString("parmValue"));
                        point.setUnit(aps.getJSONObject(a).optString("unit"));
                        point.setType(aps.getJSONObject(a).optString("signaltype"));
                        mps.add(point);
                    }
                    item.setMeasuringpoints(mps);
                }
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 更新生产巡检巡检点列表
     */
    private void updateList() {
        if (!PatrolDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (points.size() > 0) {
                        rc_list.setVisibility(View.VISIBLE);
                        adapter = new ProPatrolPointAdapter(points, PatrolDetailActivity.this, new ProPatrolPointAdapter.onRecyclerViewItemClick() {
                            @Override
                            public void onItemClick(View v, int position) {
//                                sel_point = points.get(position);
//                                Intent intent = new Intent(PatrolDetailActivity.this, CaptureActivity.class);
//                                /*ZxingConfig是配置类
//                                 *可以设置是否显示底部布局，闪光灯，相册，
//                                 * 是否播放提示音  震动
//                                 * 设置扫描框颜色等
//                                 * 也可以不传这个参数
//                                 * */
//                                ZxingConfig config = new ZxingConfig();
//                                config.setPlayBeep(true);//是否播放扫描声音 默认为true
//                                config.setShake(true);//是否震动  默认为true
//                                config.setDecodeBarCode(true);//是否扫描条形码 默认为true
////                                config.setReactColor(R.color.white);//设置扫描框四个角的颜色 默认为白色
////                                config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
////                                config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
//                                config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
//                                intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
//                                startActivityForResult(intent, REQUEST_CODE_SCAN);
                            }
                        });
                        rc_list.setAdapter(adapter);
                        manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
                        rc_list.setLayoutManager(manager);
                    } else {
                        rc_list.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    /**
     * 更新设备巡检设备列表
     */
    private void updateEquList() {
        if (!PatrolDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (equs.size() > 0) {
                        rc_list.setVisibility(View.VISIBLE);
                        equManager = new LinearLayoutManager(PatrolDetailActivity.this);
                        rc_list.setLayoutManager(equManager);
                        equAdapter = new PatrolInfoEquAdapter(equs, PatrolDetailActivity.this);
                        rc_list.setAdapter(equAdapter);
                    } else {
                        rc_list.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    private List<ProPatrolPoint> parsePoints(String response) {
        List<ProPatrolPoint> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray arry = new JSONArray(jsonObject.optString("result"));
            for (int i = 0; i < arry.length(); i++) {
                ProPatrolPoint item = new ProPatrolPoint();
                item.setResultId(arry.getJSONObject(i).optString("recordId"));
                item.setStatus(arry.getJSONObject(i).optString("status"));
                item.setSid(arry.getJSONObject(i).optString("id"));
                item.setName(arry.getJSONObject(i).optString("name"));
                item.setTaskId(patrolDetail.getSid());
                item.setType(patrolDetail.getType());
                item.setPointType(arry.getJSONObject(i).optString("type"));
                item.setProcessSectionId(arry.getJSONObject(i).optString("processSectionId"));
                item.setWorkerName(arry.getJSONObject(i).optString("workerName"));
                item.setFinishDt(arry.getJSONObject(i).optString("finishDt"));
                if (arry.getJSONObject(i).optString("processSectionName") != null && !arry.getJSONObject(i).optString("processSectionName").isEmpty()) {
                    ProcessSection psn = new ProcessSection();
                    psn.setSid(arry.getJSONObject(i).optString("processSectionId"));
                    psn.setName(arry.getJSONObject(i).optString("processSectionName"));
                    psn.setSname(arry.getJSONObject(i).optString("processSectionName"));
                    item.setProcessSection(psn);
                }
                List<ProPatrolPoint> pps = LitePal.where("sid = ? and resultId = ?",item.getSid(),item.getResultId()).find(ProPatrolPoint.class);
                if (pps.size()>0){
                    if (pps.get(0).getWorkerId()!=null&&!pps.get(0).getWorkerId().isEmpty()){
                        item.setWorkerName(pps.get(0).getWorkerName());
                        item.setWorkerId(pps.get(0).getWorkerId());
                        item.setStatus(pps.get(0).getStatus());
                        item.setFinishDt(pps.get(0).getFinishDt());
                    }
                }
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    protected void onResume() {
        super.onResume();
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        isNFC_support = !(nfcAdapter == null || !nfcAdapter.isEnabled());
        if (isNFC_support) {
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
                    mTechLists);
            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
                // 注意这个if中的代码几乎不会进来，因为刚刚在上一行代码开启了监听NFC连接，下一行代码马上就收到了NFC连接的intent，这种几率很小
                // 处理该intent
                String result = processIntent(getIntent());
                checkResult(result);
            }
        }
        if(Utils.isNetworkConnected(PatrolDetailActivity.this)) {
            getTaskDetail();
        }else {
            List<Patrol> lll = LitePal.where("sid = ?",patrolDetail.getSid()).find(Patrol.class);
            if (lll.size()>0) {
                Patrol pp = lll.get(0);
                points = pp.getPatrolRecordPatrolRoutes();
                updateList();
            }
        }
    }

    private void checkResult(String result) {
        Boolean ishave = false;
        for (int i = 0; i < points.size(); i++) {
            if (result.equals(points.get(i).getSid())) {
                ishave = true;
                sel_point = points.get(i);
//                points.get(i).setStatus("2");
            }
        }
        if (ishave) {
            if (sel_point.getPointType().equals("point")||sel_point.getPointType().equals("P")) {
                PatrolPointDetailActivity.actionStart(PatrolDetailActivity.this, sel_point, sel_point.getTaskId(), sel_point.getType());
            } else if (sel_point.getPointType().equals("equipment")||sel_point.getPointType().equals("E")) {
                PatrolEquDetailActivity.actionStart(PatrolDetailActivity.this, sel_point.getSid(), "", sel_point.getTaskId(), sel_point.getType());
            }
//            PatrolPointDetailActivity.actionStart(PatrolDetailActivity.this, sel_point, patrolDetail.getId(), sel_point.getTaskType());
        } else {
            noThisPoint();
        }
    }

    private void noThisPoint() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new SweetAlertDialog(PatrolDetailActivity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("该巡检点不在任务中，请确认后再扫描！")
                        .show();
            }
        });
    }

    /**
     * 获取tab标签中的内容
     *
     * @param intent
     * @return
     */
    @SuppressLint("NewApi")
    private String processIntent(Intent intent) {
        Parcelable[] rawmsgs = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawmsgs != null) {
            NdefMessage msg = (NdefMessage) rawmsgs[0];
            NdefRecord[] records = msg.getRecords();
            String resultStr = new String(records[0].getPayload());
            return resultStr;
        } else {
            return "error";
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null && nfcAdapter.isEnabled()) {
            // 当前Activity如果不在手机的最前端，就停止NFC设备连接的监听
            stopNFC_Listener();
        }
    }

    private void stopNFC_Listener() {
        // 停止监听NFC设备是否连接
        nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        super.onNewIntent(intent);
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            String result = processIntent(intent);
            checkResult(result);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                if (content.equals(sel_point.getSid())){
                    if (sel_point.getPointType().equals("point")) {
                        PatrolPointDetailActivity.actionStart(PatrolDetailActivity.this, sel_point, sel_point.getTaskId(), sel_point.getType());
                    } else if (sel_point.getPointType().equals("equipment")) {
                        PatrolEquDetailActivity.actionStart(PatrolDetailActivity.this, sel_point.getSid(), "", sel_point.getTaskId(), sel_point.getType());
                    }
                }else {
                    showNotice("二维码不匹配");
                }
            }
        }
    }

    private void showNotice(String st) {
        if (!PatrolDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolDetailActivity.this,SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText(st)
                            .setConfirmText("确定")
                            .show();
                }
            });
        }
    }
}
