package com.sipai.jspatrol.Patrol;

import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
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.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.speech.tts.TextToSpeech;
import android.text.Html;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.sipai.jspatrol.Bean.Patrol;
import com.sipai.jspatrol.Fault.NewFaultActivity;
import com.sipai.jspatrol.utils.Global.GlobalVal;
import com.sipai.jspatrol.Bean.PatrolPointContent;
import com.sipai.jspatrol.Bean.FileForDL;
import com.sipai.jspatrol.Bean.InputPoint;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Bean.ProPatrolPoint;
import com.sipai.jspatrol.Patrol.patrolInfoAdapter.PatrolEqu;
import com.sipai.jspatrol.Patrol.patrolInfoAdapter.PatrolInfoEquAdapter;
import com.sipai.jspatrol.Patrol.patrolInfoAdapter.PatrolInfoMeasurePointAdapter;
import com.sipai.jspatrol.ProMonitoring.MeasurePointsAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PatrolPointDetailActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
    private String pointid;
    private String taskId;
    private String taskType;
    private ProPatrolPoint sel_point;
    private LinearLayoutManager manager,equManager;
    private List<Measuringpoint> measuringpoints = new ArrayList<>();
    private PatrolInfoMeasurePointAdapter pointAdapter;
    private FileForDLAdapter fileForDLAdapter;
    private PatrolInfoEquAdapter equAdapter;
    private List<InputPoint> points = new ArrayList<>();
    private EditMPointAdapter mAdapter;
    private LinearLayoutManager editManager;
    private List<FileForDL> fileForDLs = new ArrayList<>();
    private List<PatrolPointContent> ppcs = new ArrayList<>();
    private final int POINTINFO=2;
    private String sel_content = "";
    private TextView tv_content;
    private TextToSpeech tts;
    private String ttstext="";//存储tts播放内容
    private List<PatrolEqu> equs = new ArrayList<>();
    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private boolean isNFC_support = false;
    private TextView tv_point_detail_title;
    private RecyclerView rc_file;
    private RecyclerView rc_edit_point;
    private RecyclerView rc_equs;
    private TextView tv_point,tv_edit_point,tv_equ;
    private Button btn_sub_point;
    private SweetAlertDialog pDialog;
    private TextView tv_file_count;
    private RecyclerView rc_content;
    private LinearLayoutManager contentManager;
    private PatrolPointContentSelectorAdapter contentSelectorAdapter;
    private String markOfSub = "0";//标记上传进行到的步骤，0为填报内容（测量点），1为巡检内容，2为巡检点状态
    private RecyclerView rc_point;
    private LinearLayoutManager autoManager;
    private MeasurePointsAdapter autoAdapter;
    private LinearLayout ll_sub_fault;
    private LinearLayout ll_auto_point,ll_do_content,ll_edit_point,ll_equ;

    public static void actionStart(Context context , ProPatrolPoint point, String taskid,String taskType){
        Intent intent = new Intent(context,PatrolPointDetailActivity.class);
        intent.putExtra("point",point);
        intent.putExtra("taskid",taskid);
        intent.putExtra("tasktype",taskType);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patrol_point_detail);
        init();
        initView();
        if (Utils.isNetworkConnected(PatrolPointDetailActivity.this)) {
            if (pointid != null && pointid.length() > 0) {
                getAutoPoint();
                getPointDetail();
                getPointPatrolContent();
            }
        }else {
            measuringpoints = new ArrayList<>();
            updateAutoPoint();
            points = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointid,taskId,"").find(InputPoint.class);
            updateEditPoints();
            ppcs = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointid,taskId,"").find(PatrolPointContent.class);
            updatePC();
        }
    }

    @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());
                if(result!=null && !result.equals("error")){
                    showinfobyNFC(result);
                }
            }
        }
        if (Utils.isNetworkConnected(PatrolPointDetailActivity.this)) {
            if (pointid != null && pointid.length() > 0) {
                getPointEquList();
            }
        }else {
            equs = LitePal.where("patrolPointId = ? and patrolRecordId = ?",pointid,taskId).find(PatrolEqu.class);
            UpdateEquUI();
        }
    }

    @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);
            if(result!=null && !result.equals("error")){
                showinfobyNFC(result);
            }
        }
    }
    private void showinfobyNFC(String st){
        int ishave = 0;
        if (ishave>0){
            Intent intent = new Intent(PatrolPointDetailActivity.this,PatrolEquDetailActivity.class);
            intent.putExtra("id",st);
            intent.putExtra("pointId",pointid);
            intent.putExtra("taskId",taskId);
            startActivity(intent);
        }else {
            NoThisEqu();
        }
    }

    private void NoThisEqu() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new SweetAlertDialog(PatrolPointDetailActivity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("该区域巡检列表中无此设备！")
                        .setConfirmText("确定")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                            }
                        }).show();
            }
        });
    }

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

    /**
     * 获取巡检点下自动点
     */
    private void getAutoPoint() {
        HashMap<String,String> map = new HashMap<>();
        map.put("type","auto");
        map.put("patrolPointId",sel_point.getSid());
        map.put("unitId",mBizid);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer,MethodURL.GetPatrolPointAutoPoint_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ErrorDialog("巡检点下测量点列表获取失败，请重试","auto");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("code")&&res.contains("result")) {
                    measuringpoints = parseMeasuringPoints(res);
                }else {
                    measuringpoints = new ArrayList<>();
                }
                updateAutoPoint();
            }
        });
    }

    /**
     * 更新自动点列表
     */
    private void updateAutoPoint() {
        if (!PatrolPointDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    autoAdapter = new MeasurePointsAdapter(PatrolPointDetailActivity.this,measuringpoints);
                    rc_point.setAdapter(autoAdapter);
                    if (measuringpoints.size()==0){
                        ll_auto_point.setVisibility(View.GONE);
                    }else {
                        ll_auto_point.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    /**
     * 解析自动点
     * @param response
     * @return
     */
    private List<Measuringpoint> parseMeasuringPoints(String response) {
        List<Measuringpoint> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray aNews = new JSONArray(jsonObject.getString("result"));
            for (int i=0;i<aNews.length();i++){
                Measuringpoint point = new Measuringpoint();
                point.setSid(aNews.getJSONObject(i).opt("id").toString());
                point.setName(aNews.getJSONObject(i).opt("parmname").toString());
                point.setCvalue(aNews.getJSONObject(i).opt("parmvalue").toString());
                point.setUnit(aNews.getJSONObject(i).opt("unit").toString());
                point.setType(aNews.getJSONObject(i).opt("signaltype").toString());
                point.setValuemeaning(aNews.getJSONObject(i).optString("valuemeaning"));
                list.add(point);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 巡检点下设备列表
     */
    private void getPointEquList() {
        HashMap<String,String> map = new HashMap<>();
        map.put("patrolRecordId",sel_point.getTaskId());
        map.put("patrolPointId",sel_point.getSid());
        map.put("unitId",mBizid);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer,MethodURL.GetPatrolPointEquList_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ErrorDialog("巡检点下设备列表获取失败，请重试","equs");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.i("Equ", "onResponse: "+res);
                if (res.contains("code")&&res.contains("result")){
                    equs = parsePatrolEqu(res);
                }
                UpdateEquUI();
            }
        });
    }

    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();
                item.setEquipmentId(array.getJSONObject(i).optString("equipmentId"));
                item.setEquipmentName(array.getJSONObject(i).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(array.getJSONObject(i).optString("equipmentCardId"));
                item.setManufacturers(array.getJSONObject(i).optString("equipmentManufacturer"));
                item.setType(sel_point.getType());
                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 UpdateEquUI() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (equs.size()==0){
                    ll_equ.setVisibility(View.GONE);
                }else {
                    ll_equ.setVisibility(View.VISIBLE);
                }
                equManager = new LinearLayoutManager(PatrolPointDetailActivity.this);
                rc_equs.setLayoutManager(equManager);
                equAdapter = new PatrolInfoEquAdapter(equs,PatrolPointDetailActivity.this);
                rc_equs.setAdapter(equAdapter);
            }
        });
    }


    /**
     * 巡检点执行内容详情
     */
    private void getPointPatrolContent() {
        HashMap<String,String> map = new HashMap<>();
        map.put("patrolRecordId",sel_point.getTaskId());
        map.put("patrolPointId",sel_point.getSid());
        map.put("type",sel_point.getType());
        map.put("equipmentId","");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer,MethodURL.GetPatrolPointContent_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ErrorDialog("巡检点执行内容获取失败，请重试","content");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res!=null&&!res.isEmpty()){
                    ppcs = parseContent(res);
                }
                updatePC();
            }
        });
    }

    private void updatePC() {
        if (!PatrolPointDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ppcs.size()==0){
                        ll_do_content.setVisibility(View.GONE);
                    }else {
                        ll_do_content.setVisibility(View.VISIBLE);
                    }
                    contentSelectorAdapter = new PatrolPointContentSelectorAdapter(ppcs,PatrolPointDetailActivity.this);
                    rc_content.setAdapter(contentSelectorAdapter);
                }
            });
        }
    }

    private List<PatrolPointContent> parseContent(String response) {
        List<PatrolPointContent> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = new JSONArray(jsonObject.optString("result"));
            if (jsonArray.length()>0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    PatrolPointContent item = new PatrolPointContent();
                    item.setSid(jsonArray.getJSONObject(i).optString("id"));
                    item.setContents(jsonArray.getJSONObject(i).optString("contents"));
                    item.setContentsDetail(jsonArray.getJSONObject(i).optString("contentsDetail"));
                    item.setStatus(jsonArray.getJSONObject(i).optString("status"));
                    list.add(item);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 巡检点下填报内容
     */
    private void getPointDetail() {
        HashMap<String,String> map = new HashMap<>();
        map.put("patrolRecordId",sel_point.getTaskId());
        map.put("patrolPointId",sel_point.getSid());
        map.put("unitId",mBizid);
        map.put("type",sel_point.getType());
        map.put("equipmentId","");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer,MethodURL.GetPatrolPointEditPoint_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ErrorDialog("手动测量点列表获取失败，请重试","point");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    JSONArray jsonArray = new JSONArray(jsonObject.optString("result"));
                    if (jsonArray.length()>0) {
                        points = parsePoint(res);
                    }else {
//                        ErrorDialog("手动测量点列表获取失败，请重试","point");
                        points = new ArrayList<>();
                    }
                    updateEditPoints();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void updateEditPoints() {
        if (!PatrolPointDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    editManager = new LinearLayoutManager(PatrolPointDetailActivity.this);
                    rc_edit_point.setLayoutManager(editManager);
                    mAdapter = new EditMPointAdapter(points,PatrolPointDetailActivity.this);
                    rc_edit_point.setAdapter(mAdapter);
                    if (points.size()==0){
                        ll_edit_point.setVisibility(View.GONE);
                    }else {
                        ll_edit_point.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    private void ErrorDialog(String content,String type) {
        if (!PatrolPointDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolPointDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText(content)
                            .setConfirmText("重试")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    if (type.equals("content")){
                                        getPointPatrolContent();
                                    }else if (type.equals("point")){
                                        getPointDetail();
                                    }else if (type.equals("equs")){
                                        getPointEquList();
                                    }else if(type.equals("auto")){
                                        getAutoPoint();
                                    }
                                }
                            })
                            .setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .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","");
        sel_point = (ProPatrolPoint) getIntent().getSerializableExtra("point");
        if (sel_point.getSid()!=null&&sel_point.getSid().length()>0){
            pointid = sel_point.getSid();
        }
        taskId = getIntent().getStringExtra("taskid");
        taskType = getIntent().getStringExtra("tasktype");
    }

    private void initView() {
        TextView tv_title = findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText("巡检点详情");
        ImageView btn_back = findViewById(R.id.moudle_back_title_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#419DE4"));
        pDialog.setTitleText("数据获取中...");
        pDialog.setCancelable(true);
        pDialog.setCanceledOnTouchOutside(true);
        ll_auto_point = findViewById(R.id.moudle_patrolinfo_ll_auto_point);
        ll_do_content = findViewById(R.id.moudle_patrolinfo_ll_do_content);
        ll_edit_point = findViewById(R.id.moudle_patrolinfo_ll_edit_point);
        ll_equ = findViewById(R.id.moudle_patrolinfo_ll_equ);
        tv_point = findViewById(R.id.moudle_patrol_point_detail_tv_file);
        tv_point.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pointid!=null&&pointid.length()>0){
                    getPointDetail();
                }
            }
        });
        tv_edit_point = findViewById(R.id.moudle_patrol_point_detail_tv_edit_point);
        tv_edit_point.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pointid!=null&&pointid.length()>0){
                    getPointDetail();
                }
            }
        });
        ll_sub_fault = findViewById(R.id.moudle_patrol_point_detail_ll_sub_fault);
        ll_sub_fault.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NewFaultActivity.actionStart(PatrolPointDetailActivity.this,sel_point.getSid(),taskId,sel_point.getTaskId());
            }
        });
        rc_point = findViewById(R.id.moudle_patrolinfo_rc_auto_point);
        autoManager = new LinearLayoutManager(this);
        rc_point.setLayoutManager(autoManager);
        autoAdapter = new MeasurePointsAdapter(PatrolPointDetailActivity.this,measuringpoints);
        rc_point.setAdapter(autoAdapter);

        rc_content = findViewById(R.id.moudle_patrolinfo_rc_content);
        contentManager = new LinearLayoutManager(PatrolPointDetailActivity.this);
        rc_content.setLayoutManager(contentManager);
        contentSelectorAdapter = new PatrolPointContentSelectorAdapter(ppcs,PatrolPointDetailActivity.this);
        rc_content.setAdapter(contentSelectorAdapter);

        tv_equ = findViewById(R.id.moudle_patrol_point_detail_tv_equ);
        tv_equ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pointid!=null&&pointid.length()>0) {
                    getPointEquList();
                }
            }
        });
        btn_sub_point = findViewById(R.id.moudle_patrol_point_detail_btn_sub_point);
        btn_sub_point.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isNetworkConnected(PatrolPointDetailActivity.this)) {
                    if (markOfSub.equals("0")) {
                        subValue();
                    } else if (markOfSub.equals("1")) {
                        subContent();
                    } else if (markOfSub.equals("2")) {
                        subThisPatrolPoint();
                    }
                }else {
                    List<Patrol> lll = LitePal.where("sid = ?",taskId).find(Patrol.class);
                    if (lll.size()>0) {
                        saveOfflineInfo();
                    }else {
                        noOfflineData();
                    }
                }
            }
        });
        tv_point_detail_title = findViewById(R.id.moudle_patrol_point_detail_tv_point_name);
        tv_point_detail_title.setText(sel_point.getName());
        tv_content = findViewById(R.id.moudle_patrol_point_detail_tv_content);
        if (sel_content.length()>0){
            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {
                tv_content.setText(Html.fromHtml(sel_content,Html.FROM_HTML_MODE_COMPACT));
            }else {
                tv_content.setText(Html.fromHtml(sel_content));
            }
        }else {
            tv_content.setText("查看巡检点区域测量点及设备！");
        }
        rc_file = findViewById(R.id.moudle_patrol_point_detail_rc_file);
        manager = new LinearLayoutManager(PatrolPointDetailActivity.this);
        rc_file.setLayoutManager(manager);
        fileForDLAdapter = new FileForDLAdapter(PatrolPointDetailActivity.this, fileForDLs, new FileForDLAdapter.onRcViewItemClick() {
            @Override
            public void onItemClick(View v, int position) {
                checkFile(fileForDLs.get(position));
            }
        });
        rc_file.setAdapter(fileForDLAdapter);
        tv_file_count = findViewById(R.id.moudle_patrol_point_detail_tv_file_count);
        tv_file_count.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (rc_file.getVisibility()==View.GONE){
                    rc_file.setVisibility(View.VISIBLE);
                }else {
                    rc_file.setVisibility(View.GONE);
                }
            }
        });
        rc_edit_point = findViewById(R.id.moudle_patrol_point_detail_rc_edit_point);
        editManager = new LinearLayoutManager(PatrolPointDetailActivity.this);
        rc_edit_point.setLayoutManager(editManager);
        mAdapter = new EditMPointAdapter(points,PatrolPointDetailActivity.this);
        rc_edit_point.setAdapter(mAdapter);

        rc_equs = findViewById(R.id.moudle_patrol_point_detail_rc_equ);
        equManager = new LinearLayoutManager(PatrolPointDetailActivity.this);
        rc_equs.setLayoutManager(equManager);
        equAdapter = new PatrolInfoEquAdapter(equs,PatrolPointDetailActivity.this);
        rc_equs.setAdapter(equAdapter);
        tts = new TextToSpeech(this, this);
        //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 noOfflineData() {
        if (!PatrolPointDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolPointDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText("网络不可用，且本地未检测到本条任务离线数据，无法进行离线保存！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private void saveOfflineInfo() {
        //保存执行内容
        for (int i = 0; i < ppcs.size(); i++) {
            ppcs.get(i).setStatus(GlobalVal.Status_Issue);
            ppcs.get(i).updateAll("sid = ?",ppcs.get(i).getSid());
        }
        Map<Integer, Boolean> map1 = contentSelectorAdapter.getMap();
        for (int i = map1.size()-1; 0<=i; i--) {
            if (map1.get(i)) {
                Log.d("TAG", "你选了第：" + i + "项");
//						sel_users.add(users.get(i));
                ppcs.get(i).setStatus(GlobalVal.Status_Finish);
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                ppcs.get(i).setFinishDt(format.format(date));
                ppcs.get(i).updateAll("sid = ?",ppcs.get(i).getSid());
            }
        }
        List<PatrolPointContent> contents = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointid,taskId,"").find(PatrolPointContent.class);
        //保存填报内容
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i=0;i<points.size();i++){
            points.get(i).setFinishDt(format.format(date));
            points.get(i).updateAll("sid = ? and patrolRecordId = ?",points.get(i).getSid(),points.get(i).getPatrolRecordId());
        }
//        List<InputPoint> pts = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointid,taskId,"").find(InputPoint.class);
        //保存巡检点状态与提交时间
        sel_point.setFinishDt(format.format(date));
        sel_point.setWorkerId(mUserid);
        sel_point.setWorkerName(mCaption);
        sel_point.setStatus(GlobalVal.Status_Finish);
        sel_point.updateAll("sid = ? and resultId = ?",sel_point.getSid(),sel_point.getResultId());
        List<ProPatrolPoint> list = LitePal.where("sid = ?",sel_point.getSid()).find(ProPatrolPoint.class);
        showSaveSuccessDialog();
    }

    private void showSaveSuccessDialog() {
        if (!PatrolPointDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolPointDetailActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("成功")
                            .setContentText("保存成功！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    finish();
                                }
                            }).show();
                }
            });
        }
    }

    /**
     * 上传执行内容
     */
    private void subContent() {
        for (int i = 0; i < ppcs.size(); i++) {
            ppcs.get(i).setStatus(GlobalVal.Status_Issue);
        }
        Map<Integer, Boolean> map1 = contentSelectorAdapter.getMap();
        for (int i = map1.size()-1; 0<=i; i--) {
            if (map1.get(i)) {
                Log.d("TAG", "你选了第：" + i + "项");
                ppcs.get(i).setStatus(GlobalVal.Status_Finish);
            }
        }
        Gson gson = new Gson();
        String json = "{\"re1\":"+gson.toJson(ppcs)+"}";
        HashMap<String,String> map = new HashMap<>();
        map.put("isLimited","true");
        map.put("patrolRecordId",sel_point.getTaskId());
        map.put("patrolPointId",sel_point.getSid());
        map.put("json",json);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer,MethodURL.SubPatrolPointContent_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                ErrorDialog("巡检点下测量点列表获取失败，请重试","auto");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    if (jsonObject.opt("code").toString().equals("1")){
                        markOfSub = "2";
                        subThisPatrolPoint();
                    }else {
                        markOfSub = "1";
                        subError();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    markOfSub = "1";
                    subError();
                }
            }
        });
    }

    private void subError() {
        if (!PatrolPointDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolPointDetailActivity.this,SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText("上传失败，请重试")
                            .setConfirmText("重试")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    subContent();
                                }
                            })
                            .setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .show();
                }
            });
        }
    }


    /**
     * 上传巡检点内所有手动点
     */
    private void subValue() {
        Gson gson = new Gson();
        String json = "{\"re1\":"+gson.toJson(points)+"}";
        subAllPoints(json);
    }

    /**
     * 上传所有测量点
     * @param json
     */
    private void subAllPoints(String json) {
        HashMap<String,String> map = new HashMap<>();
        map.put("patrolRecordId",sel_point.getTaskId());
        map.put("patrolPointId",sel_point.getSid());
        map.put("json",json);
        map.put("isLimited","true");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer,MethodURL.SubPatrolPointEditPoint_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                ErrorDialog("巡检点下测量点列表获取失败，请重试","auto");
                failDailog(json);
            }

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

    /**
     * 上传巡检点巡检状态
     */
    private void subThisPatrolPoint() {
        HashMap<String,String> map = new HashMap<>();
        map.put("id",sel_point.getResultId());
        map.put("patrolRecordId",sel_point.getTaskId());
        map.put("isLimited","true");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer,MethodURL.SubPatrolPointStatus_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                ErrorDialog("巡检点下测量点列表获取失败，请重试","auto");
                confirmFailDailog("提交失败！");
            }

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

    }

    private void subPatrolPointStatus() {
        HashMap<String,String> map = new HashMap<>();
        map.put("patrolRecordId",sel_point.getTaskId());
        map.put("patrolPointId",sel_point.getSid());
        map.put("userId",mUserid);
        map.put("isLimited","true");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer, MethodURL.SubPatrolPointPS_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("code")&&res.contains("result")){
                    try {
                        JSONObject jsonObject = new JSONObject(res);
                        if (jsonObject.get("code").toString().equals("1")){
                            successDialog();
                        }else {
                            markOfSub = "3";
                            if (jsonObject.optString("msg").contains("时间内")) {
                                subStatusFail(jsonObject.optString("msg"));
                            }else {
                                subStatusFail("提交失败！");
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else {
                    markOfSub = "3";
                }
            }
        });
    }

    private void subStatusFail(String s) {
        if (!PatrolPointDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolPointDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText(s)
                            .setConfirmText("重试")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    subPatrolPointStatus();
                                }
                            })
                            .setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .show();
                }
            });
        }
    }

    private void failDailog(String json) {
        if (!PatrolPointDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolPointDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText("测量点信息提交失败，请重试！")
                            .setConfirmText("重试")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    subAllPoints(json);
                                }
                            })
                            .setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .show();
                }
            });
        }
    }

    private void confirmFailDailog(String s) {
        if (!PatrolPointDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolPointDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText(s)
                            .setConfirmText("重试")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    subThisPatrolPoint();
                                }
                            })
                            .setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .show();
                }
            });
        }
    }

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



    /**
     * 解析手动测量点
     * @param response
     * @return
     */
    private List<InputPoint> parsePoint(String response) {
        List<InputPoint> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = new JSONArray(jsonObject.optString("result"));
            for (int i=0;i<jsonArray.length();i++){
                InputPoint item = new InputPoint();
                JSONObject js = new JSONObject(jsonArray.getJSONObject(i).opt("mPoint").toString());
                item.setSid(jsonArray.getJSONObject(i).optString("id"));
                item.setPid(jsonArray.getJSONObject(i).optString("id"));
                item.setAlarmmax(js.optString("alarmmax"));
                item.setAlarmmin(js.optString("alarmmin"));
                item.setBiztype(js.optString("biztype"));
                item.setValuemeaning(js.optString("valuemeaning"));
                item.setPatrolRecordId(sel_point.getPatrolRecordId());
//                item.setId(js.opt("id").toString());
                item.setMeasuredt(js.optString("measuredt"));
                item.setMpointcode(js.optString("mpointcode"));
                item.setParmname(js.optString("parmname"));
                item.setParmvalue(jsonArray.getJSONObject(i).optString("mpvalue"));
                item.setSignalType(js.optString("signaltype"));
                item.setSql(js.optString("sql"));
                item.setUnit(js.optString("unit"));
                item.setWhere(js.optString("where"));
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 检测文件
     * @param fileForDL
     */
    private void checkFile(FileForDL fileForDL) {
        Uri uri = Uri.parse(mServer+"base/downloadFile.do?key="+fileForDL.getId()+"&tbName=tb_doc_file");
        Intent intent = new Intent(Intent.ACTION_VIEW,uri);
        startActivity(intent);
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS){
            int result = tts.setLanguage(Locale.CHINESE);
            if (result == TextToSpeech.LANG_MISSING_DATA||result == TextToSpeech.LANG_NOT_SUPPORTED){
//                Toast.makeText(PatrolPointDetailActivity.this, "数据不支持", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tts.stop();
        tts.shutdown();
    }
}
