package com.bjzc.zjyxdxj.activity.sbxj;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
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.zjyxdxj.DBModel.XSJJHDataBean;
import com.bjzc.zjyxdxj.DBModel.XSJJHXZDataBean;
import com.bjzc.zjyxdxj.DBModel.Xjjh;
import com.bjzc.zjyxdxj.R;
import com.bjzc.zjyxdxj.adapter.ScxsAdapter;
import com.bjzc.zjyxdxj.base.BaseFragment;
import com.bjzc.zjyxdxj.bean.ScxjjhBean;
import com.bjzc.zjyxdxj.bean.StatusInfo2;
import com.bjzc.zjyxdxj.contans.Contans;
import com.bjzc.zjyxdxj.utils.GsonUtils;
import com.bjzc.zjyxdxj.utils.RSAUtils;
import com.bjzc.zjyxdxj.utils.SPUtils;
import com.bjzc.zjyxdxj.utils.UiUtlis;
import com.bjzc.zjyxdxj.weight.MeasureDialog;
import com.bjzc.zjyxdxj.weight.WaitDialog;
import com.bjzc.zjyxdxj.weight.toastviewbymyself;
import com.google.gson.Gson;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.litepal.crud.DataSupport.where;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

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

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

    private XjMainActivity mActivity;
    private View headView;
    private View head;
    private CheckBox xj_cb;
    private ScxsAdapter adapter;
    private WaitDialog dialog;
    private RequestQueue queue;
    private int noCheck = 0;
    private int checked = 0;
    private int uploadIndex = 0;
    private List<Xjjh> dbxjjh = new ArrayList<>();
    private List<String> deleteZxids = new ArrayList<>();
    private Map<String, List<XSJJHDataBean>> xsJjhDataBeanMap = new HashMap<>();
    private Map<String, List<XSJJHXZDataBean>> xsJjhBaDataBeanMap = new HashMap<>();
    private String type = null;
    private String username;

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Contans.ACTION_REFRESHPLANUPLOAD.equals(action)) {
                //刷新页面
                initData();
            }
        }
    };

    public ScxsjhFragment() {

    }

    public ScxsjhFragment(String type) {
        this.type = type;
    }

    public static ScxsjhFragment newInstance(String type) {
        ScxsjhFragment fragment = new ScxsjhFragment(type);
        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);

        queue = NoHttp.newRequestQueue(1);

        String UserIDTemp = (String) SPUtils.get(context, Contans.USERID, "");
        username = RSAUtils.decryptBASE64StrLocal(UserIDTemp);

        lv.setEmptyView(tvNodata);
        dialog = new WaitDialog(context, "上传数据中...请稍等...");
        dialog.setCancelable(false);
        mActivity = (XjMainActivity) getActivity();
        headView = View.inflate(context, R.layout.scxscb_item, null);
        head = headView.findViewById(R.id.head);
        xj_cb = headView.findViewById(R.id.xj_cb);
        lv.addHeaderView(headView, null, false);
        xj_cb.setOnClickListener(view -> {

            if (xj_cb.isChecked()) {
                for (int i = 0; i < dbxjjh.size(); i++) {
                    dbxjjh.get(i).setChecked(true);
                    adapter.notifyDataSetChanged();
                }
            } else {
                for (int i = 0; i < dbxjjh.size(); i++) {
                    dbxjjh.get(i).setChecked(false);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        btn_sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type != null && type.equals("BA")) {
                    //上传勾选中的保安数据
                    uploadDataCheckBA();
                } else {
                    //上传勾选中的运行和燃料数据
                    uploadDataCheck();
                }
            }
        });
        btn_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除勾选中的数据
                deleteData();
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contans.ACTION_REFRESHPLANUPLOAD);
        LocalBroadcastManager.getInstance(requireActivity()).registerReceiver(myReceiver, filter);
    }


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

    public void initData() {
        xj_cb.setChecked(false);
        if (type != null && type.equals("BA")) {
            getDataInSQLBA();//获取保安数据
        } else {
            getDataInSQL();//获取运行，燃料数据
        }
        setListData();//显示数据
    }


    /**
     * 获取数据库的数据
     */
    public void getDataInSQL() {
        dbxjjh.clear();
        dbxjjh.addAll(where("download = ? and mk = ?  and username = ?", "1", type, username).find(Xjjh.class));
        //Log.i("app", String.valueOf(dbxjjh.size()));
        xsJjhDataBeanMap.clear();
        for (int i = 0; i < dbxjjh.size(); i++) {
            Xjjh dataBean = dbxjjh.get(i);
            //Log.i("app", dataBean.getZxid());
            //Gson gson = new Gson();
            //Log.i("app", gson.toJson(dataBean));
            List<XSJJHDataBean> qydDataBeen = DataSupport.where("zxid = ?  and username = ?", dataBean.getZxid(), username).find(XSJJHDataBean.class);
            //zxid = dataBean.getZxid();
            //Log.i("app", String.valueOf(qydDataBeen.size()));
            int count = 0;
            for (int j = 0; j < qydDataBeen.size(); j++) {
                if (qydDataBeen.get(j).isChecked()) {
                    count++;
                }
            }
            dataBean.setCountPercent(String.valueOf(count));
            xsJjhDataBeanMap.put(dataBean.getZxid(), qydDataBeen);
            if (count != 0) {
                toastviewbymyself.makeText(getActivity(), "有巡检数据未上传,请检查!!!", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void setListData() {
        adapter = new ScxsAdapter(context, dbxjjh, view -> {
            CheckBox checkBox = (CheckBox) view;
            int index = (int) checkBox.getTag();
            dbxjjh.get(index).setChecked(checkBox.isChecked());
            int count = 0;
            for (int a = 0; a < dbxjjh.size(); a++) {
                if (dbxjjh.get(a).isChecked()) {
                    count++;
                }
            }
            xj_cb.setChecked(count == dbxjjh.size());
            adapter.notifyDataSetChanged();
        });
        lv.setAdapter(adapter);
        lv.setOnItemClickListener((adapterView, view, i, l) -> {
            dbxjjh.get(i - 1).setChecked(!dbxjjh.get(i - 1).isChecked());
            int count = 0;
            for (int a = 0; a < dbxjjh.size(); a++) {
                if (dbxjjh.get(a).isChecked()) {
                    count++;
                }
            }
            xj_cb.setChecked(count == dbxjjh.size());
            adapter.notifyDataSetChanged();
        });
    }

    /**
     * 获取数据库的数据
     */
    public void getDataInSQLBA() {
        dbxjjh.clear();
        dbxjjh.addAll(where("download = ? and mk = ?  and username = ?", "1", type, username).find(Xjjh.class));
        //Log.i("app", String.valueOf(dbxjjh.size()));
        xsJjhBaDataBeanMap.clear();
        for (int i = 0; i < dbxjjh.size(); i++) {
            Xjjh dataBean = dbxjjh.get(i);
            //Log.i("app", dataBean.getZxid());
            //Gson gson = new Gson();
            //Log.i("app", gson.toJson(dataBean));
            if (!dataBean.getZxid().equals("")) {
                List<XSJJHXZDataBean> qydDataBeen = DataSupport.where("zxid = ?  and username = ?", dataBean.getZxid(), username).find(XSJJHXZDataBean.class);
                //Log.i("app", String.valueOf(qydDataBeen.size()));
                int count = 0;
                for (int j = 0; j < qydDataBeen.size(); j++) {
                    if (qydDataBeen.get(j).isBAChecked()) {
                        count++;
                    }
                }
                dataBean.setCountPercent(String.valueOf(count));
                xsJjhBaDataBeanMap.put(dataBean.getZxid(), qydDataBeen);
                if (count != 0) {
                    toastviewbymyself.makeText(getActivity(), "有巡检数据未上传,请检查!!!", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void uploadDataCheck() {
        boolean isSelectUpLoad = false;
        for (int i = 0; i < dbxjjh.size(); i++) {
            if (dbxjjh.get(i).isChecked()) {
                isSelectUpLoad = true;
            }
        }
        if (!isSelectUpLoad) {
            showToast("请选择要上传的计划");
        } else {
            MeasureDialog measureDialog = new MeasureDialog(context, "确定要上传选中的计划吗？", new MeasureDialog.AuditDialogListener() {
                @Override
                public void confirm() {
                    uploadData();
                }

                @Override
                public void cancel() {

                }
            });
            measureDialog.show();
        }
    }

    private void uploadData() {
        int noCheck = 0;//没有检查的数量
        for (int i = 0; i < dbxjjh.size(); i++) {
            String zxid = dbxjjh.get(i).getZxid();
            ScxjjhBean scxjjhbean = new ScxjjhBean();
            scxjjhbean.setAction("YX_XJGL_RWSC_SET");
            scxjjhbean.setQZWC(0);
            if (dbxjjh.get(i).isChecked()) {
                List<XSJJHDataBean> xsjjhdatabeanList = xsJjhDataBeanMap.get(dbxjjh.get(i).getZxid());
                scxjjhbean.setZxid(dbxjjh.get(i).getZxid());
                List<ScxjjhBean.data> datalist = new ArrayList<>();
                for (int j = 0; j < xsjjhdatabeanList.size(); j++) {
                    ScxjjhBean.data datas = new ScxjjhBean.data();
                    datas.setScid(xsjjhdatabeanList.get(j).getScid());
                    if (xsjjhdatabeanList.get(j).getDbh() != null) {
                        datas.setDbh(xsjjhdatabeanList.get(j).getDbh());
                    } else {
                        datas.setDbh("");
                    }
                    if (xsjjhdatabeanList.get(j).getCJJG() == null) {
                        datas.setCbsz("");
                        noCheck++;
                    } else {
                        datas.setCbsz(xsjjhdatabeanList.get(j).getCJJG());
                    }
                    if (xsjjhdatabeanList.get(j).getDATE() == null) {
                        datas.setDjsj("");
                    } else {
                        datas.setDjsj(xsjjhdatabeanList.get(j).getDATE());
                    }
                    if (xsjjhdatabeanList.get(j).getSmfs() != null) {
                        datas.setSmfx(xsjjhdatabeanList.get(j).getSmfs());
                    } else {
                        datas.setSmfx("");
                    }
                    if (xsjjhdatabeanList.get(j).getFxnr() != null) {
                        datas.setFxnr(xsjjhdatabeanList.get(j).getFxnr());
                    } else {
                        datas.setFxnr("");
                    }
                    datas.setZcmc((String) SPUtils.get(context, Contans.BZBH, ""));
                    datas.setCbr(username);
                    datalist.add(datas);
                }
                scxjjhbean.setData(datalist);
                if (noCheck > 0) {     //如果未检查的数量大于0 则提示有未检查的项目
                    scxjjhbean.setQZWC(0);
                    final String json = GsonUtils.GsonString(scxjjhbean);
                    sCData(json, zxid);
                } else {
                    final String json = GsonUtils.GsonString(scxjjhbean);
                    sCData(json, zxid);
                }
            }
        }
    }

    private void sCData(String json, String zxid) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.XSCB, RequestMethod.POST);
        //Log.i("app", json);
        request.setDefineRequestBodyForJson(json);

        String tokenTemp = (String) SPUtils.get(mActivity, Contans.LOGIN_TOKEN, "");
        if(!TextUtils.isEmpty(tokenTemp)){
            String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
            String credential = "Bearer " + token;
            request.addHeader("Authorization", credential);
//            Log.i("app", request.url());
//            Log.i("app", credential);
//            Log.i("app",new Gson().toJson(request.headers()));
        }

        queue.add(1, request, new OnResponseListener<String>() {

            @Override
            public void onStart(int what) {
                dialog.show();
            }

            @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) { //成功
                            showToast("上传数据成功");
                            DataSupport.deleteAll(XSJJHXZDataBean.class, "zxid = ?  and username = ?", zxid, username);
                            DataSupport.deleteAll(XSJJHDataBean.class, "zxid = ?  and username = ?", zxid, username);
                            DataSupport.deleteAll(Xjjh.class, "zxid = ?  and username = ?", zxid, username);
                            //刷新页面
                            initData();
                            //刷新计划下载界面
                            Intent intent = new Intent(Contans.ACTION_REFRESHDOWNLOADPLAN);
                            //发送广播,刷新任务下载页面
                            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                        } else {
                            showToast("上传数据失败");
                        }
                    }
                } catch (Exception e) {
                    showToast(UiUtlis.getString(context, R.string.data_error));
                }
            }

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

            }

            @Override
            public void onFinish(int what) {
                dialog.dismiss();
            }
        });
    }

    private void uploadDataCheckBA() {
        boolean isSelectUpLoad = false;
        for (int i = 0; i < dbxjjh.size(); i++) {
            if (dbxjjh.get(i).isChecked()) {
                isSelectUpLoad = true;
            }
        }
        if (!isSelectUpLoad) {
            showToast("请选择要上传的计划");
        } else {
            MeasureDialog measureDialog = new MeasureDialog(context, "确定要上传选中的计划吗？", new MeasureDialog.AuditDialogListener() {
                @Override
                public void confirm() {
                    uploadDataBA();
                }

                @Override
                public void cancel() {

                }
            });
            measureDialog.show();
        }
    }

    private void uploadDataBA() {
        String idTemp = (String) SPUtils.get(context, Contans.REQUEST_ID, "");
        String id = RSAUtils.decryptBASE64StrLocal(idTemp);

        int noCheck = 0;//没有检查的数量
        for (int i = 0; i < dbxjjh.size(); i++) {
            if (dbxjjh.get(i).isChecked()) {
                String zxid = dbxjjh.get(i).getZxid();
                ScxjjhBean scxjjhbean = new ScxjjhBean();
                scxjjhbean.setAction("BA_XJGL_RWSC_SET");
                scxjjhbean.setId(id);
                scxjjhbean.setQZWC(0);
                List<XSJJHXZDataBean> xsjjhdatabeanList = xsJjhBaDataBeanMap.get(dbxjjh.get(i).getZxid());
                //Log.i("app", String.valueOf(noCheck));
                //Log.i("app", GsonUtils.GsonString(xsjjhdatabeanList));
                scxjjhbean.setZxid(dbxjjh.get(i).getZxid());
                List<ScxjjhBean.data> datalist = new ArrayList<>();
                for (int j = 0; j < xsjjhdatabeanList.size(); j++) {
                    //Log.i("app",(String) SPUtils.get(context, Contans.USERID, ""));
                    if (!xsjjhdatabeanList.get(j).isBAChecked()) {
                        noCheck++;
                    }
                    ScxjjhBean.data datas = new ScxjjhBean.data();
                    datas.setScid(xsjjhdatabeanList.get(j).getScid());
                    datas.setDbh(xsjjhdatabeanList.get(j).getQybh());
                    if (xsjjhdatabeanList.get(j).isBAChecked()) {
                        datas.setCbsz("已检");
                    } else {
                        datas.setCbsz("");
                    }
                    if (xsjjhdatabeanList.get(j).getDATE() == null) {
                        datas.setDjsj("");
                    } else {
                        datas.setDjsj(xsjjhdatabeanList.get(j).getDATE());
                    }
                    datas.setZcmc((String) SPUtils.get(context, Contans.BZBH, ""));
                    datas.setCbr(username);
                    if (xsjjhdatabeanList.get(j).getFxnr() == null) {
                        datas.setFxnr("");
                    } else {
                        datas.setFxnr(xsjjhdatabeanList.get(j).getFxnr());
                    }
                    if (xsjjhdatabeanList.get(j).getSmfs() != null) {
                        datas.setSmfx(xsjjhdatabeanList.get(j).getSmfs());
                    } else {
                        datas.setSmfx("");
                    }
                    if (xsjjhdatabeanList.get(j).getDjsj() == null) {
                        datas.setDjsj("");
                    } else {
                        datas.setDjsj(xsjjhdatabeanList.get(j).getDjsj());
                    }
                    datalist.add(datas);
                }
                scxjjhbean.setData(datalist);
                if (noCheck > 0) {
                    //如果未检查的数量大于0 则提示有未检查的项目
                    scxjjhbean.setQZWC(0);
                    final String json = GsonUtils.GsonString(scxjjhbean);
                    sCDataBA(json, zxid);
                } else {
                    final String json = GsonUtils.GsonString(scxjjhbean);
                    sCDataBA(json, zxid);
                }
            }
        }
    }

    private void sCDataBA(String json, String zxid) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.XSCB_PLAN_BA_UPLOAD, RequestMethod.POST);
        request.setDefineRequestBodyForJson(json);

        String tokenTemp = (String) SPUtils.get(mActivity, Contans.LOGIN_TOKEN, "");
        if(!TextUtils.isEmpty(tokenTemp)){
            String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
            String credential = "Bearer " + token;
            request.addHeader("Authorization", credential);
            showLog(request.url());
            showLog(credential);
            showLog(new Gson().toJson(request.headers()));
        }

        queue.add(2, request, new OnResponseListener<String>() {
            @Override
            public void onStart(int what) {
                dialog.show();
            }

            @Override
            public void onSucceed(int what, Response<String> response) {
                Gson gson = new Gson();
                String result = response.get();
                //Log.i("app", result);
                StatusInfo2 info = GsonUtils.GsonToBean(result, StatusInfo2.class);
                try {
                    if (what == 2) {
                        if (info.getState() == 1) { //成功
                            showToast("上传数据成功");
                            DataSupport.deleteAll(XSJJHXZDataBean.class, "zxid = ?  and username = ?", zxid, username);
                            DataSupport.deleteAll(XSJJHDataBean.class, "zxid = ?  and username = ?", zxid, username);
                            DataSupport.deleteAll(Xjjh.class, "zxid = ?  and username = ?", zxid, username);
                            //刷新页面
                            initData();
                            //刷新计划下载界面
                            Intent intent = new Intent(Contans.ACTION_REFRESHDOWNLOADPLAN);
                            //发送广播,刷新任务下载页面
                            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                        } else {
                            showToast("上传数据失败");
                        }
                    }
                } catch (Exception e) {
                    showToast(UiUtlis.getString(context, R.string.data_error));
                }
            }

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

            }

            @Override
            public void onFinish(int what) {
                dialog.dismiss();
            }
        });
    }

    private void deleteData() {
        int count = 0;
        for (int a = 0; a < dbxjjh.size(); a++) {
            if (dbxjjh.get(a).isChecked()) {
                count++;
            }
        }
        if (count == 0) {
            showToast("请选择要删除的计划");
            return;
        }
        MeasureDialog measureDialog = new MeasureDialog(context, "你确定要删除？", new MeasureDialog.AuditDialogListener() {
            @Override
            public void confirm() {
                dbxjjh.removeIf((item) -> {
                    if (item.isChecked()) {
                        DataSupport.deleteAll(XSJJHXZDataBean.class, "zxid = ?  and username = ?", item.getZxid(), username);
                        DataSupport.deleteAll(XSJJHDataBean.class, "zxid = ?  and username = ?", item.getZxid(), username);
                        DataSupport.deleteAll(Xjjh.class, "zxid = ?  and username = ?", item.getZxid(), username);
                    }
                    return item.isChecked();
                });
//                for (int i = 0; i < dbxjjh.size(); i++) {
//                    if (dbxjjh.get(i).isChecked()) {
//                        DataSupport.deleteAll(XSJJHXZDataBean.class, "zxid = ?  and username = ?", dbxjjh.get(i).getZxid(), username);
//                        DataSupport.deleteAll(XSJJHDataBean.class, "zxid = ?  and username = ?", dbxjjh.get(i).getZxid(), username);
//                        DataSupport.deleteAll(Xjjh.class, "zxid = ?  and username = ?", dbxjjh.get(i).getZxid(), username);
//                    }
//                }

                //刷新页面
                initData();
                //刷新计划下载界面
                Intent intent = new Intent(Contans.ACTION_REFRESHDOWNLOADPLAN);
                //发送广播,刷新任务下载页面
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            }

            @Override
            public void cancel() {

            }
        });
        measureDialog.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LocalBroadcastManager.getInstance(requireActivity()).unregisterReceiver(myReceiver);
    }
}