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

import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
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.Ajhjh;
import com.example.administrator.zhapp.DBModel.AjhjhxzrwList;
import com.example.administrator.zhapp.DBModel.Ajhxzrwqy;
import com.example.administrator.zhapp.DBModel.Djjh;
import com.example.administrator.zhapp.DBModel.DjjhList;
import com.example.administrator.zhapp.DBModel.DjjhRwList;
import com.example.administrator.zhapp.DBModel.DjjhRwQyList;
import com.example.administrator.zhapp.DBModel.Zy;
import com.example.administrator.zhapp.DBModel.ZyInfo;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.sbxdjgl.SxcdjActivity;
import com.example.administrator.zhapp.adapter.XzjhAdapter;
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.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.util.ArrayList;
import java.util.List;
import androidx.appcompat.app.AlertDialog;

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

    ListView lv;
    Button btn_xz;
    Button btn_del;
    TextView tvNodata;

    private WaitDialog dialog;

    private SxcdjActivity 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 DjjhList list;
    private DjjhRwList rwlist;
    private List<String> jhids = new ArrayList<>();
    private List<Ajhxzrwqy> rwqys;
    private RequestQueue queue;


    public XzjhFragment() {
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

    @Override
    protected void initView() {

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

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

                    jhids.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).getJHID());
                            jhids.add(djjhs.get(i).getJHID());
                            final int finalI = i;
                        }
                    }
                } else {
                    showToast("没有可下载计划");
                }
            }
        });

        btn_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (djjhs.size() != 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) {
                            List<Djjh> delete = new ArrayList<>();
                            for (int i = 0; i < djjhs.size(); i++) {
                                if (djjhs.get(i).isChecked()) {
                                    delete.add(djjhs.get(i));
                                    DataSupport.deleteAll(Djjh.class, "jhid = ?", djjhs.get(i).getJHID());
                                }
                            }
                            djjhs.removeAll(delete);
                            adapter.notifyDataSetChanged();
                        }
                    });
                    builder.show();

                } else {
                    showToast("没有可删除计划");
                }
            }
        });

        lv.setEmptyView(tvNodata);
        mActivity = (SxcdjActivity) getActivity();
        headView = View.inflate(context, R.layout.xzjh_item, null);
        head = headView.findViewById(R.id.head);
        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 < 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<>();
        rwqys = new ArrayList<>();
        //如果数据库中有数据
        if (DataSupport.count("Djjh") != 0) {
            List<Djjh> djjhall = DataSupport.where("download = ?", "0").find(Djjh.class);
            djjhs.clear();
            djjhs.addAll(djjhall);
            setListData();

            tvNodata.setText("暂无数据");
        } else {

        }
    }

    private void downData(String jhid) {
        selectCount++;
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.DJJHDLB);
        request.add("JHID", UiUtlis.encoder(jhid));

        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(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 {
                String result = response.get();
                showLog(String.valueOf(what));
                showLog(result);

                switch (what) {
                    case 0:
                        list = GsonUtils.GsonToBean(result, DjjhList.class);
                        if (list != null) {
                            if (list.getTotal() != 0) {
                                djjhs.clear();
                                djjhs.addAll(list.getRows());
                                setListData();
                                savaDataInSQLite();
                            }
                        } else {
                            showToast(UiUtlis.getString(context, R.string.data_error));
                        }
                        break;
                    case 1:
                        ++requestCount;
                        rwlist = null;
                        rwlist = GsonUtils.GsonToBean(result, DjjhRwList.class);

                        //保存数据
                        if (rwlist != null) {

                            ContentValues values = new ContentValues();
                            values.put("download", 1);
                            DataSupport.updateAll(Djjh.class, values, "JHID = ?", rwlist.getRows().get(0).getDjjhRqqys().get(0).getJHID());
                            Log.e("dataLog", rwlist.getRows().get(0).getDjjhRqqys().get(0).getJHID());

                            for (int i = 0; i < rwlist.getRows().size(); i++) {
                                DjjhRwQyList item = rwlist.getRows().get(i);
                                showLog(GsonUtils.GsonString(item));
                                showLog(GsonUtils.GsonString(rwlist.getRows().get(i).getDjjhRqqys()));
                                DataSupport.saveAll(rwlist.getRows().get(i).getDjjhRqqys());
                            }
                        } else {
                            showToast(UiUtlis.getString(context, R.string.data_error));
                        }

                        break;

                    case 2:
                        ++requestCount;
                        AjhjhxzrwList list = GsonUtils.GsonToBean(result, AjhjhxzrwList.class);
                        if (list != null) {
                            if (list.getTotal() != 0) {
                                rwqys.clear();
                                for (int i = 0; i < list.getRows().size(); i++) {
                                    rwqys.addAll(list.getRows().get(i).getAjhxzrwqys());
                                }
                                //保存下载数据
                                DataSupport.saveAll(rwqys);

                                ContentValues values = new ContentValues();
                                values.put("download", 1);
                                DataSupport.updateAll(Ajhjh.class, values, "JHID = ?", rwqys.get(0).getJHID());

                            }
                        } else {
                            showToast(UiUtlis.getString(context, R.string.data_error));
                        }

                        break;
                    case 9:
                        ZyInfo info = GsonUtils.GsonToBean(result, ZyInfo.class);
                        if (info != null) {
                            if (DataSupport.count("zy") != 0) {
                                DataSupport.deleteAll(Zy.class);
                            }
                            List<Zy> zys = info.getRows();
                            //保存专业信息
                            DataSupport.saveAll(zys);
                        } else {
                            showToast(UiUtlis.getString(context, R.string.data_error));
                        }
                        dialog.dismiss();
                        break;
                }

                if (requestCount == selectCount && requestCount != 0) {
                    requestCount = 0;
                    selectCount = 0;
                    tvNodata.setText("暂无数据");
                    requestCount = 0;
                    selectCount = 0;
                    dialog.cancel();

                    //更新的点检点上传列表
                    mActivity.updataDjdsc();

                    djjhs.clear();
                    djjhs.addAll(DataSupport.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 savaDataInSQLite() {
        list.save();
        DataSupport.saveAll(list.getRows());
    }

    private void setListData() {

        adapter = new XzjhAdapter(context, djjhs, new XzjhAdapter.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();
            }
        });
    }

}
