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

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseFragment;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.res.SilosLsjyMode;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.from.LogActivity;
import com.bonait.bnframework.modules.home.fragment.from.PlcControlActivity;
import com.bonait.bnframework.modules.home.fragment.from.RealTimeActivity;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.arch.QMUIFragment;
import com.suke.widget.SwitchButton;

import java.util.List;

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

public class Silos_item_jiaoyan_fragment extends LinearLayout {

    //region 界面布局
    @BindView(R.id.wuliaojiaozhun)
    LinearLayout wuliaojiaozhun;
    @BindView(R.id.manguanjiaozhun)
    LinearLayout manguanjiaozhun;
    @BindView(R.id.jiaoliaojiaozhun)
    LinearLayout jiaoliaojiaozhun;
    @BindView(R.id.buchangjiaozhun)
    LinearLayout buchangjiaozhun;
    //endregion

    //region 称相关
    @BindView(R.id.dianzicheng1)
    TextView dianzicheng1;
    @BindView(R.id.dianzicheng2)
    TextView dianzicheng2;
    @BindView(R.id.dianzicheng3)
    TextView dianzicheng3;

    @BindView(R.id.chuliaokeshu1)
    EditText chuliaokeshu1;
    @BindView(R.id.chuliaokeshu2)
    EditText chuliaokeshu2;
    @BindView(R.id.chuliaokeshu3)
    EditText chuliaokeshu3;
    //endregion

    //region 满管
    @BindView(R.id.runtime)
    Chronometer runtime;

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

    final int[] time = {0};

    final int[] zl = {0};
    //endregion

    //region 物料校准变量
    @BindView(R.id.wljz1)
    EditText wljz1;

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

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

    @BindView(R.id.text_wljz)
    TextView text_wljz2;
    //endregion

    //region 通道补偿
    @BindView(R.id.control_switch)
    SwitchButton control_switch;

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

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

    @BindView(R.id.bcjz_clsj)
    EditText bcjz_clsj;
    //endregion

    //region 变量
    private Context context;
    /**
     * 当前料仓
     */
    public lcMode lcMode = null;
    /**
     * 当前类型
     */
    public String TypeName = "";
    //endregion

    //region 界面实例
    private View root;
    public Silos_item_jiaoyan_fragment(Context _context, @Nullable AttributeSet attrs) {
        super(_context, attrs);
        root= LayoutInflater.from(context).inflate(R.layout.fragment_silos_item_jiaoyan, this);
        context=_context;
        ButterKnife.bind(this, root);

    }
    //endregion

    //region 初始化设置数据

    /**
     * 初始化界面
     */
    public void InitView() {
        switch (TypeName) {
            case "满管校准":
                wuliaojiaozhun.setVisibility(View.GONE);
                manguanjiaozhun.setVisibility(View.VISIBLE);
                jiaoliaojiaozhun.setVisibility(View.GONE);
                buchangjiaozhun.setVisibility(View.GONE);
                break;
            case "酱料校准":
                wuliaojiaozhun.setVisibility(View.GONE);
                manguanjiaozhun.setVisibility(View.GONE);
                jiaoliaojiaozhun.setVisibility(View.VISIBLE);
                buchangjiaozhun.setVisibility(View.GONE);
                break;
            case "补偿校准":
                wuliaojiaozhun.setVisibility(View.GONE);
                manguanjiaozhun.setVisibility(View.GONE);
                jiaoliaojiaozhun.setVisibility(View.GONE);
                buchangjiaozhun.setVisibility(View.VISIBLE);
                break;
            default:
                wuliaojiaozhun.setVisibility(View.VISIBLE);
                manguanjiaozhun.setVisibility(View.GONE);
                jiaoliaojiaozhun.setVisibility(View.GONE);
                buchangjiaozhun.setVisibility(View.GONE);
                break;
        }

        /**
         * 计时器超时
         */
        runtime.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                //如果计时到现在超过了一小时秒 20s
                if (SystemClock.elapsedRealtime() - runtime.getBase() > 20 * 1000) {
                    mHandler.sendEmptyMessage(1);
                }
            }
        });
    }


    public Activity activity=null;
    /**
     * 设置名称
     *
     * @param
     */
    public void SetData(String type, lcMode mode, Activity ac) {
        TypeName = type;
        lcMode = mode;
        activity=ac;
        InitView();
        Run();
    }
    //endregion

    //region 外部消息通知

    /**
     * 通知事件
     */
    public void Run() {
        //重量通知
        ExecuteTheRecipe.WeighComplete = new IRun() {
            @Override
            public void Run() {
                if(mHandler!=null){
                    mHandler.sendEmptyMessage(0);
                    if (ExecuteTheRecipe.OutletWeigh >= (zl[0] + 2))//当前重量大于2g
                    {
                        mHandler.sendEmptyMessage(1);
                    }
                }

            }
        };
        //通道校准完成
        ExecuteTheRecipe.OnChargeMixtureComNotPar = new IRun() {
            @Override
            public void Run() {
                final int kkk = lcMode.num;
                try {
                    if(activity!=null)
                    {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            // 在2秒后执行按钮操作
                                            int zhongliangxianshi = ExecuteTheRecipe.OutletWeigh;
                                            ExecuteTheRecipe.WritePLC("校准值" + kkk, (short) zhongliangxianshi, null);
                                            String s = String.valueOf(zhongliangxianshi);
                                            String zll = String.format("%.1f", (Double.parseDouble(s) / 10));
                                            wljz3.setText(zll + "");
                                            lcMode.jValue = zll;
                                            QueryDB.UpdateJYZ(lcMode.id, zll);
                                            ToastUtils.warning("通道校准完成！");
                                        }
                                    }, 2000);
                                } catch (Exception e) {
                                    ToastUtils.error("重量解析显示异常！" + e.getMessage());
                                }
                            }
                        });
                    }
                } catch (Exception ex) {
                    Log.d("dsds", "Run: " + ex.getMessage());
                }
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {

                if(activity!=null)
                {
                    activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        exit_mgjz.setText(lcMode.bValue + "");
                        //填充校准时间
                        String time = lcMode.jTime == null ? "0.0" : lcMode.jTime;
                        String ftime = lcMode.fTime == null ? "0.0" : lcMode.fTime;
                        String jvalue = lcMode.jValue == null ? "0.0" : lcMode.jValue;
                        wljz1.setText(time);
                        wljz1.setText(ftime);
                        wljz3.setText(jvalue);

                        String Gxs = lcMode.Gxs == null ? "0.0" : lcMode.Gxs;
                        String Lxs = lcMode.Lxs == null ? "0.0" : lcMode.Lxs;
                        String tdclsj = lcMode.tdclsj == null ? "0.0" : lcMode.tdclsj;

                        control_switch.setChecked(lcMode.isOpenbcsf == 1);
                        bcjz_gxs.setText(Gxs);
                        bcjz_gxs.setText(Lxs);
                        bcjz_gxs.setText(tdclsj);
                    }
                });
                }
            }
        }).start();

    }

    public void destroy(){
        if(mHandler!=null){
            mHandler = null;
        }
        if(activity!=null){
            activity = null;
        }
        ExecuteTheRecipe.OnChargeMixtureComNotPar = null;
        ExecuteTheRecipe.WeighComplete = null;
    }
    //endregion

    //region 刷新界面
    /**
     * 界面刷新
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    dianzicheng1.setText(String.valueOf((int) ExecuteTheRecipe.OutletWeigh / 10.0) + " g");
                    dianzicheng2.setText(String.valueOf((int) ExecuteTheRecipe.OutletWeigh / 10.0) + " g");
                    dianzicheng3.setText(String.valueOf((int) ExecuteTheRecipe.OutletWeigh / 10.0) + " g");
                    break;
                case 1:
                    time[0] = StopTime();
                    lcMode.bValue = time[0];
                    exit_mgjz.setText(time[0] + "");
                    QueryDB.UpdateMGTime(lcMode.id, time[0]);
                    break;
                case 2:

                    break;
            }
        }
    };
    //endregion

    //region 点击事件
    @OnClick({
            R.id.qingling1, R.id.qingling2, R.id.qingling3,
            R.id.chuliao1, R.id.chuliao2, R.id.chuliao3,
            R.id.click_mgjz, R.id.click_mgjz_save,
            R.id.click_wljz, R.id.click_wljz_save,
            R.id.control_switch, R.id.click_bcjz_save,
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.qingling1:
            case R.id.qingling2:
            case R.id.qingling3:
                dzcql();
                break;
            case R.id.chuliao1:
            case R.id.chuliao2:
            case R.id.chuliao3:
                mncl();
                break;
            case R.id.click_mgjz://满管校准
                zl[0] = ExecuteTheRecipe.OutletWeigh;
                StartTime();
                break;
            case R.id.click_mgjz_save://满管校准 保存参数
                String value1 = exit_mgjz.getText().toString();
                int val1 = 0;
                try {
                    val1 = (value1 == null || value1.isEmpty()) ? 0 : Integer.parseInt(value1);
                    lcMode.bValue = val1;
                    QueryDB.UpdateMGTime(lcMode.id, val1);
                    ToastUtils.info("校准时间保存成功！");
                } catch (Exception e) {

                }
                break;
            case R.id.click_wljz://物料校准
                WLJZ();
                break;
            case R.id.click_wljz_save://物料校准 保存参数
                SaveWLJZ();
                break;

            case R.id.control_switch://通道开关
                boolean isopen = control_switch.isChecked();
                if (ConfigName.getInstance().PlcIsConnect) {
                    ExecuteTheRecipe.WritePLC("通道" + lcMode.num + "补偿开关", isopen, null);
                    QueryDB.UpdateSilosisOpenbcsf(lcMode.id, isopen);
                    ToastUtils.info(lcMode.name.toString() + (isopen ? "打开" : "关闭") + "成功!");
                } else {
                    ToastUtils.warning(lcMode.name.toString() + (isopen ? "打开" : "关闭") + "失败!PLC未连接！！");
                }
                break;
            case R.id.click_bcjz_save://补偿校准 保存参数
                SaveBCJZ();
                break;
        }
    }
    //endregion

    //region 电子秤清零

    /**
     * 电子秤清零
     */
    public void dzcql() {
        ExecuteTheRecipe.WritePLC("重量清零", true, new IWriteCallBack() {
            @Override
            public void onSuccess() {
                ToastUtils.info("清零成功！");
            }

            @Override
            public void onFailure(String ErrorMsg) {
                ToastUtils.error("清零失败！");
            }
        });
    }
    //endregion

    //region 模拟出料

    /**
     * 模拟出料
     */
    public void mncl() {
        String zltext = chuliaokeshu1.getText().toString();
        if (TypeName.equals("物料校准")) {
            zltext = chuliaokeshu1.getText().toString();
        } else if (TypeName.equals("酱料校准")) {
            zltext = chuliaokeshu2.getText().toString();
        } else if (TypeName.equals("补偿校准")) {
            zltext = chuliaokeshu3.getText().toString();
        }

        if (zltext.equals("")) {
            ToastUtils.warning("出料重量不能为空！");
            return;
        }
        double zl = 0;
        try {
            zl = Double.parseDouble(zltext);
        } catch (Exception e) {
            ToastUtils.warning("出料重量获取异常！" + e.getMessage());
            return;
        }
        if (zl <= 0) {
            ToastUtils.warning("出料重量至少大于0g！");
            return;
        }

        if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机"))
        {
            if (!ExecuteTheRecipe.IsCup) {
                ToastUtils.warning("出料口没有检测到器皿！");
                return;
            }
        }

        short kkk = (short) ((int) (zl * 10));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ExecuteTheRecipe.WritePLC("配料完成", false, null);
                    ExecuteTheRecipe.WritePLC("手自切换", true, null);
                    ExecuteTheRecipe.WritePLC("需求值" + lcMode.num, kkk, new IWriteCallBack() {
                        @Override
                        public void onSuccess() {
                            ExecuteTheRecipe.WritePLC("配料启动", true, null);
                        }

                        @Override
                        public void onFailure(String ErrorMsg) {
                        }
                    });
                } catch (Exception e) {
                }
            }
        }).start();
        ToastUtils.info("需求值下发成功！开始配料......");
    }
    //endregion

    //region 保存物料校准参数
    public void SaveWLJZ() {
        String stime = wljz1.getText().toString();
        String ftime = wljz2.getText().toString();
        String zl = wljz3.getText().toString();

        if (stime.equals("")) {
            ToastUtils.warning("校准基准时间不能为空！");
            return;
        }

        if (zl.equals("")) {
            ToastUtils.warning("校准重量不能为空！");
            return;
        }

        int stime_1 = 0;
        int ftime_1 = 0;

        try {
            stime_1 = (int) Math.round((Double.parseDouble(stime) * 10));
        } catch (Exception e) {
            ToastUtils.error("时间异常！" + e.getMessage());
            return;
        }

        try {
            Double.parseDouble(zl);
        } catch (Exception e) {
            ToastUtils.error("重量异常！" + e.getMessage());
            return;
        }
        if (!ConfigName.getInstance().versionSelectionEnum.equals("奶茶机")) {
            if (ftime.equals("")) {
                ToastUtils.warning("反转基准时间不能为空！");
                return;
            }
            try {
                ftime_1 = (int) Math.round((Double.parseDouble(ftime) * 10));
            } catch (Exception e) {
                ToastUtils.error("时间异常！" + e.getMessage());
                return;
            }
            ExecuteTheRecipe.WritePLC("反转时间", (short) ftime_1, new IWriteCallBack() {
                @Override
                public void onSuccess() {
                    ToastUtils.info("反转时间保存成功！");
                }

                @Override
                public void onFailure(String ErrorMsg) {
                    ToastUtils.error("反转时间保存失败！");
                }
            });
        }
        QueryDB.UpdateSilosJZTime(lcMode.id, stime, ftime);
        QueryDB.UpdateJYZ(lcMode.id, zl);
        ExecuteTheRecipe.WritePLC("基准时间", (short) stime_1, new IWriteCallBack() {
            @Override
            public void onSuccess() {
                ToastUtils.info("校准基准时间保存成功！");
            }

            @Override
            public void onFailure(String ErrorMsg) {
                ToastUtils.error("校准基准时间保存失败！");
            }
        });
    }
    //endregion

    //region 物料校准
    public void WLJZ() {
        //判断是否为果糖->判断温度
        if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机")) {
            if (lcMode.num == 11) {
                if (ExecuteTheRecipe.SugarTempLeft < ExecuteTheRecipe.SugarTempLeft_SZ) {
                    ToastUtils.warning("果糖左仓温度未达到设置值,不允许校准...");
                    return;
                }
            } else if (lcMode.num == 12) {
                if (ExecuteTheRecipe.SugarTempRight < ExecuteTheRecipe.SugarTempRight_SZ) {
                    ToastUtils.warning("果糖右仓温度未达到设置值,不允许校准...");
                    return;
                }
            }
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ExecuteTheRecipe.WritePLC("校准完成", false, null);
                    ExecuteTheRecipe.WritePLC("手自切换", false, null);
                    ExecuteTheRecipe.WritePLC("通道校准", true, new IWriteCallBack() {
                        @Override
                        public void onSuccess() {
                            ToastUtils.info("启动通道校准成功！");
                        }

                        @Override
                        public void onFailure(String ErrorMsg) {
                            ToastUtils.error("启动通道校准失败！");
                        }
                    });
                } catch (Exception e) {
                }
            }
        }).start();
    }
    //endregion

    //region 补偿校准
    public void SaveBCJZ() {
        Short H = 0;
        Short L = 0;
        Short time = 0;
        try {
            H = Short.parseShort(bcjz_gxs.getText().toString());
            L = Short.parseShort(bcjz_dxs.getText().toString());
            int ftime = (int) Math.round((Double.parseDouble(bcjz_clsj.getText().toString()) * 10));
            time = (short) ftime;
        } catch (Exception ex) {
            ToastUtils.error("数据不合法,保存变量失败!" + ex.getMessage());
            return;
        }
        Short finalH = H;
        Short finalL = L;
        Short finalTime = time;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ExecuteTheRecipe.WritePLC("高系数" + lcMode.num, finalH, null);
                    ExecuteTheRecipe.WritePLC("低系数" + lcMode.num, finalL, null);
                    ExecuteTheRecipe.WritePLC("补偿" + lcMode.num + "时间", finalTime, new IWriteCallBack() {
                        @Override
                        public void onSuccess() {
                            ToastUtils.info("保存变量成功!");
                            QueryDB.UpdateSilosisOpenbcsf(lcMode.id, bcjz_gxs.getText().toString(),
                                    bcjz_dxs.getText().toString(), bcjz_clsj.getText().toString());
                        }

                        @Override
                        public void onFailure(String ErrorMsg) {
                            ToastUtils.warning("保存变量失败!");
                        }
                    });
                } catch (Exception e) {

                }
            }
        }).start();

    }
    //endregion

    //region 定时器

    /**
     * 启动定时器
     */
    public void StartTime() {
        runtime.setBase(SystemClock.elapsedRealtime());
        runtime.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //自动模式
                    ExecuteTheRecipe.WritePLC("手自切换", false, null);
                    //开启
                    ExecuteTheRecipe.WritePLC("手动控制" + lcMode.num, true, null);
                } catch (Exception e) {

                }
            }
        }).start();
    }

    /**
     * 停止定时器
     */
    public int StopTime() {
        long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
        runtime.stop();
        int time = (int) (elapsedMillis / 1000);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ExecuteTheRecipe.WritePLC("手动控制" + lcMode.num, false, null);
                } catch (Exception e) {

                }
            }
        }).start();
        return time;//当前点击多少秒
    }
    //endregion

    //region 关闭窗体事件
    //endregion
}
