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.XwaqgcJh;
import com.example.administrator.zhapp.DBModel.XwaqgcSc;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.entity.XwaqglInfo;
import com.example.administrator.zhapp.fragment.BaseFragment;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.NoscrollViewPager;
import org.litepal.crud.DataSupport;
import java.util.ArrayList;
import java.util.List;

public class XwaqgcxgFragment extends BaseFragment {

    Spinner spGzdd;
    Spinner spCbs;
    TextView tvQy;
    EditText etCbs;
    EditText etBgcr;
    EditText etGzp;
    EditText etNr;
    NoscrollViewPager vp;
    Button btnLast;
    Button btnNext;



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

    private XwaqgcSc sc;

    private List<XwaqgcSc> scs;


    public static XwaqgcxgFragment newInstance(XwaqgcSc sc) {
        XwaqgcxgFragment fragment = new XwaqgcxgFragment();
        Bundle args = new Bundle();
        args.putParcelable("xwaqgcsc", sc);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getArguments();

        if (bundle != null) {
            sc = bundle.getParcelable("xwaqgcsc");
        }
    }

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

    @Override
    protected void initView() {

        spGzdd = view.findViewById(R.id.sp_gzdd);
        spCbs = view.findViewById(R.id.sp_cbs);
        tvQy = view.findViewById(R.id.tv_qy);
        etCbs = view.findViewById(R.id.et_cbs);
        etBgcr = view.findViewById(R.id.et_bgcr);
        etGzp = view.findViewById(R.id.et_gzp);
        etNr = view.findViewById(R.id.et_nr);
        vp = view.findViewById(R.id.vp);
        btnLast = view.findViewById(R.id.btn_last);
        btnNext = view.findViewById(R.id.btn_next);

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

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

        if (sc != null) {
            tvQy.setText(sc.getGZDD());
            etBgcr.setText(sc.getBGCR());
            etCbs.setText(sc.getCBS());
            etGzp.setText(sc.getGZP());
            etNr.setText(sc.getGZNR());
        }
    }

    @Override
    public void initData() {
        lists = new ArrayList<>();
        items = new ArrayList<>();
        views = new ArrayList<>();
        jhs = new ArrayList<>();
        scs = new ArrayList<>();

        scs.addAll(DataSupport.where("gcid = ?", sc.getGCID()).find(XwaqgcSc.class));
        jhs.addAll(DataSupport.findAll(XwaqgcJh.class));

        if (scs.size() == 7) {
            initListData();
            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() {

        int saveCount = 0;
        boolean flag = false;//是否未选择项
        if (!UiUtlis.getText(etCbs).isEmpty() || !UiUtlis.getText(etBgcr).isEmpty()
                || !UiUtlis.getText(etGzp).isEmpty() || !UiUtlis.getText(etNr).isEmpty()) {
            for (XwaqglInfo info : lists) {
                for (XwaqgcJh jh : jhs) {
                    StringBuilder nr = new StringBuilder();
                    //全部安全被选中
                    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(etBgcr));
                        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 = ?",
                                sc.getGCID(), jh.getJHID(), info.getTitle());

                        if (update != 0) {
                            saveCount++;
                        }
                    } else {
                        flag = true;
                    }
                }
            }
            if (saveCount == 7) {
                showToast("保存成功");
            }

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

        } else {
            showToast("你还有数据未填写");
        }
    }


    private void initViewPagerView() {

        views = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            final List<CheckBox> cbs = new ArrayList<>();
            View view = View.inflate(context, 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);
                            }
                        }
                    }
                }
            });

            String[] s = scs.get(i).getNR().split(" ");

            for (int j = 0; j < lists.get(i).getList().size(); j++) {

                final int finalJ = j;
                final int finalI = i;

                final CheckBox checkBox = new CheckBox(context);
                checkBox.setText(lists.get(i).getList().get(j).getText());
                checkBox.setChecked(lists.get(i).getList().get(j).isCheked());
                cbs.add(checkBox);

                for (String str : s) {
                    if (str.equals(lists.get(i).getList().get(j).getText())) {
                        checkBox.setChecked(true);
                        cb_all.setEnabled(false);
                        lists.get(finalI).getList().get(finalJ).setCheked(true);
                        break;
                    }

                    if (str.equals("全部安全")) {
                        cb_all.setChecked(true);
                        checkBox.setEnabled(false);
                        lists.get(finalI1).setChecked(true);
                        break;
                    }
                }

                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean 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);
        }
    }


    /**
     * 初始化条目数据
     */
    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);
        }
    }
}
