package com.rehome.sgbaxj.activity.regular;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.rehome.sgbaxj.DBModel.Dqgz;
import com.rehome.sgbaxj.R;
import com.rehome.sgbaxj.adapter.DqgzDownloadAdapter;
import com.rehome.sgbaxj.base.BaseFragment;
import com.rehome.sgbaxj.bean.DqgzUpLoadBean;
import com.rehome.sgbaxj.bean.StatusInfo2;
import com.rehome.sgbaxj.contans.Contans;
import com.rehome.sgbaxj.utils.GsonUtils;
import com.rehome.sgbaxj.utils.HttpListener;
import com.rehome.sgbaxj.utils.HttpResponseListener;
import com.rehome.sgbaxj.utils.SPUtils;
import com.rehome.sgbaxj.utils.UiUtlis;
import com.rehome.sgbaxj.weight.MeasureDialog;
import com.rehome.sgbaxj.weight.WaitDialog;
import com.rehome.sgbaxj.weight.toastviewbymyself;
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.List;

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

/**
 * Created by huang on 2021/12/09
 * 定期工作-任务上传
 */
public class DqgzUpFragment extends BaseFragment {

    ListView lv;
    Button btn_sc;
    Button btn_del;
    TextView tvNodata;


    private DqgzUpAndDownActivity mActivity;
    private View headView;
    private View head;
    private CheckBox xj_cb;
    private DqgzDownloadAdapter adapter;
    private WaitDialog dialog;
    private RequestQueue queue;
    private int noCheck = 0;
    private int selectCount = 0;
    private List<Dqgz> dbxjjh = new ArrayList<>();
    //private List<XSJJHXZDataBean> xsjjhxzDataBeanList = new ArrayList<>();
    //private String rwid = "";
//   private List<XSJJHXZDataBean> xsjhxzdatalist = new ArrayList<>();
//   private Map<String, List<XSJJHDataBean>> xsJjhDataBeanMap = new HashMap<>();
//    private Map<String, List<XSJJHXZDataBean>> xsJjhBaDataBeanMap = new HashMap<>();
    private String type = null;
    private  String username;

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Contans.ACTION_REFRESHPLANUPLOAD.equals(action)) {
                //刷新页面
                initData();
            }
        }
    };

    public DqgzUpFragment() {

    }

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

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


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


        username = (String) SPUtils.get(context, Contans.USERID, "");
        lv.setEmptyView(tvNodata);

        btn_sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadData();//上传勾选中的数据
            }
        });

        btn_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();//删除勾选中的数据
            }
        });


        dialog = new WaitDialog(context, "上传中...");
        dialog.setCancelable(false);
        mActivity = (DqgzUpAndDownActivity) getActivity();
        headView = View.inflate(context, R.layout.scxscb_item, null);
        head = headView.findViewById(R.id.head);
        xj_cb = headView.findViewById(R.id.xj_cb);
        lv.addHeaderView(headView, null, false);
        TextView tv_taskName=headView.findViewById(R.id.tv_gwmc);
        tv_taskName.setText("任务名称");
        TextView tv_isCheck=headView.findViewById(R.id.tv_yjzj);
        tv_isCheck.setText("状态");
        xj_cb.setOnClickListener(view -> {

            if (xj_cb.isChecked()) {
                for (int i = 0; i < dbxjjh.size(); i++) {
                    dbxjjh.get(i).setChecked(true);
                    adapter.notifyDataSetChanged();
                }
            } else {
                for (int i = 0; i < dbxjjh.size(); i++) {
                    dbxjjh.get(i).setChecked(false);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contans.ACTION_REFRESHPLANUPLOAD);
        DqgzUpFragment.this.requireActivity().registerReceiver(myReceiver, filter);
    }


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

    public void initData() {
        xj_cb.setChecked(false);
        queue = NoHttp.newRequestQueue(1);
        getDataInSQL();//获取运行，燃料数据
        setListData();//显示数据
    }


    /**
     * 获取数据库的数据
     */
    public void getDataInSQL() {

        dbxjjh.clear();
        dbxjjh.addAll(where("download = ? and mkbs = ? and username = ?", "1",type,username).find(Dqgz.class));

        Log.i("app",String.valueOf(dbxjjh.size()));

        int count = 0;
        for (int i = 0; i < dbxjjh.size(); i++) {
            Dqgz dataBean = dbxjjh.get(i);
            Log.i("app", dataBean.getRWID());
            Gson gson = new Gson();
            Log.i("app", gson.toJson(dataBean));
            if (!dataBean.getRWID().equals("")) {
                if(dataBean.isWorkChecked()){
                    count++;
                }
            }
        }
        if (count != 0) {
            toastviewbymyself.makeText(getActivity(), "有巡检数据未上传,请检查!!!", Toast.LENGTH_LONG).show();
        }
    }

    private void setListData() {

        adapter = new DqgzDownloadAdapter(context, dbxjjh,view -> {
            CheckBox checkBox = (CheckBox) view;
            int index = (int) checkBox.getTag();
            dbxjjh.get(index).setChecked(checkBox.isChecked());
            int count = 0;
            for (int a = 0; a < dbxjjh.size(); a++) {
                if (dbxjjh.get(a).isChecked()) {
                    count++;
                }
            }
            xj_cb.setChecked(count == dbxjjh.size());
            adapter.notifyDataSetChanged();
        });
        lv.setAdapter(adapter);


        lv.setOnItemClickListener((adapterView, view, i, l) -> {

            Log.i("app",String.valueOf(i));

            dbxjjh.get(i - 1).setChecked(!dbxjjh.get(i - 1).isChecked());
            int count = 0;
            for (int a = 0; a < dbxjjh.size(); a++) {
                if (dbxjjh.get(a).isChecked()) {
                    count++;
                }
            }
            xj_cb.setChecked(count == dbxjjh.size());
            adapter.notifyDataSetChanged();
        });
    }

    private void uploadData() {
        noCheck = 0;//没有检查的数量
        selectCount = 0;
        boolean isSelectUpLoad = false;
        DqgzUpLoadBean scxjjhbean = new DqgzUpLoadBean();
        scxjjhbean.setAction("DQGZ_RWSC_SET");
        scxjjhbean.setSCR(username);
        List<DqgzUpLoadBean.data> datalist = new ArrayList<>();
        for (int i = 0; i < dbxjjh.size(); i++) {
            Dqgz dataBean = dbxjjh.get(i);
            if (dataBean.isChecked()) {
                isSelectUpLoad = true;
                selectCount++;
                DqgzUpLoadBean.data datas = new DqgzUpLoadBean.data();
                datas.setRWID(dataBean.getRWID());
                datas.setSCNR(dataBean.getSCNR());
                if(dataBean.getSCNR()==null){
                    datas.setSCNR("");
                }
                datas.setSCBZ(dataBean.getSCBZ());
                if(dataBean.getSCBZ()==null){
                    datas.setSCBZ("");
                }
                if(dataBean.isWorkChecked()){
                    datas.setDATE(dataBean.getDATE());
                }else{
                    datas.setDATE("");
                }
                datalist.add(datas);
                if(!dataBean.isWorkChecked()){
                    noCheck++;
                }
            }
        }
        scxjjhbean.setData(datalist);
        Gson gson = new Gson();
        Log.i("app",gson.toJson(scxjjhbean));
        if (noCheck > 0) {     //如果未检查的数量大于0 则提示有未检查的项目
            if(selectCount==noCheck){
                MeasureDialog measureDialog = new MeasureDialog(context, "至少有一条任务已检才能上传！", new MeasureDialog.AuditDialogListener() {
                    @Override
                    public void confirm() {

                    }

                    @Override
                    public void cancel() {

                    }
                });
                measureDialog.show();
            }else{
                MeasureDialog measureDialog = new MeasureDialog(context, "还有项目未检查，是否还要上传？", new MeasureDialog.AuditDialogListener() {
                    @Override
                    public void confirm() {
                        final String json = GsonUtils.GsonString(scxjjhbean);
                        sCData(json);
                    }

                    @Override
                    public void cancel() {

                    }
                });
                measureDialog.show();
            }
        } else {
            final String json = GsonUtils.GsonString(scxjjhbean);
            sCData(json);
        }
        if (!isSelectUpLoad) {
            showToast("请选择要上传的计划");
        }
    }

    private void sCData(String json) {
        Log.i("app",Contans.IP + Contans.DQGZ_UPLOAD_TASK);
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.DQGZ_UPLOAD_TASK, RequestMethod.POST);
        request.setDefineRequestBodyForJson(json);
        queue.add(1, request, new HttpResponseListener<>(getActivity(), request, callback, false, true, "上传数据中...请稍等..."));
    }

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


            Gson gson = new Gson();
            Log.i("app", gson.toJson(response.get()));
            StatusInfo2 info = GsonUtils.GsonToBean(response.get(), StatusInfo2.class);


            try {
                if (what == 1) {
                    if (info.getState() == 1) { //成功

                        showToast("上传数据成功");

                        List<Dqgz> dbxjjhTemp = new ArrayList<>();
                        //这里处理那个删除item，更新UI
                        for (int i = 0; i < dbxjjh.size(); i++) {

                            if (dbxjjh.get(i).isChecked()) {

                                DataSupport.deleteAll(Dqgz.class, "rwid = ? and username = ?", dbxjjh.get(i).getRWID(),username);

                                //dbxjjh.remove(dbxjjh.get(i));
                            }else{
                                dbxjjhTemp.add(dbxjjh.get(i));
                            }

                        }
                        dbxjjh.clear();
                        dbxjjh.addAll(dbxjjhTemp);

                        adapter.notifyDataSetChanged();

                        //刷新计划下载界面
                        Intent intent = new Intent(Contans.ACTION_REFRESHDOWNLOADPLAN);
                        //发送广播,刷新任务下载页面
                        DqgzUpFragment.this.requireActivity().sendBroadcast(intent);

                    } else {

                        showToast("上传数据失败");

                    }
                }


            } 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 deleteData() {
        int count = 0;
        for (int a = 0; a < dbxjjh.size(); a++) {
            if (dbxjjh.get(a).isChecked()) {
                count++;
            }
        }
        if(count==0){
            showToast("请选择要删除的计划");
            return;
        }
        MeasureDialog measureDialog = new MeasureDialog(context, "你确定要删除？", new MeasureDialog.AuditDialogListener() {
            @Override
            public void confirm() {
                for (int i = 0; i < dbxjjh.size(); i++) {
                    Log.i("app",String.valueOf(i));
                    Log.i("app",String.valueOf(dbxjjh.get(i).isChecked()));
                    if (dbxjjh.get(i).isChecked()) {
                        DataSupport.deleteAll(Dqgz.class, "rwid = ? and username = ?", dbxjjh.get(i).getRWID(),username);
                    }
                }

                xj_cb.setChecked(false);
                //刷新界面
                getDataInSQL();
                //刷新计划下载界面
                Intent intent = new Intent(Contans.ACTION_REFRESHDOWNLOADPLAN);
                //发送广播,刷新任务下载页面
                DqgzUpFragment.this.requireActivity().sendBroadcast(intent);

                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void cancel() {

            }
        });
        measureDialog.show();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        DqgzUpFragment.this.requireActivity().unregisterReceiver(myReceiver);
    }
}
