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

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

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;

import com.bonait.bnframework.HBL.Dialog.AlertDialogButton;
import com.bonait.bnframework.HBL.Dialog.DialogManager;
import com.bonait.bnframework.HBL.Dialog.WaitDialog;
import com.bonait.bnframework.HBL.Executor;
import com.bonait.bnframework.HBL.Trig.TTrig;
import com.bonait.bnframework.HBL.Unity;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.business.PLCName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_SILOS_CALIBRATE;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.utils.ToastUtils;

import java.util.Timer;
import java.util.TimerTask;

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

public class silos_jiaoyan extends LinearLayout {
    //region qita
    @BindView(R.id.close_from)
    Button close_from;
    @BindView(R.id.title_bc)
    TextView title_bc;
    /**
     * 当前料仓
     */
    public lcMode lcMode = null;
    /**
     * 窗体
     */
    public FragmentManager fragmentManager;
    /**
     * 点击事件
     */
    public MyClickListener mListener=null;
    private View root;

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

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

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

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

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

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

//    @BindView(R.id.controlStatus)
//    TextView controlStatus;
    //endregion


    public silos_jiaoyan(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        root= LayoutInflater.from(context).inflate(R.layout.silos_jiaoyan_item_edit, this);
        ButterKnife.bind(this, root);
        //初始化界面控件的事件
        initEvent();
    }



    /**
     * 初始化数据
     */
    private void initData()
    {
        title_bc.setText(lcMode.num+" "+lcMode.materialName);
    }

    private void initEvent()
    {
        //关闭窗体
        close_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.clickListenerNew(v,0,null);
                }
            }
        });
    }

    Activity activity =null;
    /**
     * 设置数据
     * @param
     */
    public void SetData(lcMode _lcMode,Activity ac)
    {
        activity=ac;
        this.lcMode=_lcMode;
        initData();
        InitView("物料校准");
        Run();

//        new Thread(()->{
//            try{
//               while(true){
//                   String name = lcMode.name+lcMode.num+"启停控制";
//                   boolean res =  ExecuteTheRecipe.ReadBool(name);
//                   activity.runOnUiThread(()->{controlStatus.setText("控制状态："+String.valueOf(res));});
//                   Thread.sleep(10);
//               }
//
//            }catch (Exception e){}
//        }).start();

        BPA_SILOS_CALIBRATE res = QueryDB.GetSilosCalibrateByNum(lcMode.num);
        if(res!=null){
            min_time.setText(String.valueOf(res.outputTimeMin));
            max_time.setText(String.valueOf(res.outputTimeMax));
            min_weight.setText(res.inputWightMin+"");
            max_weight.setText(res.inputWightMax+"");
        }else{
            min_time.setText("2");
            max_time.setText("5");
            min_weight.setText("0");
            max_weight.setText("0");
        }

    }


    //region 初始化设置数据
    public String TypeName="物料校准";
    /**
     * 初始化界面
     */
    public void InitView(String _TypeName) {
        TypeName=_TypeName;
    }
    //endregion

    //region 外部消息通知

    /**
     * 通知事件
     */
    public void Run() {
        //重量通知
        ExecuteTheRecipe.WeighComplete = new IRun() {
            @Override
            public void Run() {
                if(mHandler!=null){
                    mHandler.sendEmptyMessage(0);
                }
            }
        };
        //通道校准完成
        ExecuteTheRecipe.OnChargeMixtureComNotPar = new IRun() {
            @Override
            public void Run() {
                if(mHandler!=null){
                    final int kkk = lcMode.num;
                    try {

                        mHandler.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());
                    }
                }
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=1;i<=20;i++)
                {
                    ExecuteTheRecipe.WritePLC("通道"+i+"校准开关",false,null);
                }
                ExecuteTheRecipe.WritePLC("通道" + lcMode.num + "校准开关", true, null);
                if(activity!=null)
                {
                }
            }
        }).start();
    }
    //endregion

    //region 刷新界面
    /**
     * 界面刷新
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if(msg.what == 1){
            }
        }
    };
    //endregion

    private Timer timer;
    private TimerTask timerTask;

    public void show(){
        close();
        setVisibility(VISIBLE);
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                activity.runOnUiThread(()->{
                    float resultWeight = (float) (ExecuteTheRecipe.ReadShort(PLCName.称当前重量)/10.0);
                    current_weight.setText(resultWeight+"g");
                });
            }
        };
        timer.schedule(timerTask,500,500);
    }

    public void close(){
        setVisibility(GONE);
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        ExecuteTheRecipe.WeighComplete = null;
        ExecuteTheRecipe.OnChargeMixtureComNotPar = null;
        if(timer!=null){
            timer.cancel();
            timer = null;
        }
        if(timerTask!=null){
            timerTask.cancel();
            timerTask = null;
        }
    }


    private float EditTextValidate(EditText et,String info){
        if(et==null) return -1;
        if(et.getText().toString().isEmpty()){
            DialogManager.showError(activity,info,AlertDialogButton.OK,null);
            return -1;
        }
        try{
            return Float.parseFloat(et.getText().toString());
        }catch  (Exception e){
            return -1;
        }
    }

    /**
     * 按钮单击事件
     * @param view
     */
    @OnClick({R.id.btn_min_standard, R.id.btn_max_standard,R.id.btn_sim_discharge,R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_max_standard:
            case R.id.btn_min_standard:
                float time = EditTextValidate(view.getId()==R.id.btn_min_standard? min_time:max_time,"请输入正确的时间");
                if(time<0) return;
                DialogManager.showWarn(activity,"校准前请确认是否准备就绪？\r\n是否开始校准?", AlertDialogButton.YesNo,s->{
                    if(s){
                        WaitDialog.getInstance().Show(view.getId()==R.id.min_time?"最小校准":"最大校准","开始校准",getContext(),activity);
                        Executor.get().runThread(()->{

                            WaitDialog.getInstance().AddText("电子秤清零");
                            try {
                                ExecuteTheRecipe.Write(PLCName.重量清零, true, null);//电子秤重量清零
                                Thread.sleep(100);
                                ExecuteTheRecipe.Write(PLCName.重量清零, true, null);//电子秤重量清零
                                Thread.sleep(100);
                                ExecuteTheRecipe.Write(PLCName.重量清零, true, null);//电子秤重量清零
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            WaitDialog.getInstance().AddText("等待清零完成");
                            //等待清零完成
                            Unity.Wait(()->{
                                return ExecuteTheRecipe.ReadShort(PLCName.称当前重量)>-20&&ExecuteTheRecipe.ReadShort(PLCName.称当前重量)<=20;},3000).OnSource(()->{

                                WaitDialog.getInstance().AddText("下发参数，开始校准");
                                ExecuteTheRecipe.Write(lcMode.name+lcMode.num+"出料时间",((int) time)*100,null);//下发出料时间
                                long startTime = System.currentTimeMillis();
                                MessageLog.ShowInfo("下发参数，开始校准 当前时间："+startTime +" 出料时间"+((int) time)*100);
                                ExecuteTheRecipe.Write(lcMode.name+lcMode.num+"启停控制",true,null);//下发启动信号


                                WaitDialog.getInstance().AddText("等待校准完成");
                                String name = lcMode.name+lcMode.num+"启停控制";
                                //等待出料完成
                                Unity.Wait(()->{return TTrig.get(name).Start(ExecuteTheRecipe.ReadBool(name));},(int)(time*1000+2000)).OnSource(()->{
                                    //获取电子秤重量,并填充到对应位置
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                    MessageLog.ShowInfo("下发参数，结束校准 结束时间："+(System.currentTimeMillis()-startTime) +" 读取启停控制 false");

                                    activity.runOnUiThread(()->{
                                        float weight = (float) (ExecuteTheRecipe.ReadShort(PLCName.称当前重量)/10.0);
                                        MessageLog.ShowInfo("下发参数，结束校准 校准重量："+weight);
                                        if(view.getId()==R.id.btn_min_standard) min_weight.setText(weight+"");
                                        else max_weight.setText(weight+"");
                                    });
                                    WaitDialog.getInstance().Dismiss();
                                    DialogManager.showInfo(activity,"校准完成",AlertDialogButton.OK,null);
                                }).OnFailed(msg->{WaitDialog.getInstance().TimeOut("等待校准完成超时，请退出后重试！");});
                                TTrig.Remove(name);
                            }).OnFailed((msg)->{WaitDialog.getInstance().TimeOut("等待清零超时，请退出后重试！");});
                        });
                    }
                });
                break;
            case R.id.btn_sim_discharge:
                try{
                    float minWeight = Float.parseFloat(min_weight.getText().toString());
                    float weight = Float.parseFloat(sim_discharge_weight.getText().toString());
                    float maxweight = Float.parseFloat(max_weight.getText().toString());
//                    if(weight<minWeight){
//                        DialogManager.showError(activity,"模拟出料重量小于最小出料重量，请重新输入模拟出料重量",AlertDialogButton.OK,null);
//                        return;
//                    }
//
//                    if(weight>maxweight){
//                        DialogManager.showError(activity,"模拟出料重量大于最大出料重量，请重新输入模拟出料重量",AlertDialogButton.OK,null);
//                        return;
//                    }

                }catch(Exception e){}
                WaitDialog.getInstance().Show("模拟","模拟出料",getContext(),activity);
                DialogManager.showWarn(activity,"模拟出料前请将容器放入指定位置！\r\n请问是否继续",AlertDialogButton.YesNo,(s->{
                    if(s){
                        try{
                            float weight = Float.parseFloat(sim_discharge_weight.getText().toString());
                            BPA_SILOS_CALIBRATE res = QueryDB.GetSilosCalibrateByNum(lcMode.num);
                            if(res!=null){
                                WaitDialog.getInstance().AddText("电子秤清零");
                                try {
                                    ExecuteTheRecipe.Write(PLCName.重量清零, true, null);//电子秤重量清零
                                    Thread.sleep(100);
                                    ExecuteTheRecipe.Write(PLCName.重量清零, true, null);//电子秤重量清零
                                    Thread.sleep(100);
                                    ExecuteTheRecipe.Write(PLCName.重量清零, true, null);//电子秤重量清零
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                                WaitDialog.getInstance().AddText("等待清零完成");
                                //等待清零完成
                                Unity.Wait(()->{
                                    return ExecuteTheRecipe.ReadShort(PLCName.称当前重量)>-20&&ExecuteTheRecipe.ReadShort(PLCName.称当前重量)<=20;},2000).OnSource(()->{
                                    float outValue = Unity.Scale(weight,res.inputWightMax,res.inputWightMin,res.outputTimeMax,res.outputTimeMin);
                                    WaitDialog.getInstance().Show("模拟出料","启动模拟出料",getContext(),activity);
                                    Executor.get().runThread(()->{
                                        ExecuteTheRecipe.Write(lcMode.name+lcMode.num+"出料时间",(short)(outValue*100),null);//下发出料时间
                                        ExecuteTheRecipe.Write(lcMode.name+lcMode.num+"启停控制",true,null);//下发启动信号
                                        WaitDialog.getInstance().AddText("等待出料完成");
                                        String name = lcMode.name+lcMode.num+"启停控制";
                                        try {
                                            Thread.sleep((int)(outValue*1000)+500);
                                        } catch (InterruptedException e) {
                                            throw new RuntimeException(e);
                                        }
                                        WaitDialog.getInstance().Dismiss();
                                        TTrig.Remove(name);
                                    });
                                }).OnFailed((msg)->{WaitDialog.getInstance().TimeOut("等待清零超时，请退出后重试！");});
                            }else{
                                DialogManager.showWarn(activity,"料仓参数未校准，请校准后再试！",AlertDialogButton.OK,null);
                            }
                        }catch(Exception e){
                            DialogManager.showError(activity,"模拟出料失败，"+e.getMessage(),AlertDialogButton.OK,null);
                        }
                    }else {
                        WaitDialog.getInstance().Dismiss();
                    }
                }));
                break;
            case R.id.btn_save:
                DialogManager.showWarn(activity,"请问是否覆盖本地参数？",AlertDialogButton.YesNo,s->{
                    if(s){
                        boolean runResult = false;
                        try{
                            float outputMax = Float.parseFloat(max_time.getText().toString());
                            float outputMin=Float.parseFloat(min_time.getText().toString());
                            float inputMax=Float.parseFloat(max_weight.getText().toString());
                            float inputMin=Float.parseFloat(min_weight.getText().toString());
                            if(lcMode!=null){
                                BPA_SILOS_CALIBRATE res = QueryDB.GetSilosCalibrateByNum(lcMode.num);
                                if(res!=null) runResult =QueryDB.UpdateSilosCalibrate(res.id,outputMax,outputMin,inputMax,inputMin);
                                else runResult =QueryDB.AddSilosCalibrate(new BPA_SILOS_CALIBRATE(lcMode.name,lcMode.num,outputMax,outputMin,inputMax,inputMin));
                            }
                        }catch  (Exception e){
                        }
                        if(runResult) DialogManager.showInfo(activity,"参数保存成功",AlertDialogButton.OK,null);
                        else DialogManager.showError(activity,"参数保存失败",AlertDialogButton.OK,null);
                    }
                });
                break;
        }
    }


}
