package com.example.administrator.zhapp.fragment.ajhxcgl;

import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;

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 com.example.administrator.zhapp.BaseListViewAdapter.CommonAdapter;
import com.example.administrator.zhapp.BaseListViewAdapter.ViewHolder;
import com.example.administrator.zhapp.DBModel.AjhScInfo;
import com.example.administrator.zhapp.DBModel.Ajhjh;
import com.example.administrator.zhapp.DBModel.Ajhxcjs;
import com.example.administrator.zhapp.DBModel.Ajhxzrwqy;
import com.example.administrator.zhapp.DBModel.YhpcInfo;
import com.example.administrator.zhapp.DBModel.Yhpctp;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.AjhSc;
import com.example.administrator.zhapp.entity.StatusInfo;
import com.example.administrator.zhapp.fragment.BaseFragment;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.HttpResponseListener;
import com.example.administrator.zhapp.utils.RSAUtils;
import com.example.administrator.zhapp.utils.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.WaitDialog;
import com.orhanobut.logger.Logger;
import com.yolanda.nohttp.FileBinary;
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.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AscFragment extends BaseFragment {

    ListView lv;
    TextView tvNodata;
    Button btnSc;
    Button btn_del;

    private CommonAdapter<AjhSc> adapter;
    private List<Ajhjh> ajhjhs;//安建环计划
    private List<AjhSc> ajhscs;
    private Map<String, List<Ajhxzrwqy>> map;
    private View headView;
    private List<String> jhids;
    private int selectCount;
    private int requestCount;
    private CheckBox cb;
    private WaitDialog dialog;
    private RequestQueue queue;

    public AscFragment() {
    }

    public static AscFragment newInstance(String param1, String param2) {
        AscFragment fragment = new AscFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

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

    @Override
    protected void initView() {
        lv = view.findViewById(R.id.lv);
        btnSc = view.findViewById(R.id.btn_sc);
        tvNodata = view.findViewById(R.id.tv_nodata);
        btn_del = view.findViewById(R.id.btn_delete);

        dialog = new WaitDialog(context, "上传中...");
        dialog.setCancelable(false);

        btnSc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上传数据
                uploadData();
            }
        });

        btn_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> jhids = new ArrayList<>();

                for (AjhSc sc : ajhscs) {
                    if (sc.isChecked()) {
                        jhids.add(sc.getJhid());
                    }
                }

                //删除数据
                for (String jhid : jhids) {
                    List<Ajhxcjs> ajhxcjses = DataSupport.findAll(Ajhxcjs.class);
                    for (Ajhxcjs js : ajhxcjses) {
                        File file = new File(js.getFile());
                        if (file.isFile()) {
                            file.delete();
                        }
                    }
                    DataSupport.deleteAll(Ajhxcjs.class, "jhid = ?", jhid);
                    DataSupport.deleteAll(Ajhjh.class, "jhid = ?", jhid);
                    DataSupport.deleteAll(Ajhxzrwqy.class, "jhid = ?", jhid);
                    DataSupport.deleteAll(AjhScInfo.class, "jhid = ?", jhid);
                }

                getDataInSQL();
                adapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    public void initData() {

        queue = NoHttp.newRequestQueue(1);
        map = new HashMap<>();
        ajhjhs = new ArrayList<>();
        ajhscs = new ArrayList<>();
        jhids = new ArrayList<>();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            visible();
        }
    }

    //视图显示时才查询数据库数据
    private void visible() {
        getDataInSQL();
        if (adapter == null) {
            setListData();
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    //获取数据库数据
    private void getDataInSQL() {
        ajhjhs.clear();
        map.clear();
        ajhscs.clear();
        //查找已下载计划
        ajhjhs.addAll(DataSupport.where("download = ?", "1").find(Ajhjh.class));
        for (Ajhjh ajhjh : ajhjhs) {
            map.put(ajhjh.getJHID(), DataSupport.where("jhid = ?", ajhjh.getJHID()).find(Ajhxzrwqy.class));
        }

        for (int i = 0; i < ajhjhs.size(); i++) {
            List<Ajhxzrwqy> ajhxzrwqies = map.get(ajhjhs.get(i).getJHID());
            int yj = 0;
            for (Ajhxzrwqy ajhxzrwqy : ajhxzrwqies) {
                if (ajhxzrwqy.isChecked()) {
                    yj++;
                }
            }
            AjhSc info = new AjhSc();
            info.setXh(i + 1);
            info.setJhmc(ajhjhs.get(i).getJHMC());
            info.setYjzj(yj + "/" + ajhxzrwqies.size());
            info.setJhid(ajhjhs.get(i).getJHID());
            ajhscs.add(info);
        }
    }

    //设置列表adapter
    private void setListData() {

        headView = View.inflate(context, R.layout.xzjh_item, null);
        TextView tv = (TextView) headView.findViewById(R.id.tv_jhlx);
        tv.setText("已检总计");
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
        cb = (CheckBox) headView.findViewById(R.id.cb);
        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (cb.isChecked()) {
                    for (int i = 0; i < ajhscs.size(); i++) {
                        ajhscs.get(i).setChecked(true);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    for (int i = 0; i < ajhscs.size(); i++) {
                        ajhscs.get(i).setChecked(false);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });


        adapter = new CommonAdapter<AjhSc>(context, R.layout.xzjh_item, ajhscs) {
            @Override
            protected void convert(ViewHolder viewHolder, AjhSc item, final int position) {

                viewHolder.setOnClickListener(R.id.cb, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CheckBox checkBox = (CheckBox) v;
                        ajhscs.get(position).setChecked(checkBox.isChecked());
                        int count = 0;
                        for (int a = 0; a < ajhscs.size(); a++) {
                            if (ajhscs.get(a).isChecked()) {
                                count++;
                            }
                        }
                        cb.setChecked(count == ajhscs.size());
                        adapter.notifyDataSetChanged();
                    }
                });

                viewHolder.setChecked(R.id.cb, item.isChecked());
                viewHolder.setText(R.id.tv_xh, item.getXh() + "");
                viewHolder.setText(R.id.tv_jhmc, item.getJhmc());
                viewHolder.setText(R.id.tv_jhlx, item.getYjzj());
            }
        };
        lv.addHeaderView(headView, null, false);
        lv.setEmptyView(tvNodata);
        lv.setAdapter(adapter);
    }

    private void uploadData() {

        jhids.clear();

        final List<Ajhxzrwqy> rwqys = new ArrayList<>();
        int select = 0;//选中的计划
        int checked = -1;//全部检查项目

        for (AjhSc sc : ajhscs) {
            if (sc.isChecked()) {
                select++;
                jhids.add(sc.getJhid());
            }
        }
        if (select != 0) {
            for (String jhid : jhids) {
                rwqys.addAll(map.get(jhid));
            }
            for (Ajhxzrwqy rwqy : rwqys) {
                if (!rwqy.isChecked()) {
                    checked = 0;
                    break;
                }
            }
            //还有未检查项目
            if (checked == 0) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("提示");
                builder.setTitle("你还有项目未检查，是否上传？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sCData(toJson(rwqys));
                        //toJson(rwqys);
                    }
                });
                builder.show();

            } else {
                //已经全部检查
                sCData(toJson(rwqys));
                //toJson(rwqys);
            }
        } else {
            showToast("没有可上传计划");
        }
    }

    private void sCData(String json) {
        dialog.show();
        selectCount++;
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.AJHSC, RequestMethod.POST);
        request.setDefineRequestBodyForJson(UiUtlis.encoder(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());
//            if(!TextUtils.isEmpty(token)){
//                showLog(credential);
//                showLog(new Gson().toJson(request.headers()));
//            }
        }
        queue.add(0, request, new HttpResponseListener<>(getActivity(), request, callback, false, false, ""));
        //NohttpUtils.getInstance().add(getActivity(), 0, request, callback, false, false, "上传中...");

        for (String jhid : jhids) {
            List<Ajhxcjs> xcjs = DataSupport.where("jhid = ?", jhid).find(Ajhxcjs.class);
            for (Ajhxcjs ajhxcjs : xcjs) {
                selectCount++;
                Request<String> request1 = NoHttp.createStringRequest(Contans.IP + Contans.AJHXCJS +
                        "?bz=" + UiUtlis.encoder(ajhxcjs.getBz()) +
                        "&jhid=" + UiUtlis.encoder(ajhxcjs.getJhid()) +
                        "&areacode=" + UiUtlis.encoder(ajhxcjs.getAreacode()) +
                        "&jsr=" + UiUtlis.encoder((String) SPUtils.get(context, Contans.USERNAME, "")), RequestMethod.POST);
                request1.add(Contans.FILEPS, new FileBinary(new File(ajhxcjs.getFile())));

                if(!TextUtils.isEmpty(tokenTemp)){
                    String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
                    String credential = "Bearer " + token;
                    request1.addHeader("Authorization", credential);
                    showLog(request1.url());
//            if(!TextUtils.isEmpty(token)){
//                showLog(credential);
//                showLog(new Gson().toJson(request.headers()));
//            }
                }
                queue.add(1, request1, new HttpResponseListener<>(getActivity(), request1, callback, false, false, ""));
                //NohttpUtils.getInstance().add(getActivity(), 1, request1, callback, false, false, "");
            }
        }

        Request<String> request2 = NoHttp.createStringRequest(Contans.IP + Contans.YHPC, RequestMethod.POST);
        List<YhpcInfo> infos = DataSupport.findAll(YhpcInfo.class);
        if (infos.size() != 0) {
            selectCount++;
            String json1 = "{\"Rows\":" + GsonUtils.GsonString(infos) + ",\"Total\": " + infos.size() + "}";
            Logger.json(json1);
            json1 = new String(json1.getBytes(), StandardCharsets.UTF_8);
            request2.setDefineRequestBodyForJson(UiUtlis.encoder(json1));

            if(!TextUtils.isEmpty(tokenTemp)){
                String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
                String credential = "Bearer " + token;
                request2.addHeader("Authorization", credential);
                showLog(request2.url());
//            if(!TextUtils.isEmpty(token)){
//                showLog(credential);
//                showLog(new Gson().toJson(request.headers()));
//            }
            }
            queue.add(2, request2, new HttpResponseListener<>(getActivity(), request2, callback, false, false, ""));
            //NohttpUtils.getInstance().add(getActivity(), 2, request2, callback, false, false, "上传中...");
        }

        List<Yhpctp> tps = DataSupport.findAll(Yhpctp.class);
        if (tps.size() != 0) {
            for (Yhpctp tp : tps) {
                selectCount++;
                Request<String> yhpctp = NoHttp.createStringRequest(Contans.IP + Contans.YHPCTP + "?guid=" + tp.getGuid(), RequestMethod.POST);
                yhpctp.add(Contans.FILEPS, new FileBinary(new File(tp.getPath())));

                if(!TextUtils.isEmpty(tokenTemp)){
                    String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
                    String credential = "Bearer " + token;
                    yhpctp.addHeader("Authorization", credential);
                    showLog(yhpctp.url());
//            if(!TextUtils.isEmpty(token)){
//                showLog(credential);
//                showLog(new Gson().toJson(request.headers()));
//            }
                }
                queue.add(3, yhpctp, new HttpResponseListener<>(getActivity(), yhpctp, callback, false, false, ""));
            }
        }

    }

    //生成要上传的json数据
    private String toJson(List<Ajhxzrwqy> rwqys) {
        List<AjhScInfo> infos = new ArrayList<>();
        for (Ajhxzrwqy rwqy : rwqys) {
            AjhScInfo info = new AjhScInfo();
            info.setMS(rwqy.getMS() == null ? "" : rwqy.getMS());
            info.setBZID((String) SPUtils.get(context,Contans.BZBH,""));//班组ID，登录成功的时候返回的
            info.setCHECKED(rwqy.isChecked());
            info.setJCR((String) SPUtils.get(context, Contans.USERNAME, ""));
            info.setJCSJ(rwqy.getDATE()== null ? "" : rwqy.getDATE());
            info.setJHID(rwqy.getJHID());
            info.setSCNR(rwqy.getSCRN()== null ? "" :rwqy.getSCRN());
            info.setYSID(rwqy.getYSID());
            info.setCHECKED(rwqy.isChecked());
            info.setSMFX(rwqy.isSMFX() ? "扫描条码" : "NFC标签");
            infos.add(info);
        }
        String json = "{\"Rows\":" + GsonUtils.GsonString(infos) + ",\"Total\": " + infos.size() + "}";
        Logger.json(json);
        json = new String(json.getBytes(), StandardCharsets.UTF_8);
        return json;
    }

    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {

            Logger.v(response.get());

            try {
                StatusInfo info = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
                if (info != null) {
                    switch (what) {
                        case 0: {
                            if (info.getRows().get(0).getStatus().equals("1")) {
                                requestCount++;
                            } else {
                                showToast("上传失败");
                            }
                        }
                        break;
                        case 1:
                            if (info.getRows().get(0).getStatus().equals("1")) {
                                requestCount++;
                            } else {
                                showToast("上传失败");
                            }
                            break;
                        case 2:
                            if (info.getRows().get(0).getStatus().equals("1")) {
                                requestCount++;
                                //DataSupport.deleteAll(YhpcInfo.class);
                            } else {
                                showToast("上传失败");
                            }
                            break;
                        case 3:
                            if (info.getRows().get(0).getStatus().equals("1")) {
                                requestCount++;
                                //DataSupport.deleteAll(YhpcInfo.class);
                            } else {
                                showToast("上传失败");
                            }
                            break;
                    }

                    if (requestCount == selectCount) {
                        requestCount = 0;
                        selectCount = 0;
                        showToast("上传成功");
                        dialog.dismiss();
                        //删除数据
                        deleteData();
                        getDataInSQL();
                        cb.setChecked(false);
                        adapter.notifyDataSetChanged();
                    }

                } else {
                    showToast("数据出错");
                    dialog.dismiss();
                }

            } catch (Exception e) {
                showToast("数据出错");
                dialog.dismiss();
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
                requestCount = 0;
                selectCount = 0;
            }
        }
    };

    //删除数据
    private void deleteData() {
        for (String jhid : jhids) {
            List<Ajhxcjs> ajhxcjses = DataSupport.findAll(Ajhxcjs.class);
            for (Ajhxcjs js : ajhxcjses) {
                File file = new File(js.getFile());
                if (file.isFile()) {
                    file.delete();
                }
            }

            List<Yhpctp> tps = DataSupport.findAll(Yhpctp.class);
            for (Yhpctp tp : tps)
            {
                File file = new File(tp.getPath());
                if (file.isFile()) {
                    file.delete();
                }
            }
            DataSupport.deleteAll(Ajhxcjs.class, "jhid = ?", jhid);
            DataSupport.deleteAll(Ajhjh.class, "jhid = ?", jhid);
            DataSupport.deleteAll(Ajhxzrwqy.class, "jhid = ?", jhid);
            DataSupport.deleteAll(AjhScInfo.class, "jhid = ?", jhid);
            DataSupport.deleteAll(YhpcInfo.class);
            DataSupport.deleteAll(Yhpctp.class);
        }
    }
}