package com.bjzc.bhzhgd.activity.sbxdj;


import android.content.ContentValues;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bjzc.bhzhgd.DBModel.Djjh;
import com.bjzc.bhzhgd.DBModel.XDJJHXZBean;
import com.bjzc.bhzhgd.DBModel.XDJJHXZDataBean;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.adapter.XzjhAdapter;
import com.bjzc.bhzhgd.base.BaseFragment;
import com.bjzc.bhzhgd.bean.XscbRequestBean;
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.WaitDialog;
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.util.ArrayList;
import java.util.List;

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

/**
 * 设备巡点检管理-下载计划
 */
public class XzjhFragment extends BaseFragment {

    ListView lv;
    Button btn_xz;
    TextView tvNodata;
    LinearLayout LL;

    private WaitDialog dialog;
    private DjMainActivity mActivity;
    private View headView;
    private View head;
    private XzjhAdapter adapter;
    private CheckBox cb;
    private List<Djjh> djjhs;
    private int selectCount = 0;
    private int requestCount = 0;
    private List<String> gwids = new ArrayList<>();
    private RequestQueue queue;
    private XDJJHXZBean xdjjhxzBean;

    public XzjhFragment() {

    }

    public static XzjhFragment newInstance() {
        XzjhFragment fragment = new XzjhFragment();
        return fragment;
    }


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

    @Override
    protected void initView() {

        lv.setEmptyView(tvNodata);
        mActivity = (DjMainActivity) getActivity();

        lv = view.findViewById(R.id.lv);
        tvNodata = view.findViewById(R.id.tv_nodata);
        btn_xz = view.findViewById(R.id.btn_xz);
        LL = view.findViewById(R.id.LL);

        btn_xz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (djjhs.size() != 0) {

                    gwids.clear();
                    for (int i = 0; i < djjhs.size(); i++) {
                        if (djjhs.get(i).isChecked()) {
                            if (!dialog.isShowing()) {
                                dialog.setMessage("下载计划中...");
                                dialog.show();
                            }

                            downData(djjhs.get(i).getGWID());
                            gwids.add(djjhs.get(i).getGWID());
                        }
                    }
                } else {
                    showToast("没有可下载计划");
                }
            }
        });

        headView = View.inflate(context, R.layout.xzjh_item, null);
        head = headView.findViewById(R.id.head);
        head.setVisibility(View.VISIBLE);
        lv.addHeaderView(headView, null, false);
        cb = headView.findViewById(R.id.cb);
        cb.setOnClickListener(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);
        dialog = new WaitDialog(getActivity(), "加载中...");
        dialog.setCancelable(false);
        djjhs = new ArrayList<>();
        //如果数据库中有数据
        if (DataSupport.count("Djjh") != 0) {
            List<Djjh> djjhall = where("download = ?", "0").find(Djjh.class);
            djjhs.clear();
            djjhs.addAll(djjhall);
            setListData();
        } else {
            tvNodata.setText("暂无数据");
            LL.setVisibility(View.GONE);
        }
    }

    private void downData(String gwid) {
        selectCount++;
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.DJJHDLB, RequestMethod.POST);
        request.setDefineRequestBodyForJson(createZyJson(gwid));
        queue.add(1, request, new HttpResponseListener<>(getActivity(), request, callback, false, false, ""));
    }

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

            try {
                if (what == 1) {
                    ++requestCount;
                    Log.e("dataLog", response.get());
                    xdjjhxzBean = GsonUtils.GsonToBean(response.get(), XDJJHXZBean.class);
                    if (xdjjhxzBean != null && xdjjhxzBean.getState() == 1) {
                        List<XDJJHXZDataBean> xdjjhxzDataBeanList = xdjjhxzBean.getData();
                        ContentValues values = new ContentValues();
                        values.put("download", 1);//把Djjh里面的下载过的download变成1
                        for (int i = 0; i < xdjjhxzDataBeanList.size(); i++) {
                            DataSupport.updateAll(Djjh.class, values, "GWID = ?", xdjjhxzDataBeanList.get(i).getGWID());
                        }
                        int dataCount = DataSupport.count(XDJJHXZDataBean.class);
                        int index;//序号
                        index = dataCount;
                        for (int i = 0; i < xdjjhxzDataBeanList.size(); i++) {
                            xdjjhxzDataBeanList.get(i).setSN(++index);
                            DataSupport.saveAll(xdjjhxzDataBeanList.get(i).getQYD_DATA());
                            DataSupport.saveAll(xdjjhxzDataBeanList.get(i).getQYAQFX_DATA());
                        }
                        DataSupport.saveAll(xdjjhxzDataBeanList);
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                }

                if (requestCount == selectCount && requestCount != 0) {
                    requestCount = 0;
                    selectCount = 0;
                    tvNodata.setText("暂无数据");
                    requestCount = 0;
                    selectCount = 0;
                    dialog.cancel();
                    djjhs.clear();
                    djjhs.addAll(where("download = ?", "0").find(Djjh.class));
                    if (adapter != null) {
                        cb.setChecked(false);
                        adapter.notifyDataSetChanged();
                    }
                    showToast("下载成功");
                    dialog.dismiss();
                }
            } catch (Exception e) {
                showToast(UiUtlis.getString(context, R.string.data_error));
                dialog.dismiss();
            }
        }

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

    private void setListData() {
        adapter = new XzjhAdapter(context, djjhs, 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.setAdapter(adapter);
        lv.setOnItemClickListener((adapterView, view, i, 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();
        });
    }

    private String createZyJson(String gwid) {
        String YHID = (String) SPUtils.get(context, Contans.USERID, "");
        XscbRequestBean info = new XscbRequestBean();
        info.setAction("DJ_RWXZ_GET");
        info.setGWID(gwid);
        info.setYHID(YHID);
        String json = GsonUtils.GsonString(info);
        return json;
    }

}
