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

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
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.ExecuteTheRecipe;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class add_silos_message extends LinearLayout {

    //region 界面变量
    @BindView(R.id.close_from)
    Button close_from;
    @BindView(R.id.silosname)
    TextView silosname;//
    @BindView(R.id.xuhao)
    TextView xuhao;//1号
    @BindView(R.id.t_text)
    TextView t_text;//1号


    @BindView(R.id.zongliang)
    EditText zongliang;
    @BindView(R.id.gaojingrongliang)
    EditText gaojingrongliang;
    @BindView(R.id.tiaoliaobiaoding)
    EditText tiaoliaobiaoding;
    @BindView(R.id.editsp_wl)
    Spinner editsp_wl;

    @BindView(R.id.click_dcqx)
    imagebuttom click_dcqx;

    public MyClickListener mListener = null;
    private View root;
    private Context contextMian;
    //endregion

    //region 私立
    public add_silos_message(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        contextMian = context;
        root = LayoutInflater.from(context).inflate(R.layout.dialog_silos_message, this);
        ButterKnife.bind(this, root);
        initEvent();
    }
    //endregion

    //region 私有函数
    /**
     * 初始化事件
     */
    private void initEvent() {
        close_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    ExecuteTheRecipe.WritePLC("料仓" + mode.num + "校准开关", false,null);
                    ExecuteTheRecipe.WritePLC("料仓" + mode.num + "手动开关", false, null);
                    mListener.clickListener(v,  mode);
                }
            }
        });

        /**
         * 单仓清洗
         */
        click_dcqx.mListener=new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
                boolean status = (boolean) data;
                ExecuteTheRecipe.WritePLC("料仓" + mode.num + "手动开关", status, null);
            }

            @Override
            public void clickListenerNew(View v, int k, Object data) {

            }
        };
    }

    /**
     * 初始化数据
     */
    private void initData() {
        xuhao.setText(GetNum(mode.num)+"");
        silosname.setText(mode.materialName+"");
        int bfb=0;
        int yl=mode.silosmargin;
        int zl=mode.siloszl;
        if(zl==0)
        {
            bfb=0;
        }else
        {
            bfb=((yl*100)/zl)>=100?100:((yl*100)/zl);
        }
        t_text.setText(bfb+"%");



        zongliang.setText(mode.siloszl+"");
        gaojingrongliang.setText(mode.warningValue+"");

        int index = 0;
        int count = 0;
        for (BPA_MATERIAL item : materials) {
            if (item.name.equals(mode.materialName)) {
                index = count;
            }
            count++;
        }
        final int checkIndex = index;
        editsp_wl.setSelection(checkIndex);
    }
    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.save_rlsz,R.id.save_ghtl,
            R.id.save_tlbd,R.id.click_dcbl,R.id.click_lcjz})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.save_rlsz:
                String zl= zongliang.getText().toString();
                String wg= gaojingrongliang.getText().toString();
                if(DataYanZheng(zl) && DataYanZheng(wg))
                {
                    mode.siloszl=Integer.parseInt(zl);
                    mode.warningValue=Integer.parseInt(wg);
                    QueryDB.UpdateSilosBJZ(mode.id,mode.warningValue);
                    QueryDB.UpdateSilosZL(mode.id,mode.siloszl);
                    initData();
                    ToastUtils.info("容量保存成功！");
                }
                break;
            case R.id.save_tlbd:
                String jzzl = tiaoliaobiaoding.getText().toString();

                if (jzzl.equals("")) {
                    ToastUtils.warning("校准重量不能为空！");
                    return;
                }
                int jzzl_1 = 0;
                try {
                    //jzzl_1 = (int) Math.round((Double.parseDouble(jzzl) * 10));
                    jzzl_1 = (int) Math.round((Double.parseDouble(jzzl)));//  ()int) Math.round((Double.parseDouble(jzzl)));
                } catch (Exception e) {
                    ToastUtils.error("校准重量！" + e.getMessage());
                    return;
                }
                ExecuteTheRecipe.WritePLC("料仓"+mode.num+"校准值",jzzl_1,null);
                ToastUtils.warning("调料标定成功！");
                break;
            case R.id.save_ghtl:
                BPA_SILOSANDMATERIAL item = new BPA_SILOSANDMATERIAL();
                BPA_MATERIAL material = materials.get(editsp_wl.getSelectedItemPosition());
                item.silosID = mode.id;
                item.materialID = material.id;
                //更新
                if (QueryDB.UpdateSilosAndMaterial(item)) {
                    mode.materialId = material.id;
                    mode.materialName = material.name;
                }
                initData();
                ToastUtils.info("更换物料成功！");
                break;
            case R.id.click_dcbl:
                QueryDB.UpdateYL(mode.id,mode.siloszl);
                mode.silosmargin=mode.siloszl;
                initData();
                ToastUtils.info("补料成功！");
                break;
            case R.id.click_lcjz:
                ExecuteTheRecipe.WritePLC("校准时间", 50, null);//默认校准时间5秒
                ExecuteTheRecipe.WritePLC("料仓" + mode.num + "校准开关", true,null);
                ExecuteTheRecipe.WritePLC("开始校正",true,null);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ExecuteTheRecipe.WritePLC("开始校正", false, null);
                    }
                }, 500);
                ToastUtils.info("开始校准！");
                break;
        }
    }

    /**
     * 数据验证
     * @param data
     * @return
     */
    private boolean DataYanZheng(String data)
    {
        try {
            if(data==null || data.isEmpty())
            {
                ToastUtils.warning("数据不能为空！");
                return false;
            }

            int k= Integer.parseInt(data);

            return true;
        }catch (Exception ex)
        {
            ToastUtils.warning("数据格式错误！");
            return false;
        }
    }

    /**
     * 设置下拉框
     * @param spinner
     * @param map
     */
    private 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);
    }

    /**
     * 获取号数
     * @param num
     * @return
     */
    public String GetNum(int num)
    {
        if(num==1)
        {
            return "①";
        }else if(num==2)
        {
            return "②";
        }else if(num==3)
        {
            return "③";
        }else if(num==4)
        {
            return "④(水阀)";
        }else if(num==5)
        {
            return "⑤";
        }else if(num==6)
        {
            return "⑥";
        }else
        {
            return "①";
        }
    }
    //endregion

    //region 公共函数
    public lcMode mode=null;
    public ArrayList<BPA_MATERIAL> materials = new ArrayList<>();
    public List<String> names = new ArrayList<>();
    /**
     * 设置数据
     *
     * @param
     */
    public void SetData(lcMode data,  Activity activity) {
        try {
            click_dcqx.SetStatus(false);
            mode = data;
            //region 设置物料下拉框
            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);
            //endregion
            new Thread(new Runnable() {
                @Override
                public void run() {

                    String jzz="0";
                    Object obj1= ExecuteTheRecipe.ReadPLC("料仓"+mode.num+"校准值");
                    if(obj1!=null)
                    {
                        String s = String.valueOf(obj1);
                        //jzz = String.format("%.1f", (Double.parseDouble(s) / 10));
                        jzz = s;//String.format("%.1f", (Double.parseDouble(s)));
                    }else
                    {
                        String s = String.valueOf(0);
                        jzz = "0";//String.format("%.1f", (Double.parseDouble(s)));
                        //jzz = String.format("%.1f", (Double.parseDouble(s) / 10));
                    }
                    String finalJzz = jzz;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tiaoliaobiaoding.setText(finalJzz);
                        }
                    });
                }
            }).start();
            initData();
        } catch (Exception ex) {
        }
    }
    //endregion
}