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

import android.content.ContentValues;
import android.os.Bundle;
import androidx.viewpager.widget.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.administrator.zhapp.DBModel.Qy;
import com.example.administrator.zhapp.DBModel.XwaqgcJh;
import com.example.administrator.zhapp.DBModel.XwaqgcSc;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.XwaqglInfo;
import com.example.administrator.zhapp.fragment.BaseFragment;
import com.example.administrator.zhapp.utils.SPUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.NoscrollViewPager;
import org.litepal.crud.DataSupport;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

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

    Spinner sp_gzdd;
    Spinner sp_cbs;
    EditText et_bgcr;
    NoscrollViewPager vp;
    Button btn_last;
    Button btn_next;
    TextView tvQy;
    EditText etCbs;
    EditText etGzp;
    EditText etNr;





    private int vpItem = 0;
    private List<XwaqglInfo> lists;
    private List<XwaqglInfo.ItemInfo> items;
    private int itemflag = 0;
    private List<View> views;

    private String code;
    private boolean nfcorewm;
    private String xwjljsid;

    private List<Qy> qys;
    private List<XwaqgcJh> jhs;

    private boolean isCheck = false;

    private String GCID = "";

    private boolean update = false;


    public XwaqgcglFragment() {
    }

    public static XwaqgcglFragment newInstance(String code, boolean nfcorewm, String xwjljsid) {
        XwaqgcglFragment fragment = new XwaqgcglFragment();
        Bundle args = new Bundle();
        args.putString("code", code);
        args.putBoolean("nfcorewm", nfcorewm);
        args.putString("xwjljsid", xwjljsid);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            code = bundle.getString("code");
            nfcorewm = bundle.getBoolean("nfcorewm");
            xwjljsid = bundle.getString("xwjljsid");
        }
    }


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

    @Override
    protected void initView() {
        sp_gzdd = view.findViewById(R.id.sp_gzdd);
        sp_cbs = view.findViewById(R.id.sp_cbs);
        et_bgcr = view.findViewById(R.id.et_bgcr);
        vp = view.findViewById(R.id.vp);
        btn_last = view.findViewById(R.id.btn_last);
        btn_next = view.findViewById(R.id.btn_next);
        tvQy = view.findViewById(R.id.tv_qy);
        etCbs = view.findViewById(R.id.et_cbs);
        etGzp = view.findViewById(R.id.et_gzp);
        etNr = view.findViewById(R.id.et_nr);

        btn_last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_next.setText(UiUtlis.getString(context, R.string.next));
                vpItem--;
                if (vpItem == -1) {
                    vpItem++;
                } else {
                    vp.setCurrentItem(vpItem, false);
                }
            }
        });

        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_next.getText().toString().equals("保存")) {
                    saveData();
                }
                if (vpItem == 5) {
                    btn_next.setText("保存");
                }
                vpItem++;
                if (vpItem == 7) {
                    //showToast("保存");
                    vpItem--;
                } else {
                    vp.setCurrentItem(vpItem, false);
                }
            }
        });

        initListData();
    }

    public void initData() {

        qys = new ArrayList<>();
        jhs = new ArrayList<>();

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

        if (nfcorewm) {
            qys = DataSupport.where("txm = ?", code).find(Qy.class);
        } else {
            qys = DataSupport.where("bqbm = ?", code).find(Qy.class);
        }

        if (qys.size() != 0) {
            for (Qy qy : qys) {
                tvQy.setText(qy.getAREANAME());
            }
        } else {
            showToast("扫描区域失败");
        }


        //初始化观察表界面
        initViewPagerView();
        vp.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return views.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(views.get(position));
                return views.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        });

    }

    //保存数据
    private void saveData() {

        //生成一个随机ID
        UUID uuid = UUID.randomUUID();
        String gcid = uuid.toString().replace("-", "").toUpperCase();

        int saveCount = 0;
        boolean flag = false;//是否有未选择项

        List<XwaqgcSc> saveScs = new ArrayList<>();

        if (!tvQy.getText().toString().isEmpty()) {

            if (!UiUtlis.getText(etCbs).isEmpty() || !UiUtlis.getText(et_bgcr).isEmpty()
                    || !UiUtlis.getText(etGzp).isEmpty() || !UiUtlis.getText(etNr).isEmpty()) {
                for (XwaqglInfo info : lists) {
                    for (XwaqgcJh jh : jhs) {

                        StringBuilder nr = new StringBuilder();
                        List<XwaqgcSc> scs = DataSupport.where("gcid = ? and jhid = ? and bt = ?",
                                GCID, jh.getJHID(), info.getTitle()).find(XwaqgcSc.class);

                        if (scs.size() == 0) {
                            //全部安全被选中
                            if (info.isChecked()) {
                                nr.append("全部安全");
                            } else {
                                for (XwaqglInfo.ItemInfo item : info.getList()) {
                                    if (item.isCheked()) {
                                        nr.append(item.getText() + "  ");
                                    }
                                }
                            }

                            if (!nr.toString().isEmpty()) {
                                XwaqgcSc sc = new XwaqgcSc();
                                sc.setJHID(jh.getJHID());
                                sc.setBGCR(et_bgcr.getText().toString());
                                sc.setBT(info.getTitle());
                                sc.setXBT(info.getContent());
                                sc.setNR(nr.toString());
                                sc.setCBS(UiUtlis.getText(etCbs));
                                sc.setGZDD(tvQy.getText().toString());
                                sc.setJCR((String) SPUtils.get(context, Contans.USERNAME, ""));
                                sc.setJCSJ(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                sc.setGZP(UiUtlis.getText(etGzp));
                                sc.setGZNR(UiUtlis.getText(etNr));
                                sc.setGCID(gcid);
                                sc.setSMFX(nfcorewm ? "扫描条码" : "NFC标签");
                                sc.setXWJLJSID(xwjljsid);
                                saveScs.add(sc);
                                saveCount++;
                            } else {
                                flag = true;
                            }

                        } else {
                            //全部安全被选中
                            if (info.isChecked()) {
                                nr.append("全部安全");
                            } else {
                                for (XwaqglInfo.ItemInfo item : info.getList()) {
                                    if (item.isCheked()) {
                                        nr.append(item.getText() + " ");
                                    }
                                }
                            }

                            if (!nr.toString().isEmpty()) {

                                ContentValues values = new ContentValues();
                                values.put("nr", nr.toString());
                                values.put("bgcr", UiUtlis.getText(et_bgcr));
                                values.put("cbs", UiUtlis.getText(etCbs));
                                values.put("gzp", UiUtlis.getText(etGzp));
                                values.put("gznr", UiUtlis.getText(etNr));
                                int update = DataSupport.updateAll(XwaqgcSc.class, values, "gcid = ? and jhid = ? and bt = ?",
                                        GCID, jh.getJHID(), info.getTitle());

                                if (update != 0) {
                                    saveCount++;
                                    this.update = true;
                                }
                            } else {
                                flag = true;
                            }
                        }
                    }
                }
                if (saveCount == 7) {
                    DataSupport.saveAll(saveScs);
                    showToast("保存成功");
                    if (!this.update) {
                        GCID = gcid;
                    }
                }

                if (flag) {
                    showToast("你还有检查项目没有选");
                }

            } else {
                showToast("你还有数据未填写");
            }
        } else {
            showToast("区域为空，不能保存");
        }
        //List<XwaqgcSc> sc = DataSupport.findAll(XwaqgcSc.class);
        //System.out.println(GsonUtils.GsonString(sc));
        //Logger.json("上传SJON" + GsonUtils.GsonString(sc));
    }

    /**
     * 初始化条目数据
     */
    private void initListData() {
        lists = new ArrayList<>();
        String[][] text = {{"调整个人防护装备", "改变原来的位置", "重新安排工作", "停止工作", "收拾工具", "遮掩/离开", "其他"},
                {"眼睛和脸部", "耳部", "头部", "手和手臂", "脚和腿部", "呼吸系统", "躯干", "其他"},
                {"没有建立", "不适用", "没有及时更新", "不可获取", "员工不知道或不理解", "没有遵照执行", "没有办理作业许可证", "员工没有有效的上岗证", "其他"},
                {"被撞击", "被夹住", "高处坠落", "绊倒或滑倒", "接触极端温度的物体", "触电", "接触、吸入或吞食有害物质", "接触转动设备", "搬运负荷过重", "接触振动设备", "其他"},
                {"不适合该作业", "未正确使用工具与设备", "工具和设备本身不安全", "需要计量的仪器仪表没有校定", "其他"},
                {"不符合人体工效学原则", "重复的动作", "躯体位置不良", "不适当的姿势", "工作区域设计不佳", "工具和把手不方便使用", "照明不足", "其他"},
                {"作业区域不整洁", "工作场所不能做到井然有序", "材料及工具的摆放不适当", "设备有跑冒滴漏现象", "其他"}
                //{"已检查未发现不合格功能项"}
        };
        String[] title = {"1.员工的反应", "2.个人防护装备", "3.程序和标准", "4.员工的位置", "5.工具与设备", "6.人体工效学", "7.环境整洁"
                //, "8.检查结果"
        };
        String[] context = {"观察到的人员的异常反应", "未使用或未正确使用,是否完好", "观察到的问题：", "可能的问题", "观察到的问题：", "办公室、操作和检维修环境", "观察到的问题："
                // , "没有发现问题"
        };

        for (int i = 0; i < title.length; i++) {
            items = new ArrayList<>();
            for (int j = 0; j < text[i].length; j++) {
                XwaqglInfo.ItemInfo iteminfo = new XwaqglInfo.ItemInfo(text[i][j], false);
                items.add(iteminfo);
            }
            XwaqglInfo info = new XwaqglInfo(title[i], context[i], items);
            lists.add(info);
        }
    }

    /**
     * 初始化ViewPager的视图
     */
    private void initViewPagerView() {

        views = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            final List<CheckBox> cbs = new ArrayList<>();
            View view = View.inflate(getContext(), R.layout.xwaq_itme, null);
            final CheckBox cb_all = (CheckBox) view.findViewById(R.id.cb_all);
            cb_all.setTag(i);
            TextView title = (TextView) view.findViewById(R.id.title);
            TextView tv_ms = (TextView) view.findViewById(R.id.tv_ms);
            final LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll);
            title.setText(lists.get(i).getTitle());
            tv_ms.setText(lists.get(i).getContent());

            final int finalI1 = i;
            cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    lists.get(finalI1).setChecked(isChecked);
                    //如果选中，就不可以选。
                    if (cbs.size() != 0) {
                        if (isChecked) {
                            for (CheckBox cb : cbs) {
                                cb.setEnabled(false);
                            }
                        } else {
                            for (CheckBox cb : cbs) {
                                cb.setEnabled(true);
                            }
                        }
                    }
                }
            });

            for (int j = 0; j < lists.get(i).getList().size(); j++) {
                final CheckBox checkBox = new CheckBox(getContext());
                checkBox.setText(lists.get(i).getList().get(j).getText());
                checkBox.setChecked(lists.get(i).getList().get(j).isCheked());
                cbs.add(checkBox);

                final int finalJ = j;
                final int finalI = i;
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        isCheck = b;
                        lists.get(finalI).getList().get(finalJ).setCheked(b);

                        boolean checked = true;
                        for (CheckBox cb : cbs) {
                            if (cb.isChecked()) {
                                checked = false;
                            }
                        }
                        cb_all.setEnabled(checked);
                    }
                });
                ll.addView(checkBox);
            }
            views.add(view);
        }
    }
}