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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.zhapp.BaseListViewAdapter.CommonAdapter;
import com.example.administrator.zhapp.BaseListViewAdapter.ViewHolder;
import com.example.administrator.zhapp.DBModel.XwaqgcJh;
import com.example.administrator.zhapp.DBModel.XwaqgcJs;
import com.example.administrator.zhapp.DBModel.XwaqgcSc;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.BaseActivity;
import com.example.administrator.zhapp.activity.MipcaActivityCapture;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.SbdjInfo;
import com.example.administrator.zhapp.entity.StatusInfo;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.NohttpUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.WaitDialog;
import com.orhanobut.logger.Logger;
import com.yolanda.nohttp.FileBinary;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import org.litepal.crud.DataSupport;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 安健环巡查管理-行为安全观察管理
 */
public class AxwaqgcglActivity extends BaseActivity {

    ListView lv;
    Button btnSys;
    Button btnSc;
    Button btnXg;
    TextView tvNodata;

    private View headview;
    private List<SbdjInfo> list;
    private CommonAdapter<XwaqgcJh> adapter;
    private List<XwaqgcJh> jhs;
    private CheckBox cb;
    private int requestCount = 0;//请求数量
    private int successCount = 0;//成功数量
    private WaitDialog dialog;

    private void findView() {
        lv = findViewById(R.id.lv);
        btnSys = findViewById(R.id.btn_sys);
        btnSc = findViewById(R.id.btn_sc);
        btnXg = findViewById(R.id.btn_xg);
        tvNodata = findViewById(R.id.tv_nodata);
        btnSys.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (jhs.size() != 0) {
                    Intent intent = new Intent(context, MipcaActivityCapture.class);
                    startActivityForResult(intent, 1);
                } else {
                    showToast("你还没有计划");
                }
            }
        });
        btnSc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上传
                uploadData();
            }
        });
        btnXg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //修改记录
                Intent intent = new Intent(AxwaqgcglActivity.this, XwaqgcUploadActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public int getContentViewID() {
        return R.layout.activity_axwaqgcgl;
    }

    @Override
    protected void initView() {
        findView();
    }

    public void initData() {

        jhs = new ArrayList<>();

        initNFC();
        setTitle("行为安全观察");
        setBack();
        dialog = new WaitDialog(context, "上传中...");
        list = new ArrayList<>();
        headview = View.inflate(context, R.layout.xzjh_item, null);

        headview.findViewById(R.id.tv_zt).setVisibility(View.VISIBLE);
        headview.findViewById(R.id.zt).setVisibility(View.VISIBLE);

        TextView tv = (TextView) headview.findViewById(R.id.tv_jhlx);
        tv.setText("到期时间");
        headview.findViewById(R.id.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 < jhs.size(); i++) {
                        jhs.get(i).setChecked(true);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    for (int i = 0; i < jhs.size(); i++) {
                        jhs.get(i).setChecked(false);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });


        jhs.addAll(DataSupport.findAll(XwaqgcJh.class));


        adapter = new CommonAdapter<XwaqgcJh>(context, R.layout.xzjh_item, jhs) {
            @Override
            protected void convert(ViewHolder viewHolder, XwaqgcJh item, final int position) {

                viewHolder.setVisible(R.id.tv_zt, true);
                viewHolder.setVisible(R.id.zt, true);
                List<XwaqgcSc> xwaqgcScs = DataSupport.where("jhid = ?", item.getJHID()).find(XwaqgcSc.class);

                viewHolder.setOnClickListener(R.id.cb, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CheckBox checkBox = (CheckBox) v;
                        jhs.get(position).setChecked(checkBox.isChecked());
                        int count = 0;
                        for (int a = 0; a < jhs.size(); a++) {
                            if (jhs.get(a).isChecked()) {
                                count++;
                            }
                        }
                        cb.setChecked(count == jhs.size());
                        adapter.notifyDataSetChanged();
                    }

                });
                viewHolder.setChecked(R.id.cb, item.isChecked());
                viewHolder.setText(R.id.tv_xh, (position + 1) + "");
                viewHolder.setText(R.id.tv_jhmc, item.getJHMC());
                viewHolder.setText(R.id.tv_jhlx, item.getDQSJ());

                if (xwaqgcScs.size() != 0) {
                    viewHolder.setText(R.id.tv_zt, "已录入");
                } else {
                    viewHolder.setText(R.id.tv_zt, "未录入");
                }
            }
        };
        lv.setEmptyView(tvNodata);
        lv.addHeaderView(headview, null, false);
        lv.setAdapter(adapter);
    }

    //上传数据
    private void uploadData() {

        for (XwaqgcJh jh : jhs) {
            //如果已经选择
            if (jh.isChecked()) {
                List<XwaqgcSc> scs = DataSupport.where("jhid = ?", jh.getJHID()).find(XwaqgcSc.class);
                if (scs.size() != 0) {
                    if (!dialog.isShowing()) {
                        dialog.show();
                    }
                    scData(jh.getJHID());
                } else {
                    showToast("你还没有录入信息");
                }
            }
        }
    }

    private void scData(String jhid) {
        requestCount++;
        Request<String> sc = NoHttp.createStringRequest(Contans.IP + Contans.XWAQGCSC, RequestMethod.POST);
        List<XwaqgcSc> xwaq = DataSupport.where("jhid = ?", jhid).find(XwaqgcSc.class);
        //String json = GsonUtils.GsonString(DataSupport.where("jhid = ?", jhid).find(XwaqgcSc.class));
        //Logger.json(json);
        String json = "{\"Rows\":" + GsonUtils.GsonString(xwaq) + ",\"Total\": " + xwaq.size() + "}";
        json = new String(json.getBytes(), StandardCharsets.UTF_8);
        sc.setDefineRequestBodyForJson(UiUtlis.encoder(json));
        NohttpUtils.getInstance().add(this, 0, sc, callback, false, false, "");

        List<XwaqgcJs> jss = DataSupport.where("jhid = ?", jhid).find(XwaqgcJs.class);
        for (XwaqgcJs js : jss) {
            requestCount++;
            Request<String> xcjs = NoHttp.createStringRequest(Contans.IP + Contans.XWAQGCJS +
                    "?jhid=" + UiUtlis.encoder(js.getJhid()) +
                    "&jsr=" + UiUtlis.encoder(js.getJsr()) +
                    "&areacode=" + UiUtlis.encoder(js.getAreacode()) +
                    "&xwzt=" + UiUtlis.encoder(js.getXwzt()) +
                    "&kndz=" + UiUtlis.encoder(js.getKndz()) +
                    "&jzcs=" + UiUtlis.encoder(js.getJzcs()) +
                    "&xwjljsid=" + UiUtlis.encoder(js.getXwjljsid()), RequestMethod.POST);
            xcjs.add(Contans.FILEPS, new FileBinary(new File(js.getPath())));
            NohttpUtils.getInstance().add(this, 0, xcjs, callback, false, false, "");
        }
    }

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

            Logger.d(response.get());

            System.out.println(response.get());

            try {
                StatusInfo info = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
                if (info != null) {
                    if (info.getTotal() != 0) {
                        if (info.getRows().get(0).getStatus().equals("1")) {
                            successCount++;
                        } else {
                            dialog.dismiss();
                            NohttpUtils.getInstance().cancelAll();
                            showToast("上传失败");
                        }
                    }
                }
                //上传成功
                if (requestCount == successCount && successCount != 0) {
                    dialog.dismiss();
                    showToast("上传成功");
                    removeData();
                }
            } catch (Exception e) {
                showToast("数据出错");
                dialog.dismiss();
            }
        }

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

    //删除数据
    private void removeData() {
        for (XwaqgcJh jh : jhs) {
            if (jh.isChecked()) {
                int a = DataSupport.deleteAll(XwaqgcJh.class, "jhid = ?", jh.getJHID());
                int b = DataSupport.deleteAll(XwaqgcSc.class, "jhid = ?", jh.getJHID());
                int c = DataSupport.deleteAll(XwaqgcJs.class, "jhid = ?", jh.getJHID());
            }
        }
        jhs.clear();
        jhs.addAll(DataSupport.findAll(XwaqgcJh.class));
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    Intent intent = new Intent(AxwaqgcglActivity.this, AxwaqgcglDetaliActivity.class);
                    intent.putExtra(Contans.KEY_BQBM, (String) bundle.get("result"));
                    intent.putExtra(Contans.NFCOREWM, true);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public void handleNfc(String result) {
        super.handleNfc(result);

        if (jhs.size() != 0) {
            Intent intent = new Intent(AxwaqgcglActivity.this, AxwaqgcglDetaliActivity.class);
            intent.putExtra(Contans.KEY_BQBM, result);
            intent.putExtra(Contans.NFCOREWM, false);
            startActivity(intent);
        } else {
            showToast("你还没有计划");
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (adapter != null) {
            cb.setChecked(false);
            jhs.clear();
            jhs.addAll(DataSupport.findAll(XwaqgcJh.class));
            adapter.notifyDataSetChanged();
        }
    }
}