package com.bjzc.bhzhgd.activity.sbxdj;


import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bjzc.bhzhgd.DBModel.Djjh;
import com.bjzc.bhzhgd.DBModel.QYDDATABean;
import com.bjzc.bhzhgd.DBModel.XDJJHXZDataBean;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.adapter.ScjhAdapter;
import com.bjzc.bhzhgd.base.BaseFragment;
import com.bjzc.bhzhgd.bean.ScdjjhBean;
import com.bjzc.bhzhgd.bean.StatusInfo2;
import com.bjzc.bhzhgd.contans.Contans;
import com.bjzc.bhzhgd.utils.GsonUtils;
import com.bjzc.bhzhgd.utils.HttpListener;
import com.bjzc.bhzhgd.utils.HttpResponseListener;
import com.bjzc.bhzhgd.utils.SPUtils;
import com.bjzc.bhzhgd.utils.UiUtlis;
import com.bjzc.bhzhgd.weight.toastviewbymyself;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import org.litepal.crud.DataSupport;
import java.text.NumberFormat;
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 androidx.appcompat.app.AlertDialog;

/**
 * 设备巡点检管理-点检点上传
 */
public class DjdscFragment extends BaseFragment {

    ListView lv;
    Button btn_sc;
    Button btn_del;
    TextView tvNodata;

    private View headView;
    private View head;
    private CheckBox cb;
    private ScjhAdapter adapter;
    private RequestQueue queue;
    private int checkedCount = 0, totalCount = 0;//已选中的item中，已检测的数量和总数
    private final String separator = "/";//分割线
    private int selectItem = 0;//选中的item数量
    NumberFormat numberFormat = NumberFormat.getInstance();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //所有的XDJJHXZDataBean数据
    private List<XDJJHXZDataBean> xdjjhxzDataBeanList = new ArrayList<>();
    //当前查询的gwid
    private String gwid = "";
    //点检计划列表数据源
    private List<XDJJHXZDataBean> xdjjhxzDataList = new ArrayList<>();
    //点检计划map
    private Map<String, List<QYDDATABean>> qydDataBeanMap = new HashMap<>();
    public DjdscFragment() {
    }
    public static DjdscFragment newInstance() {
        DjdscFragment fragment = new DjdscFragment();
        return fragment;
    }
    @Override
    protected void initView() {
        lv = view.findViewById(R.id.lv);
        btn_sc = view.findViewById(R.id.btn_sc);
        btn_del = view.findViewById(R.id.btn_del);
        tvNodata = view.findViewById(R.id.tv_nodata);

        btn_sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectItem == 0) {
                    toastviewbymyself.makeText(getActivity(), "请先选中要上传的数据!!!", Toast.LENGTH_LONG).show();
                } else {
                    uploadData();
                }
            }
        });

        btn_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();//删除勾选中的数据
            }
        });

        lv.setEmptyView(tvNodata);
        mActivity = getActivity();
        headView = View.inflate(context, R.layout.scjh_item, null);
        head = headView.findViewById(R.id.head);
        cb = headView.findViewById(R.id.cb);
        cb.setOnClickListener(view -> {
            checkedCount = 0;
            totalCount = 0;
            selectItem = 0;
            for (int i = 0; i < xdjjhxzDataList.size(); i++) {
                xdjjhxzDataList.get(i).setChecked(cb.isChecked());
                adapter.notifyDataSetChanged();
                if (cb.isChecked()) {
                    String[] countStr = xdjjhxzDataList.get(i).getCountPercent().split(separator);
                    checkedCount += Integer.parseInt(countStr[0]);
                    totalCount += Integer.parseInt(countStr[1]);
                }
            }
            if (cb.isChecked()) {
                selectItem = xdjjhxzDataList.size();
            }
        });

    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_djdsc;
    }

    public void initData() {
        queue = NoHttp.newRequestQueue(1);
        getDataInSQL();
        setListData();
        numberFormat.setMaximumFractionDigits(2);
    }
    void getDataInSQL() {
        xdjjhxzDataList.clear();
        qydDataBeanMap.clear();
        xdjjhxzDataBeanList.clear();
        xdjjhxzDataBeanList.addAll(DataSupport.findAll(XDJJHXZDataBean.class));
        for (int i = 0; i < xdjjhxzDataBeanList.size(); i++) {
            if (!xdjjhxzDataBeanList.get(i).getGWID().equals(gwid)) {
                List<QYDDATABean> qydDataBeen = DataSupport.where("GWID = ?", xdjjhxzDataBeanList.get(i).getGWID()).find(QYDDATABean.class);
                gwid = xdjjhxzDataBeanList.get(i).getGWID();
                int count = 0;
                for (int j = 0; j < qydDataBeen.size(); j++) {
                    if (qydDataBeen.get(j).isChecked()) {
                        count++;
                    }
                }
                XDJJHXZDataBean xdjjhxzDataBean = new XDJJHXZDataBean();
                xdjjhxzDataBean.setGWMC(xdjjhxzDataBeanList.get(i).getGWMC());
                xdjjhxzDataBean.setGWID(xdjjhxzDataBeanList.get(i).getGWID());
                xdjjhxzDataBean.setCountPercent(count + separator + qydDataBeen.size());
                xdjjhxzDataBean.setQYBH(xdjjhxzDataBeanList.get(i).getQYBH());
                xdjjhxzDataList.add(xdjjhxzDataBean);
                qydDataBeanMap.put(xdjjhxzDataBeanList.get(i).getGWID(), qydDataBeen);
            }
        }
    }
    private void setListData() {
        adapter = new ScjhAdapter(context, xdjjhxzDataList, view -> {
            CheckBox checkBox = (CheckBox) view;
            int index = (int) checkBox.getTag();
            xdjjhxzDataList.get(index).setChecked(checkBox.isChecked());
            calculateSelectedCount();
            cb.setChecked(selectItem == xdjjhxzDataList.size());
            adapter.notifyDataSetChanged();
        });

        lv.addHeaderView(headView, null, false);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener((adapterView, view, i, l) -> {
            xdjjhxzDataList.get(i - 1).setChecked(!xdjjhxzDataList.get(i - 1).isChecked());
            calculateSelectedCount();
            cb.setChecked(selectItem == xdjjhxzDataList.size());
            adapter.notifyDataSetChanged();
        });
    }
    private void calculateSelectedCount() {
        selectItem = 0;
        checkedCount = 0;
        totalCount = 0;
        for (int a = 0; a < xdjjhxzDataList.size(); a++) {
            if (xdjjhxzDataList.get(a).isChecked()) {
                selectItem++;
                String[] countStr = xdjjhxzDataList.get(a).getCountPercent().split(separator);
                checkedCount += Integer.parseInt(countStr[0]);
                totalCount += Integer.parseInt(countStr[1]);
            }
        }
    }

    private void uploadData() {
        String USERNAME = (String) SPUtils.get(context, Contans.USERID, "");
        ScdjjhBean scdjjhbean = new ScdjjhBean();
        scdjjhbean.setAction("DJ_GWSC_SET");
        scdjjhbean.setYHID(USERNAME);
        List<ScdjjhBean.DJ_DATA> djDataList = new ArrayList<>();
        List<ScdjjhBean.DJ_DATA.QYDJ_DATA> qydjDataList = new ArrayList<>();
        for (int i = 0; i < xdjjhxzDataList.size(); i++) {
            ScdjjhBean.DJ_DATA dhdata = new ScdjjhBean.DJ_DATA();
            if (xdjjhxzDataList.get(i).isChecked()) {
                final List<QYDDATABean> qyddataBeanList = qydDataBeanMap.get(xdjjhxzDataList.get(i).getGWID());
                scdjjhbean.setGWID(xdjjhxzDataList.get(i).getGWID());
                scdjjhbean.setGWMC(xdjjhxzDataList.get(i).getGWMC());
                dhdata.setQYBH(xdjjhxzDataList.get(i).getQYBH());
                dhdata.setQYDJ_ST(sdf.format(new Date()));
                for (int j = 0; j < qyddataBeanList.size(); j++) {
                    ScdjjhBean.DJ_DATA.QYDJ_DATA qydj_data = new ScdjjhBean.DJ_DATA.QYDJ_DATA();
                    qydj_data.setSCID(qyddataBeanList.get(j).getSCID());
                    if (TextUtils.isEmpty(qyddataBeanList.get(j).getDATE())) {
                        qydj_data.setDJSJ("");
                    } else {
                        qydj_data.setDJSJ(qyddataBeanList.get(j).getDATE());
                    }
                    if (TextUtils.isEmpty(qyddataBeanList.get(j).getCJJG())) {
                        qydj_data.setDJSZ("");
                        qydj_data.setSBZT("");
                    } else {
                        qydj_data.setDJSZ(qyddataBeanList.get(j).getCJJG());
                        qydj_data.setFXNR(qyddataBeanList.get(j).getFXNR());
                        if (qyddataBeanList.get(j).getCJJG().equals("已停用")) {
                            qydj_data.setSBZT("3");
                            qydj_data.setFXNR("");
                        }else if (qyddataBeanList.get(j).getCJJG().equals("备用")){
                            qydj_data.setSBZT("5");
                            qydj_data.setFXNR("");
                        } else if (qyddataBeanList.get(j).getCJJG().equals("大小修")) {
                            qydj_data.setSBZT("4");
                            qydj_data.setFXNR("");
                        } else {
                            qydj_data.setSBZT("1");
                        }
                    }
                    qydj_data.setSMFS("NFC");
                    qydjDataList.add(qydj_data);
                }
                dhdata.setQYDJ_DATA(qydjDataList);
                djDataList.add(dhdata);
                scdjjhbean.setDJ_DATA(djDataList);
                final String json = GsonUtils.GsonString(scdjjhbean);
                sCData(json);
            }
        }

    }
    private void sCData(String json) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.DJJHSC, RequestMethod.POST);
        request.setDefineRequestBodyForJson(json);
        queue.add(1, request, new HttpResponseListener<>(getActivity(), request, callback, false, true, "上传数据中...请稍等..."));
    }
    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {
            StatusInfo2 info = GsonUtils.GsonToBean(response.get(), StatusInfo2.class);
            try {
                if (what == 1) {
                    if (info.getState() == 1) {
                        for (int i = 0; i < xdjjhxzDataList.size(); i++) {
                            if (xdjjhxzDataList.get(i).isChecked()) {
                                DataSupport.deleteAll(XDJJHXZDataBean.class, "GWID = ?", xdjjhxzDataList.get(i).getGWID());
                                DataSupport.deleteAll(QYDDATABean.class, "GWID = ?", xdjjhxzDataList.get(i).getGWID());
                                DataSupport.deleteAll(Djjh.class, "GWID = ?", xdjjhxzDataList.get(i).getGWID());
                                xdjjhxzDataList.remove(xdjjhxzDataList.get(i));
                            }
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        showToast(info.getMsg());
                    }
                }
            } catch (Exception e) {
                showToast(UiUtlis.getString(context, R.string.data_error));

            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {

        }
    };
    private void deleteData() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("提示");
        builder.setTitle("你确定要删除？");
        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        builder.setPositiveButton("确定", (dialog, which) -> {
            for (int i = 0; i < xdjjhxzDataList.size(); i++) {
                if (xdjjhxzDataList.get(i).isChecked()) {
                    DataSupport.deleteAll(XDJJHXZDataBean.class, "GWID = ?", xdjjhxzDataList.get(i).getGWID());
                    DataSupport.deleteAll(QYDDATABean.class, "GWID = ?", xdjjhxzDataList.get(i).getGWID());
                    DataSupport.deleteAll(Djjh.class, "GWID = ?", xdjjhxzDataList.get(i).getGWID());
                }
            }
            getDataInSQL();
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        });
        builder.show();
    }
}