package com.bonait.bnframework.modules.home.fragment.mode;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPENAME;
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL;
import com.bonait.bnframework.common.db.res.ResGoodsRecipe;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.goodpf_apapter;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.suke.widget.SwitchButton;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Delayed;

import butterknife.BindView;
import butterknife.ButterKnife;

public class add_silos_ck extends LinearLayout {

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.close_from)
    Button close_from;

    @BindView(R.id.buchongyuanliao)
    Button buchongyuanliao;

    @BindView(R.id.manguan)
    Button manguan;

    @BindView(R.id.shezhi)
    Button shezhi;

    @BindView(R.id.jiaozhun)
    Button jiaozhun;//校准

    @BindView(R.id.queren)
    Button queren;//校准


    @BindView(R.id.xuhao)
    TextView xuhao;
    @BindView(R.id.wuliaoname)
    TextView name;
    @BindView(R.id.wuliaoimage)
    ImageView wuliaoimage;
    @BindView(R.id.baifenbi)
    TextView baifenbi;

    @BindView(R.id.control_switch_shoudong)
    Button control_switch_shoudong;

    @BindView(R.id.control_huishou)
    Button control_huishou;

    @BindView(R.id.liaochang_sz)
    RelativeLayout liaochang_sz;

    @BindView(R.id.editsp_wl)
    Spinner editsp_wl;

    @BindView(R.id.edittext1)
    EditText edittext1;

    @BindView(R.id.edittext2)
    EditText edittext2;

    @BindView(R.id.control_switch)
    SwitchButton control_switch;//料仓开关

    @BindView(R.id.runtime)
    Chronometer runtime;//

    @BindView(R.id.jishiqi)
    RelativeLayout jishiqi;//

    ArrayList<BPA_MATERIAL> materials = new ArrayList<>();

    List<String> names = new ArrayList<>();


    /**
     * 点击事件
     */
    public MyClickListener mListener = null;
    private View root;

    public add_silos_ck(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        root = LayoutInflater.from(context).inflate(R.layout.dialog_add_silos_ck, this);
        ButterKnife.bind(this, root);
        Init();
    }


    public void Init() {
        //初始化界面数据
        initData();
        //初始化界面控件的事件
        initEvent();
    }


    private void initData() {
        materials.clear();
        List<BPA_MATERIAL> bpa_materials = QueryDB.GetMaterialALL();
        for (BPA_MATERIAL item : bpa_materials) {
            materials.add(item);
        }
        BPA_MATERIAL wsz = new BPA_MATERIAL();
        wsz.name = "未设置";
        wsz.id = "";
        materials.add(wsz);

        names.clear();
        for (BPA_MATERIAL item : materials) {
            names.add(item.name);
        }
        SetAdapter(editsp_wl, names);
    }

    public void SetAdapter(Spinner spinner, List<String> map) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text_item, map);
        adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }

    boolean ismanguan = false;

    private void initEvent() {
        buchongyuanliao.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                QueryDB.UpdateYL(lcMode.id, lcMode.siloszl);
                lcMode.silosmargin = lcMode.siloszl;
                SetData(lcMode);
                //补充原料
                if (mListener != null) {
                    mListener.clickListenerNew(view, 1, lcMode);
                }
            }
        });
        name.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                int index = 0;
                int count = 0;
                for (BPA_MATERIAL item : materials) {
                    if (item.name.equals(lcMode.materialName)) {
                        index = count;
                    }
                    count++;
                }
                String[] items = names.toArray(new String[names.size()]);
                final int checkIndex = index;
                new QMUIDialog.CheckableDialogBuilder(root.getContext())
                        .addItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                BPA_SILOSANDMATERIAL item = new BPA_SILOSANDMATERIAL();
                                BPA_MATERIAL material = materials.get(which);
                                item.silosID = lcMode.id;
                                item.materialID = material.id;
                                //更新
                                if (QueryDB.UpdateSilosAndMaterial(item)) {
                                    lcMode.materialId = material.id;
                                    lcMode.materialName = material.name;
                                    if (mListener != null) {
                                        mListener.clickListenerNew(view, 5, lcMode);
                                        name.setText(material.name);
                                    }
                                    SetData(lcMode);
                                    dialog.dismiss();
                                }
                            }
                        })
                        .setCheckedIndex(checkIndex)
                        .show();
            }
        });
        manguan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ismanguan == false) {
                    ismanguan = true;
                    StartTime();
                    ExecuteTheRecipe.WritePLC("手自切换", false, null);
                    int time = lcMode.bValue <= 0 ? 10 : lcMode.bValue;//默认10秒
                    ExecuteTheRecipe.WritePLC("手动控制" + lcMode.num, true, null);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ExecuteTheRecipe.WritePLC("手动控制" + lcMode.num, false, null);
                            ToastUtils.info("满管成功!!!");
                            ismanguan = false;
                            StopTime();
                        }
                    }, time * 1000);
                    //满管
                    if (mListener != null) {
                        mListener.clickListenerNew(view, 2, lcMode);
                    }
                } else {
                    ToastUtils.warning("满管中,请稍后!!!");
                }
            }
        });
        shezhi.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                liaochang_sz.setVisibility(View.VISIBLE);
                int index = 0;
                int count = 0;
                for (BPA_MATERIAL item : materials) {
                    if (item.name.equals(lcMode.materialName)) {
                        index = count;
                    }
                    count++;
                }
                final int checkIndex = index;
                editsp_wl.setSelection(checkIndex);

                edittext1.setText(lcMode.siloszl + "");
                edittext2.setText(lcMode.warningValue + "");
                //设置
                if (mListener != null) {
                    mListener.clickListenerNew(view, 3, lcMode);
                }

            }
        });

        queren.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                String type = editsp_wl.getSelectedItem().toString();
                String zl = edittext1.getText().toString();
                if (zl == null || zl.isEmpty()) {
                    ToastUtils.warning("料仓容量不能为空!");
                    return;
                }
                String bjz = edittext2.getText().toString();
                if (bjz == null || bjz.isEmpty()) {
                    ToastUtils.warning("报警值不能为空!");
                    return;
                }

                int zl_int = 0;
                int bj_int = 0;

                try {
                    zl_int = Integer.parseInt(zl);
                    bj_int = Integer.parseInt(bjz);
                } catch (Exception ex) {

                }

                if (bj_int > zl_int) {
                    ToastUtils.warning("报警值不能大于料仓容量!");
                    return;
                }

                QueryDB.UpdateSilosZL(lcMode.id, zl_int);
                QueryDB.UpdateSilosBJZ(lcMode.id, bj_int);
                lcMode.siloszl = zl_int;
                lcMode.warningValue = bj_int;

                BPA_SILOSANDMATERIAL item = new BPA_SILOSANDMATERIAL();
                BPA_MATERIAL material = materials.get(editsp_wl.getSelectedItemPosition());
                item.silosID = lcMode.id;
                item.materialID = material.id;
                //更新
                if (QueryDB.UpdateSilosAndMaterial(item)) {
                    lcMode.materialId = material.id;
                    lcMode.materialName = material.name;
                }
                SetData(lcMode);
                liaochang_sz.setVisibility(View.GONE);

                if (mListener != null) {
                    mListener.clickListenerNew(view, 6, lcMode);
                }
            }
        });
        jiaozhun.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //校准
                if (mListener != null) {
                    mListener.clickListenerNew(view, 4, lcMode);
                }
            }
        });
        close_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                liaochang_sz.setVisibility(View.GONE);
                if (mListener != null) {
                    mListener.clickListenerNew(v, 0, null);
                }
            }
        });


        control_switch_shoudong.setOnTouchListener((view,motionEvent)->{
            String name = lcMode.name + lcMode.num+"启停控制";
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                Log.e("鼠标", "按下:2222 ");
                ExecuteTheRecipe.WritePLC("清洗模式", true,null);
                try {
                    Thread.sleep(100L);//避免启动的时候还是按时间出料
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                ExecuteTheRecipe.WritePLC(name, true, null);
            } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                Log.e("鼠标", "松开:33333 ");
                ExecuteTheRecipe.WritePLC(name, false, null);
                try {
                    Thread.sleep(100L);//避免启动的时候还是按时间出料
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                ExecuteTheRecipe.WritePLC("清洗模式", false,null);
            }
            return false;
        });


//        control_switch_shoudong.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
//                    Log.e("鼠标", "按下: ");
//                    ExecuteTheRecipe.WritePLC("手自切换", false, new IWriteCallBack() {
//                        @Override
//                        public void onSuccess() {
//                            ExecuteTheRecipe.WritePLC("手动控制" + lcMode.num, true, null);
//                        }
//
//                        @Override
//                        public void onFailure(String ErrorMsg) {
//                        }
//                    });
//                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
//                    Log.e("鼠标", "松开: ");
//                    ExecuteTheRecipe.WritePLC("手动控制" + lcMode.num, false, null);
//                }
//                return false;
//            }
//        });

        control_huishou.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.e("鼠标", "按下: ");
                    ExecuteTheRecipe.WritePLC("手自切换", false, new IWriteCallBack() {
                        @Override
                        public void onSuccess() {
                            ExecuteTheRecipe.WritePLC("M_外置仓" + lcMode.num + "反转", true, null);
                        }
                        @Override
                        public void onFailure(String ErrorMsg) {
                        }
                    });
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    Log.e("鼠标", "松开: ");
                    ExecuteTheRecipe.WritePLC("M_外置仓" + lcMode.num + "反转", false, null);
                }
                return false;
            }
        });

        control_switch.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                //设置
                lcMode.status = isChecked ? 0 : 1;
                QueryDB.UpdateSilosStatus(lcMode.id, isChecked);
            }
        });
    }

    lcMode lcMode = null;

    public void SetData(lcMode _good) {
        lcMode = _good;
        control_switch.setChecked(_good.status == 0 ? true : false);
        title.setText("查看料仓-(" + lcMode.name + ")");
        xuhao.setText(lcMode.exp + "");

        if (lcMode.name.equals("外置仓")) {
            control_huishou.setVisibility(View.VISIBLE);
        } else {
            control_huishou.setVisibility(View.GONE);
        }

        name.setText(lcMode.materialName.isEmpty() ? "未设置" : (lcMode.materialName + ""));
        if (lcMode.materialName.isEmpty() || lcMode.materialName.equals("未设置")) {
            wuliaoimage.setImageResource(R.mipmap.newsilos);
            baifenbi.setText("");
        } else {
            if (lcMode.warningValue >= lcMode.silosmargin || lcMode.siloszl == 0) {
                wuliaoimage.setImageResource(R.mipmap.newsilos_yc);
            } else {
                wuliaoimage.setImageResource(R.mipmap.newsilos);
            }
            baifenbi.setText(get(lcMode.silosmargin, lcMode.siloszl));
        }
    }

    public static String get(int up, int down) {
        if (down == 0) {
            return "0%";
        }
        double value = new BigDecimal((float) up / down).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return new DecimalFormat("#%").format(value);
    }


    /**
     * 启动定时器
     */
    public void StartTime() {
        jishiqi.setVisibility(View.VISIBLE);

        runtime.setBase(SystemClock.elapsedRealtime());
        runtime.start();
    }

    /**
     * 停止定时器
     */
    public int StopTime() {
        jishiqi.setVisibility(View.GONE);
        long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
        runtime.stop();

        int time = (int) (elapsedMillis / 1000);
        return time;//当前点击多少秒
    }
}
