package com.bjzc.bhzhgd.activity.sbxj;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bjzc.bhzhgd.DBModel.XSJJHDataBean;
import com.bjzc.bhzhgd.DBModel.XSJJHXZBean;
import com.bjzc.bhzhgd.DBModel.XSJJHXZDataBean;
import com.bjzc.bhzhgd.DBModel.Xjjh;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.adapter.XzxsjhAdapter;
import com.bjzc.bhzhgd.base.BaseFragment;
import com.bjzc.bhzhgd.bean.XsRequestInfo;
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.RSAUtils;
import com.bjzc.bhzhgd.utils.SPUtils;
import com.bjzc.bhzhgd.utils.UiUtlis;
import com.bjzc.bhzhgd.weight.WaitDialog;
import com.google.gson.Gson;
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.Arrays;
import java.util.Iterator;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;


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

/**
 * Created by ruihong on 2018/4/8.
 */

public class XzxsjhFragment extends BaseFragment {
    ListView lv;
    TextView tvNodata;
    FrameLayout FL;
    Button btnXz;
    Button btnDelete;
    LinearLayout LL;


    private WaitDialog dialog;
    private XjMainActivity mActivity;
    private View headView;
    private View head;
    private XzxsjhAdapter adapter;
    private CheckBox cb;
    private List<Xjjh> xjjhs;
    private int selectCount = 0;
    private int requestCount = 0;
    private List<String> zxids = new ArrayList<>();
    private List<String> jhmcs = new ArrayList<>();
    private RequestQueue queue;
    private String type = null;
    private String professionId = null;
    private String username;
    private List<String> zyids;
    private boolean firstInit = true;

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Contans.ACTION_REFRESHPLANDOWNLOAD.equals(action)) {
                //刷新页面
                initData();
            }
            if (Contans.ACTION_PROFESSIONCHANGE.equals(action)) {
                professionId = intent.getStringExtra("professionId");
                Log.i("app", professionId);
                Log.i("app", "initData");
                firstInit = false;
                //刷新页面
                initData();
            }
        }
    };

    public XzxsjhFragment() {

    }

    public XzxsjhFragment(String type) {
        this.type = type;
    }

    public static XzxsjhFragment newInstance(String type) {
        XzxsjhFragment fragment = new XzxsjhFragment(type);
        return fragment;
    }


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

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

        btnXz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (xjjhs.size() != 0) {
                    zxids.clear();
                    jhmcs.clear();
                    for (int i = 0; i < xjjhs.size(); i++) {
                        if (xjjhs.get(i).isChecked()) {
                            if (!dialog.isShowing()) {
                                dialog.setMessage("下载计划中...");
                                dialog.show();
                            }
                            if (type != null && type.equals("BA")) {
                                //保安计划下载
                                downDataBA(xjjhs.get(i).getZxid());
                            } else {
                                //运行，燃料计划下载
                                downData(xjjhs.get(i).getZxid(), xjjhs.get(i).getJhmc());
                            }
                            zxids.add(xjjhs.get(i).getZxid());
                        }
                    }
                } else {
                    showToast("没有可下载计划");
                }
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (xjjhs.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<Xjjh> delete = new ArrayList<>();
                            for (int i = 0; i < xjjhs.size(); i++) {
                                if (xjjhs.get(i).isChecked()) {
                                    delete.add(xjjhs.get(i));
                                    DataSupport.deleteAll(Xjjh.class, "zxid = ?  and username = ?", xjjhs.get(i).getZxid(), username);
                                }
                            }
                            xjjhs.removeAll(delete);
                            adapter.notifyDataSetChanged();
                        }
                    });
                    builder.show();

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



        lv.setEmptyView(tvNodata);
        mActivity = (XjMainActivity) getActivity();
        headView = View.inflate(context, R.layout.xzxsjh_item, null);
        head = headView.findViewById(R.id.head);
        head.setVisibility(View.VISIBLE);
        cb = headView.findViewById(R.id.cb);
        cb.setOnClickListener(view -> {

            if (cb.isChecked()) {
                for (int i = 0; i < xjjhs.size(); i++) {
                    xjjhs.get(i).setChecked(true);
                    adapter.notifyDataSetChanged();
                }
            } else {
                for (int i = 0; i < xjjhs.size(); i++) {
                    xjjhs.get(i).setChecked(false);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        lv.addHeaderView(headView, null, false);

        String UserIDTemp = (String) SPUtils.get(context, Contans.USERID, "");
        username = RSAUtils.decryptBASE64StrLocal(UserIDTemp);

        String zyid = (String) SPUtils.get(context, Contans.ZY, "");
        if (zyid != null && (!zyid.equals(""))) {
            zyids = this.stringToList(zyid);
            Log.i("app", "---------");
            Log.i("app", new Gson().toJson(zyids));
            if (zyids.size() > 0) {
                if (type != null && type.equals("BA")) {
                } else {
                    this.professionId = zyids.get(0);
                }
            }
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contans.ACTION_REFRESHPLANDOWNLOAD);
        filter.addAction(Contans.ACTION_PROFESSIONCHANGE);
        //requireActivity().registerReceiver(myReceiver, filter);
        LocalBroadcastManager.getInstance(requireActivity()).registerReceiver(myReceiver, filter);
    }

    public void initData() {
        queue = NoHttp.newRequestQueue(1);
        dialog = new WaitDialog(getActivity(), "加载中...");
        dialog.setCancelable(false);
        cb.setChecked(false);
        xjjhs = new ArrayList<>();
        //如果数据库中有数据
        if (DataSupport.count("Xjjh") != 0) {
            List<Xjjh> xjjhListall = new ArrayList<>();
            if (professionId != null) {
                if (type != null && type.equals("YX")) {
                    if (zyids != null && zyids.size() == 1) {
                        xjjhListall = where("download = ? and mk = ? and zyid = ? and username = ?", "0", type, professionId, username).find(Xjjh.class);
                    } else {
                        if (firstInit) {
                            //页面第一次进来初始化
                            if (zyids != null && zyids.size() > 1) {
                                StringBuffer sb = new StringBuffer();
                                for (Iterator<String> iterator = zyids.iterator(); iterator.hasNext(); ) {
                                    String string = (String) iterator.next();
                                    String oneCase = "'" + string + "'";
                                    sb.append(oneCase);
                                    if (iterator.hasNext()) {
                                        sb.append(",");
                                    }
                                }
                                String inConditions = sb.toString();
                                //Log.i("app",inConditions);
                                xjjhListall = where(String.format("zyid in (%s) and download = ? and mk =? and username = ?", inConditions), "0", type, username).find(Xjjh.class);
                            } else {
                                xjjhListall = where("download = ? and mk = ? and username = ?", "0", type, username).find(Xjjh.class);
                            }
                        } else {
                            //切换专业
                            xjjhListall = where("download = ? and mk = ? and zyid = ? and username = ?", "0", type, professionId, username).find(Xjjh.class);
                        }
                    }
                } else {
                    xjjhListall = where("download = ? and mk = ? and username = ?", "0", type, username).find(Xjjh.class);
                }
            } else {
                xjjhListall = where("download = ? and mk = ? and username = ?", "0", type, username).find(Xjjh.class);
            }

            xjjhs.clear();
            xjjhs.addAll(xjjhListall);
            setListData();
        } else {
            tvNodata.setText("暂无数据");
            LL.setVisibility(View.GONE);
        }
    }

    private List<String> stringToList(String strs) {
        String[] str = strs.split(",");
        return Arrays.asList(str);
    }


    //运行，燃料计划下载
    private void downData(String zxid, String jhmc) {
        selectCount++;
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.XSCB_PLAN_DOWNLOAD, RequestMethod.POST);
        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()));
//            }
        }
        request.setDefineRequestBodyForJson(createZyJson(zxid, jhmc));
        queue.add(1, request, new HttpResponseListener<>(getActivity(), request, callback, false, false, ""));
    }

    //保安计划下载
    private void downDataBA(String zxid) {
        selectCount++;
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.XSCB_PLAN_BA_DOWNLOAD, RequestMethod.POST);
        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()));
//            }
        }
        request.setDefineRequestBodyForJson(createZyJsonBA(zxid));
        queue.add(2, request, new HttpResponseListener<>(getActivity(), request, callbackBA, false, false, ""));
    }

    private XSJJHXZBean xsjjhxzBean;
    //运行，燃料计划下载回调
    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {
            try {
                if (what == 1) {
                    ++requestCount;
                    String result = response.get();
                    showLog("----------------");
                    showLog(result);
                    Gson gson = new Gson();
                    xsjjhxzBean = GsonUtils.GsonToBean(result, XSJJHXZBean.class);
                    if (xsjjhxzBean != null && xsjjhxzBean.getState() == 1) {
                        List<XSJJHXZDataBean> xsjjhxzDataBeanList = xsjjhxzBean.getData();
                        ContentValues values = new ContentValues();
                        values.put("download", 1);
                        if (xsjjhxzDataBeanList != null && xsjjhxzDataBeanList.size() > 0) {
                            for (int i = 0; i < xsjjhxzDataBeanList.size(); i++) {
                                XSJJHXZDataBean xsjjhxzDataBean = xsjjhxzDataBeanList.get(i);
                                showLog(gson.toJson(xsjjhxzDataBean));
                            }
                            DataSupport.updateAll(Xjjh.class, values, "zxid = ?  and mk = ?  and username = ?", xsjjhxzDataBeanList.get(0).getZxid(), type, username);
                            List<Xjjh> xjjhTemp = where("mk = ? and zxid = ? and username = ?", type, xsjjhxzDataBeanList.get(0).getZxid(), username).find(Xjjh.class);
                            String jhmc = "";
                            if (xjjhTemp != null && xjjhTemp.size() > 0) {
                                jhmc = xjjhTemp.get(0).getJhmc();
                            }
                            for (int i = 0; i < xsjjhxzDataBeanList.size(); i++) {
                                xsjjhxzDataBeanList.get(i).setSN(i + 1);
                                xsjjhxzDataBeanList.get(i).setUsername(username);
                                xsjjhxzDataBeanList.get(i).setJhmc(jhmc);
                                showLog("----------------");
                                showLog(gson.toJson(xsjjhxzDataBeanList.get(i)));

                                List<XSJJHDataBean> getData = xsjjhxzDataBeanList.get(i).getData();
                                for (int j = 0; j < getData.size(); j++) {
                                    XSJJHDataBean bean = getData.get(j);
                                    bean.setUsername(username);
                                    bean.setJhmc(jhmc);
                                }
                                DataSupport.saveAll(getData);
                            }
                            DataSupport.saveAll(xsjjhxzDataBeanList);
                        }
                    } 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();
                    xjjhs.clear();
                    List<Xjjh> xjjhListall = new ArrayList<>();
                    if (professionId != null) {
                        if (type != null && type.equals("YX")) {
                            if (zyids != null && zyids.size() == 1) {
                                xjjhListall = where("download = ? and mk = ? and zyid = ? and username = ?", "0", type, professionId, username).find(Xjjh.class);
                            } else {
                                if (firstInit) {
                                    //页面第一次进来初始化
                                    if (zyids != null && zyids.size() > 1) {
                                        StringBuffer sb = new StringBuffer();
                                        for (Iterator<String> iterator = zyids.iterator(); iterator.hasNext(); ) {
                                            String string = (String) iterator.next();
                                            String oneCase = "'" + string + "'";
                                            sb.append(oneCase);
                                            if (iterator.hasNext()) {
                                                sb.append(",");
                                            }
                                        }
                                        String inConditions = sb.toString();
                                        //Log.i("app",inConditions);
                                        xjjhListall = where(String.format("zyid in (%s) and download = ? and mk =? and username = ?", inConditions), "0", type, username).find(Xjjh.class);
                                    } else {
                                        xjjhListall = where("download = ? and mk = ? and username = ?", "0", type, username).find(Xjjh.class);
                                    }
                                } else {
                                    //切换专业
                                    xjjhListall = where("download = ? and mk = ? and zyid = ? and username = ?", "0", type, professionId, username).find(Xjjh.class);
                                }
                            }
                        } else {
                            xjjhListall = where("download = ? and mk = ? and username = ?", "0", type, username).find(Xjjh.class);
                        }
                    } else {
                        xjjhListall = where("download = ? and mk = ? and username = ?", "0", type, username).find(Xjjh.class);
                    }
                    xjjhs.addAll(xjjhListall);
//                    if(professionId!=null){
//                        xjjhs.addAll(where("download = ? and mk = ? and zyid = ? and username = ?", "0",type,professionId,username).find(Xjjh.class));
//                    }else{
//                        xjjhs.addAll(where("download = ? and mk = ? and username = ?", "0",type,username).find(Xjjh.class));
//                    }
                    if (adapter != null) {
                        cb.setChecked(false);
                        adapter.notifyDataSetChanged();
                    }
                    showToast("下载成功");
                    Intent intent = new Intent(Contans.ACTION_REFRESHPLANUPLOAD);
                    //发送广播,刷新任务上传页面
                    //requireActivity().sendBroadcast(intent);
                    LocalBroadcastManager.getInstance(requireActivity()).sendBroadcast(intent);
                    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 HttpListener<String> callbackBA = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {
            try {
                if (what == 2) {
                    ++requestCount;
                    String result = response.get();
                    showLog("----------------");
                    showLog(result);
                    xsjjhxzBean = GsonUtils.GsonToBean(result, XSJJHXZBean.class);
                    if (xsjjhxzBean != null && xsjjhxzBean.getState() == 1) {
                        List<XSJJHXZDataBean> xsjjhxzDataBeanList = xsjjhxzBean.getData();
                        ContentValues values = new ContentValues();
                        values.put("download", 1);
                        showLog("--------");
                        if (xsjjhxzDataBeanList != null && xsjjhxzDataBeanList.size() > 0) {
                            showLog(String.valueOf(xsjjhxzDataBeanList.size()));
                            DataSupport.updateAll(Xjjh.class, values, "zxid = ? and mk = ?  and username = ?", xsjjhxzDataBeanList.get(0).getZxid(), type, username);
                        }
                        int dataCount = DataSupport.count(XSJJHXZDataBean.class);
                        int index;//序号
                        index = dataCount;
                        for (int i = 0; i < xsjjhxzDataBeanList.size(); i++) {
                            xsjjhxzDataBeanList.get(i).setSN(++index);
                            xsjjhxzDataBeanList.get(i).setUsername(username);
                            //List<XSJJHDataBean> getData = xsjjhxzDataBeanList.get(i).getData();
//                            for (int j=0;j<getData.size();j++){
//                                //nfc
//                                XSJJHDataBean bean = getData.get(j);
//                                bean.setNfcbm("1");
//                            }

                            //DataSupport.saveAll(getData);
                            //no  nfc
                            //DataSupport.saveAll(xsjjhxzDataBeanList.get(i).getData());

                        }
                        DataSupport.saveAll(xsjjhxzDataBeanList);
                    } 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();
                    xjjhs.clear();
                    List<Xjjh> xjjhListall = new ArrayList<>();
                    xjjhs.addAll(where("download = ? and mk = ?  and username = ?", "0", type, username).find(Xjjh.class));
                    if (adapter != null) {
                        cb.setChecked(false);
                        adapter.notifyDataSetChanged();
                    }
                    showToast("下载成功");
                    Intent intent = new Intent(Contans.ACTION_REFRESHPLANUPLOAD);
                    //发送广播,刷新任务上传页面
                    //requireActivity().sendBroadcast(intent);
                    LocalBroadcastManager.getInstance(requireActivity()).sendBroadcast(intent);
                    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 String createZyJson(String zxid, String jhmc) {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction("YX_XJGL_RWXZ_GET");
        info.setZxid(zxid);
        String json = GsonUtils.GsonString(info);
        showLog(json);
        return json;
    }

    private String createZyJsonBA(String zxid) {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction("BA_XJGL_RWXZ_GET");
        info.setZxid(zxid);
        String json = GsonUtils.GsonString(info);
        showLog(json);
        return json;
    }

    private void setListData() {
        adapter = new XzxsjhAdapter(context, xjjhs, new XzxsjhAdapter.CallBack() {
            @Override
            public void Click(View view) {

                CheckBox checkBox = (CheckBox) view;
                int index = (int) checkBox.getTag();
                xjjhs.get(index).setChecked(checkBox.isChecked());
                int count = 0;
                for (int a = 0; a < xjjhs.size(); a++) {
                    if (xjjhs.get(a).isChecked()) {
                        count++;
                    }
                }
                cb.setChecked(count == xjjhs.size());
                adapter.notifyDataSetChanged();
            }
        });

        lv.setAdapter(adapter);
        lv.setOnItemClickListener((adapterView, view, i, l) -> {
            xjjhs.get(i - 1).setChecked(!xjjhs.get(i - 1).isChecked());
            int count = 0;
            for (int a = 0; a < xjjhs.size(); a++) {
                if (xjjhs.get(a).isChecked()) {
                    count++;
                }
            }
            cb.setChecked(count == xjjhs.size());
            adapter.notifyDataSetChanged();
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //requireActivity().unregisterReceiver(myReceiver);
        // 注销广播接收器
        LocalBroadcastManager.getInstance(requireActivity()).unregisterReceiver(myReceiver);
    }
}
