package com.sipai.jspatrol.Patrol;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
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 android.widget.Toast;

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

import com.google.gson.Gson;
import com.sipai.jspatrol.Patrol.patrolInfoAdapter.PatrolEqu;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.Global.GlobalVal;
import com.sipai.jspatrol.Bean.PatrolPointContent;
import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.InputPoint;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.ProMonitoring.MeasurePointsAdapter;
import com.sipai.jspatrol.R;
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.Map;

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

/**
 * 工艺巡检中设备详情
 */
public class PatrolEquDetailActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_equipmentname,tv_equipmentcardid,tv_equipmentclass,tv_equipmentlevel,tv_company,tv_equipmentmanufacturer,tv_area;
    private TextView tv_hand,tv_auto;
    private String id;
    private EquList equ;
    private List<InputPoint> points = new ArrayList<>();
    private List<Measuringpoint> autoPoints = new ArrayList<>();
    private SweetAlertDialog pDialog;
    private RecyclerView rc_edit_point;
    private EditMPointAdapter mAdapter;
    private LinearLayoutManager editManager;
    private RecyclerView rc;
    private MeasurePointsAdapter pointlistadapter;
    private LinearLayoutManager manager;
    private Button btn_sub;
    private String st_status;
    private String pointId = "";//巡检点id
    private String taskId = "";//巡检任务id
    private String type;
    private static String[] ar_status = {"封存","启用","故障异常"};
    private List<PatrolPointContent> ppcs = new ArrayList<>();//巡检内容列表
    private RecyclerView rc_content;
    private LinearLayoutManager contentManager;
    private PatrolPointContentSelectorAdapter contentSelectorAdapter;
    private int subResult = 0;
    private LinearLayout ll_do_content;

    public static void actionStart(Context context,String id,String patrolpointid,String patroltaskid,String type){
        Intent intent = new Intent(context,PatrolEquDetailActivity.class);
        intent.putExtra("id",id);
        intent.putExtra("pointId",patrolpointid);
        intent.putExtra("taskId",patroltaskid);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patrol_equ_detail);
        init();
        initView();
        if (Utils.isNetworkConnected(PatrolEquDetailActivity.this)) {
            getEquDetail();
            getEquPatrolEdtPoint();
            getEquPatrolContent();
        }else {
            List<PatrolEqu> equs = LitePal.where("equipmentId = ?",id).find(PatrolEqu.class);
            if (equs.size()>0){
                tv_equipmentname.setText(equs.get(0).getEquipmentName());
                tv_equipmentcardid.setText(equs.get(0).getEquipmentCardId());
            }
            points = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointId,taskId,id).find(InputPoint.class);
            ppcs = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointId,taskId,id).find(PatrolPointContent.class);
            UpDateUI();
            UpDateList();
        }
    }

    /**
     * 设备下巡检内容
     */
    private void getEquPatrolContent() {
        HashMap<String,String> map = new HashMap<>();
        map.put("equipmentId",id);
        map.put("patrolPointId",pointId);
        map.put("patrolRecordId",taskId);
        map.put("type",type);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer, MethodURL.GetPatrolPointEquDetailPC_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                errorToast(e);
            }

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

    /**
     * 解析执行内容
     * @param response
     * @return
     */
    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);
                }
            }else {
//                ErrorDialog("巡检点执行内容获取失败，请重试","content");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 获取设备下填报内容（手动测量点）
     */
    private void getEquPatrolEdtPoint() {
        HashMap<String,String> map = new HashMap<>();
        map.put("equipmentId",id);
        map.put("patrolPointId",pointId);
        map.put("patrolRecordId",taskId);
        map.put("unitId",mBizid);
        map.put("type",type);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer, MethodURL.GetPatrolPointEquDetailEC_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                errorToast(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.i("Equ", "onResponse: "+res);
                if (res!=null&&!res.isEmpty()&&res.contains("result")){
                    points = parsePoint(res);
                }else {
                    points = new ArrayList<>();
                }
                UpDateList();
            }
        });
    }

    /**
     * 解析手动测量点
     * @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).optString("mPoint"));
                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.setId(js.optString("id"));
                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;
    }

    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);
        tv_hand = findViewById(R.id.moudle_patrol_equ_detail_tv_hand);
        tv_auto = findViewById(R.id.moudle_patrol_equ_detail_tv_auto);
        tv_equipmentname = findViewById(R.id.moudle_patrol_equ_detail_tv_equipmentname);
        tv_equipmentcardid = findViewById(R.id.moudle_patrol_equ_detail_tv_equipmentcardid);
        tv_equipmentclass = findViewById(R.id.moudle_patrol_equ_detail_tv_equipmentclass);
        tv_equipmentlevel = findViewById(R.id.moudle_patrol_equ_detail_tv_equipmentlevel);
        tv_company = findViewById(R.id.moudle_patrol_equ_detail_tv_company);
        tv_equipmentmanufacturer = findViewById(R.id.moudle_patrol_equ_detail_tv_equipmentmanufacturer);
        tv_area = findViewById(R.id.moudle_patrol_equ_detail_tv_area);
        ll_do_content = findViewById(R.id.moudle_patrol_equ_detail_ll_do_content);
        rc_edit_point = findViewById(R.id.moudle_patrol_equ_detail_rc_edit_point);
        editManager = new LinearLayoutManager(PatrolEquDetailActivity.this);
        rc_edit_point.setLayoutManager(editManager);
        mAdapter = new EditMPointAdapter(points,PatrolEquDetailActivity.this);
        rc_edit_point.setAdapter(mAdapter);

        rc = findViewById(R.id.moudle_patrol_equ_detail_rc);
        manager = new LinearLayoutManager(PatrolEquDetailActivity.this);
        rc.setLayoutManager(manager);
        pointlistadapter = new MeasurePointsAdapter(PatrolEquDetailActivity.this,autoPoints);
        rc.setAdapter(pointlistadapter);

        rc_content = findViewById(R.id.moudle_patrol_equ_detail_rc_content);
        contentManager = new LinearLayoutManager(PatrolEquDetailActivity.this);
        rc_content.setLayoutManager(contentManager);
        contentSelectorAdapter = new PatrolPointContentSelectorAdapter(ppcs,PatrolEquDetailActivity.this);
        rc_content.setAdapter(contentSelectorAdapter);
        btn_sub = findViewById(R.id.moudle_patrol_equ_detail_btn_sub);
        btn_sub.setOnClickListener(this);
    }

    /**
     * 获取设备详情
     */
    private void getEquDetail() {
        HashMap<String,String> map = new HashMap<>();
        map.put("id",id);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer, MethodURL.GetPatrolPointEquDetail_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                stopRefresh();
                errorToast(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (!PatrolEquDetailActivity.this.isFinishing()){
                    if (res!=null&&!res.isEmpty()&&res.contains("code")){
                        try {
                            JSONObject jsonObject = new JSONObject(res);
                            if (jsonObject.optString("code").equals("1")&&jsonObject.optString("result").length()>10){
                                equ = parseEquInfo(res);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tv_equipmentname.setText(equ.getEquipmentname());
                                        tv_equipmentcardid.setText(equ.getEquipmentcardid());
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                stopRefresh();
            }
        });
    }

    private EquList parseEquInfo(String response) {
        EquList item = new EquList();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = jsonObject.getJSONArray("result");
            JSONObject js = jsonArray.getJSONObject(0);
            item.setEquipmentname(js.optString("equipmentname"));
            item.setEquipmentcardid(js.optString("equipmentcardid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return item;
    }

    /**
     * 解析自动测量点
     * @param response
     * @return
     */
    private List<Measuringpoint> getAutoPoints(String response) {
        List<Measuringpoint> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray aNews = new JSONArray(jsonObject.getString("content3"));
            if (aNews != null && aNews.length() > 0) {
                for (int i = 0; i <aNews.length(); i++) {
                    Measuringpoint item = new Measuringpoint();
                    item.setSid(aNews.getJSONObject(i).optString("id"));
                    item.setName(aNews.getJSONObject(i).optString("parmname"));
                    item.setUnit(aNews.getJSONObject(i).optString("unit"));
                    item.setCvalue(aNews.getJSONObject(i).optString("parmvalue"));
                    item.setType(aNews.getJSONObject(i).optString("signalType"));
                    item.setScadacode(aNews.getJSONObject(i).optString("id"));
                    item.setAlarmmax(aNews.getJSONObject(i).optString("alarmmax"));
                    item.setAlarmmin(aNews.getJSONObject(i).optString("alarmmin"));
                    list.add(item);
                }
            }
        } catch (JSONException ex) {
            Log.e("JSON Error: ", ex.toString());
        }
        return list;
    }

    private void UpDateAutoList() {
        if (!PatrolEquDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (autoPoints.size()>0) {
                        tv_auto.setVisibility(View.GONE);
                        manager = new LinearLayoutManager(PatrolEquDetailActivity.this);
                        rc.setLayoutManager(manager);
                        pointlistadapter = new MeasurePointsAdapter(PatrolEquDetailActivity.this,autoPoints);
                        rc.setAdapter(pointlistadapter);
                    }else {
                        tv_auto.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    private void errorToast(final Throwable error) {
        if (!PatrolEquDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(PatrolEquDetailActivity.this, "失败："+error.toString(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void stopRefresh() {
        if (!PatrolEquDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    refreshLayout.setRefreshing(false);
                }
            });
        }
    }


    private void UpDateList() {
        if (!PatrolEquDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    refreshLayout.setRefreshing(false);
                    if (points.size()>0) {
                        tv_hand.setVisibility(View.GONE);
                        mAdapter = new EditMPointAdapter(points,PatrolEquDetailActivity.this);
                        rc_edit_point.setAdapter(mAdapter);
                    }else {
                        tv_hand.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

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

    /**
     * 解析设备详情
     * @param response
     * @return
     */
    private EquList getDetail(String response) {
        EquList item = new EquList();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray content = new JSONArray(jsonObject.optString("content1"));
            if (content.length()>0) {
                item.setAreaid(content.getJSONObject(0).optString("areaid"));
                item.setAssetclassid(content.getJSONObject(0).optString(""));
                item.setBizid(content.getJSONObject(0).optString(""));
                if (content.getJSONObject(0).get("company") != null && !content.getJSONObject(0).get("company").toString().equals("null")) {
                    JSONObject company = new JSONObject(content.getJSONObject(0).optString("company"));
                    item.setCompany(company.optString("name"));
                } else {
                    item.setCompany("");
                }
                if (content.getJSONObject(0).get("equipmentClass") != null && !content.getJSONObject(0).get("equipmentClass").toString().equals("null")) {
                    JSONObject equClass = new JSONObject(content.getJSONObject(0).optString("equipmentClass"));
                    item.setEquipmentClass(equClass.optString("name"));
                } else {
                    item.setEquipmentClass("");
                }
                if (content.getJSONObject(0).get("equipmentLevel") != null && !content.getJSONObject(0).get("equipmentLevel").toString().equals("null")) {
                    JSONObject equLevel = new JSONObject(content.getJSONObject(0).optString("equipmentLevel"));
                    item.setEquipmentLevel(equLevel.optString("levelname"));
                } else {
                    item.setEquipmentLevel("");
                }
                if (content.getJSONObject(0).get("equipmentSpecification") != null && !content.getJSONObject(0).get("equipmentSpecification").toString().equals("null")) {
                    JSONObject equipmentSpecification = new JSONObject(content.getJSONObject(0).optString("equipmentSpecification"));
                    item.setEquipmentSpecification(equipmentSpecification.optString("name"));
                } else {
                    item.setEquipmentSpecification("");

                }
                if (content.getJSONObject(0).get("equipmentTypeNumber") != null && !content.getJSONObject(0).get("equipmentTypeNumber").toString().equals("null")) {
                    JSONObject equipmentTypeNumber = new JSONObject(content.getJSONObject(0).optString("equipmentTypeNumber"));
                    item.setEquipmentTypeNumber(equipmentTypeNumber.optString("name"));
                } else {
                    item.setEquipmentTypeNumber("");
                }
                item.setEquipmentcardid(content.getJSONObject(0).optString("equipmentcardid"));
                item.setEquipmentclassid(content.getJSONObject(0).optString("equipmentclassid"));
                item.setEquipmentlevelid(content.getJSONObject(0).optString("equipmentlevelid"));
                item.setEquipmentmanufacturer(content.getJSONObject(0).optString("equipmentmanufacturer"));
                item.setEquipmentname(content.getJSONObject(0).optString("equipmentname"));
                item.setEquipmentstatus(content.getJSONObject(0).optString("equipmentstatus"));
                item.setId(content.getJSONObject(0).optString("id"));
                item.setLeavefactorynumber(content.getJSONObject(0).optString("leavefactorynumber"));
                item.setMajorparameter(content.getJSONObject(0).optString("majorparameter"));
                item.setProductiondate(content.getJSONObject(0).optString("productiondate"));
                item.setTotaltime(content.getJSONObject(0).optString("totaltime").toString());
                if (content.getJSONObject(0).optString("equipmentstatus").equals("0")) {
                    item.setEquipmentstatus("禁用");
                } else if (content.getJSONObject(0).optString("equipmentstatus").equals("1")) {
                    item.setEquipmentstatus("启用");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return item;
    }

    /**
     * 初始化
     */
    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", "");
        id = getIntent().getStringExtra("id");
        token = sharedPre.getString("token","");
        type = getIntent().getStringExtra("type");
        if (getIntent().getStringExtra("pointId")!=null&&!getIntent().getStringExtra("pointId").isEmpty()){
            pointId = getIntent().getStringExtra("pointId");
        }
        if (getIntent().getStringExtra("taskId")!=null&&!getIntent().getStringExtra("taskId").isEmpty()){
            taskId = getIntent().getStringExtra("taskId");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.moudle_patrol_equ_detail_btn_sub:
                if (subResult!=2) {
                    subResult = 0;
                    if (Utils.isNetworkConnected(PatrolEquDetailActivity.this)) {
                        subValue();//上传填报内容
                        subContent();//上传巡检内容
                    }else {
                        List<PatrolEqu> equs = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointId,taskId,id).find(PatrolEqu.class);
                        if (equs.size()>0) {
                            saveOfflineInfo();
                        }else {
                            noOfflineData();
                        }
                    }
                }
                break;
        }
    }

    private void noOfflineData() {
        if (!PatrolEquDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolEquDetailActivity.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,id).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 = ?",points.get(i).getSid());
        }
        List<InputPoint> pts = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointId,taskId,id).find(InputPoint.class);
        //保存巡检点状态与提交时间
        List<PatrolEqu> equs = LitePal.where("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointId,taskId,id).find(PatrolEqu.class);
        equs.get(0).setFinishDt(format.format(date));
        equs.get(0).setStatus(GlobalVal.Status_Finish);
        equs.get(0).updateAll("patrolPointId = ? and patrolRecordId = ? and equipmentId = ?",pointId,taskId,id);
        showSaveSuccessDialog();
    }

    private void showSaveSuccessDialog() {
        if (!PatrolEquDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolEquDetailActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("成功")
                            .setContentText("保存成功！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    finish();
                                }
                            }).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("isLimited","true");
        map.put("json",json);
        map.put("patrolPointId",pointId);
        map.put("patrolRecordId",taskId);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer, MethodURL.SubPatrolPointEquDetailEC_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                errorDialog();
            }

            @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();
                            subResult = subResult + 1;
                            if (subResult==2){
                                subEquStatus();
                            }
                        }else {
                            errorDialog();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    /**
     * 上传执行内容
     */
    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 + "项");
//						sel_users.add(users.get(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("json",json);
        map.put("patrolPointId",pointId);
        map.put("patrolRecordId",taskId);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer, MethodURL.SubPatrolPointEquDetailPC_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                errorDialog();
            }

            @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")){
                            subResult = subResult + 1;
                            if (subResult==2){
                                subEquStatus();
                            }
                        }else {
                            errorDialog();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

//        AsyncHttpClient client = new AsyncHttpClient();
//        client.addHeader("token",token);
//        RequestParams params = new RequestParams();
//        params.put("patrolPointId",pointId);
//        params.put("patrolRecordId",taskId);
//        params.put("json",json);
//        client.post(mServer+"SIPAIIS_Patrol/timeEfficiency/patrolContentsRecord/updatePatrolContents.do?", params ,new AsyncHttpResponseHandler() {
//
//            @Override
//            public void onSuccess(String response) {
//                String res = response;
//
//            }
//            @Override
//            public void onFailure(Throwable e) {
//
//            }
//            @Override
//            public void onStart() {
//                super.onStart();
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//            }
//
//        });
    }

    private void subEquStatus() {
        HashMap<String,String> map = new HashMap<>();
        map.put("equipmentId",id);
        map.put("patrolPointId",pointId);
        map.put("patrolRecordId",taskId);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,mServer, MethodURL.SubPatrolPointEquDetailPS_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                errorDialog();
                subResult=0;
            }

            @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 {
                            errorStatusDialog();
                            subResult=0;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else {
                    subResult=0;
                }
            }
        });
    }


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

    private void errorDialog() {
        if (!PatrolEquDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolEquDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText("测量点信息提交失败，请重试！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private void errorStatusDialog() {
        if (!PatrolEquDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(PatrolEquDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText("提交失败，请重试！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

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

    private void pDialogshow() {
        if (!PatrolEquDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!PatrolEquDetailActivity.this.isFinishing()) {
                        pDialog.show();
                    }
                }
            });
        }
    }
}
