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

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.Ajhjh;
import com.example.administrator.zhapp.DBModel.AjhjhList;
import com.example.administrator.zhapp.DBModel.AjhjhxzrwList;
import com.example.administrator.zhapp.DBModel.Ajhxzrwqy;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.adapter.AjhXzjhAdapter;
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;

public class AxzFragment extends BaseFragment {

    ListView lv;
    TextView tvNodata;
    Button btnXz;
    Button btn_del;

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

    private List<Ajhjh> ajhjh;
    private int selectCount = 0;
    private int requestCount = 0;
    private WaitDialog dialog;

    private List<String> downjh;
    private List<Ajhxzrwqy> rwqys;

    private AjhXzjhAdapter adapter;

    private RequestQueue queue;

    //任务列表下载数据


    public AxzFragment() {
    }

    public static AxzFragment newInstance(String param1, String param2) {
        AxzFragment fragment = new AxzFragment();
        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_axz;
    }

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

        lv.setEmptyView(tvNodata);
        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);
        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

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

        btnXz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下载
                downjh.clear();
                for (int i = 0; i < ajhjh.size(); i++) {
                    if (ajhjh.get(i).isChecked()) {
                        //downData(ajhjh.get(i).getJHID());
                        downjh.add(ajhjh.get(i).getJHID());
                    }
                }

                if (downjh.size() != 0) {
                    dialog = new WaitDialog(getActivity(), "下载计划中...");
                    dialog.show();
                    for (String jh : downjh) {
                        ++selectCount;
                        downData(jh);
                    }
                } else {
                    showToast("没有可下载计划");
                }
            }
        });

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

                for (int i = 0; i < ajhjh.size(); i++) {
                    if (ajhjh.get(i).isChecked()) {
                        DataSupport.deleteAll(Ajhjh.class, "jhid = ?", ajhjh.get(i).getJHID());
                        ajhjhs.add(ajhjh.get(i));
                    }
                }
                ajhjh.removeAll(ajhjhs);
                adapter.notifyDataSetChanged();
            }
        });
    }

    public void initData() {


        queue = NoHttp.newRequestQueue(1);

        rwqys = new ArrayList<>();
        ajhjh = new ArrayList<>();
        downjh = new ArrayList<>();

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

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

    private void requestData() {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.AJHJHLIST);
        request.add("BZMC", 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) {
        requestCount++;
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.AJHXZRW);
        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<String>(getActivity(), request, callback, false, false, ""));

        //NohttpUtils.getInstance().add(getActivity(), 1, request, callback, false, false, "下载计划中...");
    }

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

            switch (what) {
                case 0:
                    AjhjhList info = GsonUtils.GsonToBean(response.get(), AjhjhList.class);
                    if (info != null) {
                        if (info.getTotal() != 0) {
                            info.save();
                            ajhjh.clear();
                            ajhjh.addAll(info.getRows());
                            DataSupport.saveAll(ajhjh);
                            setListData();
                        } else {
                            //showToast("暂无数据");
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 1:
                    AjhjhxzrwList list = GsonUtils.GsonToBean(response.get(), 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);
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }

                    if (list != null) {

                        if (requestCount == selectCount) {
                            requestCount = 0;
                            selectCount = 0;

                            ContentValues values = new ContentValues();
                            values.put("download", 1);
                            for (int i = 0; i < downjh.size(); i++) {
                                DataSupport.updateAll(Ajhjh.class, values, "JHID = ?", downjh.get(i));
                            }

                            ajhjh.clear();
                            ajhjh.addAll(DataSupport.where("download = ?", 0 + "").find(Ajhjh.class));
                            if (adapter != null) {
                                cb.setChecked(false);
                                adapter.notifyDataSetChanged();
                            }
                            dialog.dismiss();
                        }
                    } else {
                        dialog.dismiss();
                    }
                    break;
            }
        }

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

    private void setListData() {

        adapter = new AjhXzjhAdapter(context, ajhjh, new AjhXzjhAdapter.CallBack() {
            @Override
            public void Click(View view) {
                CheckBox checkBox = (CheckBox) view;
                int index = (int) checkBox.getTag();
                ajhjh.get(index).setChecked(checkBox.isChecked());
                int count = 0;
                for (int a = 0; a < ajhjh.size(); a++) {
                    if (ajhjh.get(a).isChecked()) {
                        count++;
                    }
                }
                cb.setChecked(count == ajhjh.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) {
                ajhjh.get(i - 1).setChecked(ajhjh.get(i - 1).isChecked());
                int count = 0;
                for (int a = 0; a < ajhjh.size(); a++) {
                    if (ajhjh.get(a).isChecked()) {
                        count++;
                    }
                }
                cb.setChecked(count == ajhjh.size());
                adapter.notifyDataSetChanged();
            }
        });
    }
}
