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

import android.content.ContentValues;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.zhapp.DBModel.LyxcXmList;
import com.example.administrator.zhapp.DBModel.LyxcqyList;
import com.example.administrator.zhapp.DBModel.XfBaxcRwqy;
import com.example.administrator.zhapp.DBModel.XfBaxcRwqyList;
import com.example.administrator.zhapp.DBModel.XfDjjh;
import com.example.administrator.zhapp.DBModel.XfDjjhList;
import com.example.administrator.zhapp.DBModel.XfDjjhRwList;
import com.example.administrator.zhapp.DBModel.XfDjjhRwqy;
import com.example.administrator.zhapp.DBModel.XfDjjhRwqyList;
import com.example.administrator.zhapp.DBModel.XfXcmhqc;
import com.example.administrator.zhapp.DBModel.XfXcmhqcList;
import com.example.administrator.zhapp.DBModel.XfXcxm;
import com.example.administrator.zhapp.DBModel.XfXcxmList;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.xfbwxcgl.XxzActivity;
import com.example.administrator.zhapp.adapter.XfXzjhAdapter;
import com.example.administrator.zhapp.contans.Contans;
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.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.yolanda.nohttp.NoHttp;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class XxzjhFragment extends BaseFragment {

    ListView lv;
    Button btnXz;
    Button btnDel;
    TextView tvNodata;

    private XxzActivity mActivity;
    private View headView;
    private View head;
    private CheckBox cb;
    private boolean flag = false;

    private XfXzjhAdapter adapter;

    private List<XfDjjh> djjhs;

    private int requestCount = 0;
    private int successCount = 0;

    private StringBuilder sb;
    private XfDjjhList list;

    private WaitDialog dialog;
    private RequestQueue queue;

    //任务列表下载数据
    private List<XfDjjhRwqyList> qylists;
    private List<XfDjjhRwqy> qys;
    private XfDjjhRwList rwlist;

    private List<XfXcmhqc> mhqcs;
    private List<XfXcxm> xcxms;
    private List<String> jhids = new ArrayList<>();
    private List<String> xftypes = new ArrayList<>();
    private List<XfBaxcRwqy> xfBaxcRwqies;


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

    public XxzjhFragment() {
    }

    public static XxzjhFragment newInstance() {
        XxzjhFragment fragment = new XxzjhFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {

        lv = (ListView) view.findViewById(R.id.lv);
        btnXz = (Button) view.findViewById(R.id.btn_xz);
        btnDel = (Button) view.findViewById(R.id.btn_delete);
        tvNodata = (TextView) view.findViewById(R.id.tv_nodata);

        mActivity = (XxzActivity) getActivity();

        headView = View.inflate(context, R.layout.xzjh_item, null);
        head = headView.findViewById(R.id.head);
        head.setVisibility(View.VISIBLE);
        TextView textView = (TextView) headView.findViewById(R.id.tv_jhlx);
        textView.setText("到期时间");
        cb = (CheckBox) headView.findViewById(R.id.cb);


        btnXz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sb = new StringBuilder();
                jhids.clear();
                xftypes.clear();
                for (int i = 0; i < djjhs.size(); i++) {
                    if (djjhs.get(i).isChecked()) {
                        jhids.add(djjhs.get(i).getJhid());
                        xftypes.add(djjhs.get(i).getXctypes());
                    }
                }
                if (jhids.size() != 0) {
                    dialog = new WaitDialog(getActivity(), "下载计划中...");
                    dialog.show();
                    for (int i = 0; i < jhids.size(); i++) {
                        downData(jhids.get(i), xftypes.get(i));
                    }
                } else {
                    showToast("没有可下载计划");
                }
            }
        });
        btnDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<XfDjjh> jhids = new ArrayList<>();
                for (int i = 0; i < djjhs.size(); i++) {
                    if (djjhs.get(i).isChecked()) {
                        jhids.add(djjhs.get(i));
                        DataSupport.deleteAll(XfDjjh.class, "jhid = ?", djjhs.get(i).getJhid());
                    }
                }
                djjhs.removeAll(jhids);
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }
        });


        lv.setEmptyView(tvNodata);
        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

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

    public void initData() {


        queue = NoHttp.newRequestQueue(1);

        djjhs = new ArrayList<>();
        qylists = new ArrayList<>();
        qys = new ArrayList<>();
        mhqcs = new ArrayList<>();
        xcxms = new ArrayList<>();
        xfBaxcRwqies = new ArrayList<>();

        dialog = new WaitDialog(context, "下载计划中...");
        dialog.setCancelable(false);

        //如果数据库中有数据
        if (DataSupport.count("Xfdjjh") != 0) {
            djjhs = DataSupport.where("download = ?", "0").find(XfDjjh.class);
            setListData();
            //showToast("读取数据库数据");
        } else {
            requestData();
            //showToast("请求接口数据");
        }
    }

    private void requestData() {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.XFDJJHALL);
        request.add("bzbh", UiUtlis.encoder((String) SPUtils.get(context, Contans.BZBH, "")));
        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, true, true, "加载中..."));

        //NohttpUtils.getInstance().add(getActivity(), 0, request, callback, true, true, "加载中...");
    }

    private void downData(String jhid, String xctypes) {
        String tokenTemp = (String) SPUtils.get(mActivity, Contans.LOGIN_TOKEN, "");
        if (xctypes.equals("1")) {
            requestCount++;
            Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.XFDJJHXZ);
            request.add("jhid", UiUtlis.encoder(jhid));
            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(1, request, new HttpResponseListener<>(getActivity(), request, callback, false, false, ""));
            //NohttpUtils.getInstance().add(getActivity(), 1, request, callback, false, false, "下载计划中...");

            requestCount++;
            Request<String> request1 = NoHttp.createStringRequest(Contans.IP + Contans.XFXCMHQC);
            request1.add("jhid", UiUtlis.encoder(jhid));
            request1.add("xftype", 1);

            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(2, request1, new HttpResponseListener<>(getActivity(), request1, callback, false, false, "加载中..."));
            //NohttpUtils.getInstance().add(getActivity(), 2, request1, callback, false, false, "下载计划中...");

            requestCount++;
            Request<String> request2 = NoHttp.createStringRequest(Contans.IP + Contans.XFXCXM);
            request2.add("jhid", UiUtlis.encoder(jhid));
            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(3, request2, new HttpResponseListener<>(getActivity(), request2, callback, false, false, "加载中..."));
            //NohttpUtils.getInstance().add(getActivity(), 3, request2, callback, false, false, "下载计划中");
        } else if (xctypes.equals("2")) {
            requestCount++;
            Request<String> xfba = NoHttp.createStringRequest(Contans.IP + Contans.BAXCJHXZ);
            xfba.add("jhid", UiUtlis.encoder(jhid));
            if(!TextUtils.isEmpty(tokenTemp)){
                String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
                String credential = "Bearer " + token;
                xfba.addHeader("Authorization", credential);
                showLog(xfba.url());
//            if(!TextUtils.isEmpty(token)){
//                showLog(credential);
//                showLog(new Gson().toJson(request.headers()));
//            }
            }
            queue.add(4, xfba, new HttpResponseListener<>(getActivity(), xfba, callback, false, false, "加载中..."));
            //NohttpUtils.getInstance().add(getActivity(), 4, xfba, callback, false, false, "下载计划中");
        } else if (xctypes.equals("3")) {
            requestCount++;
            Request<String> lyxc = NoHttp.createStringRequest(Contans.IP + Contans.LYXCXM);
            lyxc.add("jhid", UiUtlis.encoder(jhid));
            if(!TextUtils.isEmpty(tokenTemp)){
                String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
                String credential = "Bearer " + token;
                lyxc.addHeader("Authorization", credential);
                showLog(lyxc.url());
//            if(!TextUtils.isEmpty(token)){
//                showLog(credential);
//                showLog(new Gson().toJson(request.headers()));
//            }
            }
            queue.add(5, lyxc, new HttpResponseListener<>(getActivity(), lyxc, callback, false, false, "加载中..."));
            //NohttpUtils.getInstance().add(getActivity(), 5, lyxc, callback, false, false, "下载计划中");
            requestCount++;
            Request<String> lyxcqy = NoHttp.createStringRequest(Contans.IP + Contans.LYXCQY);
            lyxcqy.add("jhid", UiUtlis.encoder(jhid));
            if(!TextUtils.isEmpty(tokenTemp)){
                String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);;
                String credential = "Bearer " + token;
                lyxcqy.addHeader("Authorization", credential);
                showLog(lyxcqy.url());
//            if(!TextUtils.isEmpty(token)){
//                showLog(credential);
//                showLog(new Gson().toJson(request.headers()));
//            }
            }
            queue.add(6, lyxcqy, new HttpResponseListener<>(getActivity(), lyxcqy, callback, false, false, "加载中..."));
            //NohttpUtils.getInstance().add(getActivity(), 6, lyxcqy, callback, false, false, "下载计划中");
        }
    }

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

            switch (what) {
                case 0:
                    list = GsonUtils.GsonToBean(result, XfDjjhList.class);
                    if (list != null) {

                        if (Integer.parseInt(list.getTotal()) != 0) {
                            djjhs.clear();
                            djjhs.addAll(list.getRows());
                            setListData();
                            //保存计划列表到数据库
                            DataSupport.saveAll(list.getRows());
                            //savaDataInSQLite();
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 1:
                    rwlist = GsonUtils.GsonToBean(result, XfDjjhRwList.class);
                    //开启一个线程保存数据
                    if (rwlist != null) {
                        successCount++;
                        //保存任务区域数据
                        if (rwlist.getTotal() != 0) {
                            for (int i = 0; i < rwlist.getRows().size(); i++) {
                                qys.addAll(rwlist.getRows().get(i).getXfdjjhrwqy());
                            }
                            DataSupport.saveAll(qys);
                        }

                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 2:
                    XfXcmhqcList list = GsonUtils.GsonToBean(result, XfXcmhqcList.class);
                    if (list != null) {
                        successCount++;
                        if (!list.getTotal().equals("0")) {
                            mhqcs.clear();
                            mhqcs = list.getRows();
                            DataSupport.saveAll(mhqcs);
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 3:
                    XfXcxmList list1 = GsonUtils.GsonToBean(result, XfXcxmList.class);
                    if (list1 != null) {
                        successCount++;
                        xcxms = list1.getRows();
                        //保存消防项目数据
                        DataSupport.saveAll(xcxms);
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 4:

                    Logger.v(response.get());
                    XfBaxcRwqyList xfbas = GsonUtils.GsonToBean(result, XfBaxcRwqyList.class);
                    if (xfbas != null) {
                        successCount++;
                        xfBaxcRwqies = xfbas.getRows();
                        if (xfBaxcRwqies.size() != 0) {
                            String jhid = xfBaxcRwqies.get(0).getJhid();
                            xfbas.setJhid(jhid);
                            DataSupport.saveAll(xfBaxcRwqies);
                        } else {
                            showToast(UiUtlis.getString(context, R.string.data_error));
                        }
                    }
                    break;
                case 5:
                    //楼宇巡查
                    LyxcXmList lyxcXmList = GsonUtils.GsonToBean(result, LyxcXmList.class);
                    if (lyxcXmList != null) {
                        successCount++;
                        if (!lyxcXmList.getTotal().equals("0")) {
                            DataSupport.saveAll(lyxcXmList.getRows());
                        }
                    } else {
                        showToast("数据出错");
                    }
                    break;

                case 6:
                    LyxcqyList lyxcqyList = GsonUtils.GsonToBean(result, LyxcqyList.class);
                    if (lyxcqyList != null) {
                        successCount++;
                        if (lyxcqyList.getTotal() != 0) {
                            for (LyxcqyList.RowsBean row : lyxcqyList.getRows()) {
                                DataSupport.saveAll(row.getLyxcrwqys());
                            }
                        }
                    } else {
                        showToast("数据出错");
                    }
                    break;
            }

            if (requestCount == successCount && successCount != 0) {
                requestCount = 0;
                successCount = 0;

                for (String jhid : jhids) {
                    ContentValues values = new ContentValues();
                    values.put("download", 1);
                    DataSupport.updateAll(XfDjjh.class, values, "JHID = ?", jhid);
                }
                jhids.clear();
                //int id = DataSupport.findFirst(XfDjjhList.class).getId();
                djjhs.clear();
                djjhs.addAll(DataSupport.where("download = ?" + "", 0 + "").find(XfDjjh.class));
                if (adapter != null) {
                    cb.setChecked(false);
                    adapter.notifyDataSetChanged();
                }
                dialog.dismiss();
            }
        }

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

    //保存下载数据
    private void saveDownData(final List<XfDjjhRwqyList> qylists, final List<XfDjjhRwqy> qys, int index) {

        rwlist.setJhid(jhids.get(index));
        rwlist.save();
        if (rwlist.getTotal() != 0) {
            qylists.clear();
            for (int i = 0; i < rwlist.getRows().size(); i++) {
                XfDjjhRwqyList djjhRwQyList = rwlist.getRows().get(i);
                String qymc = rwlist.getRows().get(i).getXfdjjhrwqy().get(0).getQYNAME();
                djjhRwQyList.setQyname(qymc);
                qylists.add(djjhRwQyList);
            }
            System.out.println(qylists);
            DataSupport.saveAll(qylists);
            for (int i = 0; i < qylists.size(); i++) {
                qys.clear();
                qys.addAll(qylists.get(i).getXfdjjhrwqy());
                DataSupport.saveAll(qys);
            }
        }
    }
//
//    /**
//     * 保存计划数据到本地数据库
//     */
//    private void savaDataInSQLite() {
//        //list.save();
//        DataSupport.saveAll(list.getRows());
//    }

    private void setListData() {

        adapter = new XfXzjhAdapter(context, djjhs, new XfXzjhAdapter.CallBack() {
            @Override
            public void Click(View view) {
                CheckBox checkBox = (CheckBox) view;
                int index = (int) checkBox.getTag();
                djjhs.get(index).setChecked(checkBox.isChecked());
                int count = 0;
                for (int a = 0; a < djjhs.size(); a++) {
                    if (djjhs.get(a).isChecked()) {
                        count++;
                    }
                }
                cb.setChecked(count == djjhs.size());
                adapter.notifyDataSetChanged();
            }
        });

        lv.addHeaderView(headView, null, false);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                djjhs.get(i - 1).setChecked(djjhs.get(i - 1).isChecked());
                int count = 0;
                for (int a = 0; a < djjhs.size(); a++) {
                    if (djjhs.get(a).isChecked()) {
                        count++;
                    }
                }
                cb.setChecked(count == djjhs.size());
                adapter.notifyDataSetChanged();
            }
        });
    }
}