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


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.RectF;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.aliyun.alink.linksdk.tmp.devicemodel.Event;
import com.aliyun.alink.linksdk.tmp.devicemodel.Property;
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.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.res.StatusMode;
import com.bonait.bnframework.common.helper.ByteHelper;
import com.bonait.bnframework.common.helper.CountDownTimerExt;
import com.bonait.bnframework.common.helper.I.IRunT;
import com.bonait.bnframework.common.helper.I.IThread;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.helper.Json;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.ThreadManager;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyLayoutManager;
import com.bonait.bnframework.modules.home.adapter.lc_adapter;
import com.bonait.bnframework.modules.home.fragment.from.CpxzActivity;
import com.bonait.bnframework.modules.home.fragment.mode.LocationStatus;
import com.bonait.bnframework.modules.home.fragment.mode.MyStatus;
import com.bonait.bnframework.modules.home.fragment.mode.huoli_control;
import com.bonait.bnframework.modules.home.fragment.mode.imagebutton_control;
import com.capton.colorfulprogressbar.ColorfulProgressbar;
import com.litao.slider.NiftySlider;
import com.litao.slider.SliderEffect;
import com.litao.slider.Utils;
import com.lzy.okgo.OkGo;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.textview.QMUILinkTextView;
import com.suke.widget.SwitchButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

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

/**
 * A simple {@link Fragment} subclass.
 */
public class Home1Fragment extends BaseFragment {
    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;//顶部标题
    @BindView(R.id.xzcp)
    RelativeLayout xzcp;//选择菜谱
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;//料仓列表
    @BindView(R.id.caipumingcheng)
    QMUILinkTextView caipumingcheng;//菜谱名称
    @BindView(R.id.shengyushijian)
    QMUILinkTextView shengyushijian;//剩余时间
    @BindView(R.id.jingdu)
    ColorfulProgressbar jingdu;//进度条
    @BindView(R.id.huoli)
    huoli_control huoli;//火力控件
    @BindView(R.id.startbutton)
    ImageView startbutton;//启动安
    @BindView(R.id.choushui_control)
    Button choushui_control;//抽水
    @BindView(R.id.fangshui_control)
    Button fangshui_control;//防水
    @BindView(R.id.chaoguo_wendu)
    QMUILinkTextView chaoguo_wendu;//
    @BindView(R.id.chaoguo_weizhi)
    QMUILinkTextView chaoguo_weizhi;//
    @BindView(R.id.plc_zhuangtai)
    ImageView plc_zhuangtai;//

    @BindView(R.id.nifty_slider2)
    NiftySlider nifty_slider2;//

    @BindView(R.id.nifty_slider3)
    NiftySlider nifty_slider3;//


    @BindView(R.id.btn_jiaoban)
    SwitchButton btn_jiaoban;//
    @BindView(R.id.btn_zhuandong_control_left)
    Button btn_zhuandong_control_left;//
    @BindView(R.id.btn_zhuandong_control_Rift)
    Button btn_zhuandong_control_Rift;//


    @BindView(R.id.wk_zhuangtai)
    QMUILinkTextView wk_zhuangtai;//


    @BindView(R.id.gongxumiaoshu)
    TextView gongxumiaoshu;//工序描述

    @BindView(R.id.gongxutime)
    TextView gongxutime;//预计等待


    /**
     * 当前制作商品信息
     */
    BPA_GOODS good = null;
    private Context context;

    public Home1Fragment() {
    }

    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home1, null);
        ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = getContext();

        initTopBar();
        initData();
        HuoLiClicked();
        MakeThread();
        ControlClicked();

        nifty_slider2.setOnValueChangeListener(new NiftySlider.OnValueChangeListener() {
            @Override
            public void onValueChange(@NonNull NiftySlider niftySlider, float v, boolean b) {
                nifty_slider2.setThumbText((int) v + "");
            }
        });

        nifty_slider3.setOnValueChangeListener(new NiftySlider.OnValueChangeListener() {
            @Override
            public void onValueChange(@NonNull NiftySlider niftySlider, float v, boolean b) {
                nifty_slider3.setThumbText((int) v + "");
            }
        });
    }

    /**
     * 初始化TopBar
     */
    private void initTopBar() {
        jingdu.showPercentText(true);
        jingdu.setAnimation(true);
        jingdu.setProgress(0);
        jingdu.setSecondProgress(0);
        caipumingcheng.setText("");
        shengyushijian.setText("预计剩余时间：0s");
        startbutton.setImageResource(R.mipmap.qdzz);
        ExecuteTheRecipe.MakeStatus = false;

        mTopBar.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.app_color_theme_4));
        mTopBar.setTitle("菜谱烹饪");

    }

    /**
     * 初始化显示数据
     */
    private void initData() {
        try {
            DataBus.getInstance().GetLc();
            MyLayoutManager layout = new MyLayoutManager();
            layout.setAutoMeasureEnabled(true);
            recyclerView.setLayoutManager(layout);

            DataBus.getInstance().lcadapter = new lc_adapter(getContext());
            recyclerView.setAdapter(DataBus.getInstance().lcadapter);

            nifty_slider2.setValue(0, true);
            nifty_slider3.setValue(0, true);

        } catch (Exception e) {
            ToastUtils.info("异常信息:" + e.getMessage());
        }
    }

    /**
     * 火力按钮点击
     */
    public void HuoLiClicked() {
        huoli.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
                ExecuteTheRecipe.Write_PLC_HuoLI((int) data);
            }

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

            }
        };

        DataBus.getInstance().mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!IsMake(true)) {
                            return;
                        }
                        gongxumiaoshu.setText("等待开始");
                        good = (BPA_GOODS) data;
                        SetBottonStatus(false);
                        caipumingcheng.setText(good.name);
                        SetProcesssUI(good.maketime, 0);
                    }
                });

            }

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

    /**
     * Image Button 按钮点击事件
     */
    public void ControlClicked() {
        //region 临时屏蔽
        //        //搅拌挡位
//        jiaoban_control.mListener = new MyClickListener() {
//            @Override
//            public void clickListener(View v, Object data) {
//                boolean status = !(boolean) data;
//                if (!IsMake(false))
//                {
//                    return;
//                }
//                jiaoban_control.SetStatus(status);
//                int jd = (int) nifty_slider2.getValue();
//                ToastUtils.info("点击按钮：搅拌" + status + ".搅拌频率:" + jd);
//                ExecuteTheRecipe.WritePLC("搅拌速度", jd, new IWriteCallBack() {
//                    @Override
//                    public void onSuccess() {
//                        if (jd == 0) {
//                            ExecuteTheRecipe.WritePLC("搅拌", false, null);
//                        } else {
//                            ExecuteTheRecipe.WritePLC("搅拌", status, null);
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(String ErrorMsg) {
//                    }
//                });
//
//            }
//
//            @Override
//            public void clickListenerNew(View v, int k, Object data) {
//
//            }
//        };
//        //转动 左
//        zhuandong_control_left.mListener = new MyClickListener() {
//            @Override
//            public void clickListener(View v, Object data) {
//                boolean status = !(boolean) data;
//                if (!IsMake(true))
//                {
//                    return;
//                }
//                zhuandong_control_left.SetStatus(status);
//                int jd = (int) nifty_slider3.getValue();
//                ToastUtils.info("点击按钮：转动" + status + ".转动频率:" + jd);
//                ExecuteTheRecipe.WritePLC("转动速度", jd, new IWriteCallBack() {
//                    @Override
//                    public void onSuccess() {
//                        if (jd == 0) {
//                            ExecuteTheRecipe.WritePLC("翻转正转", false, null);
//                        } else {
//                            ExecuteTheRecipe.WritePLC("翻转正转", status, null);
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(String ErrorMsg) {
//                    }
//                });
//            }
//
//            @Override
//            public void clickListenerNew(View v, int k, Object data) {
//
//            }
//        };
//        //转动 右
//        zhuandong_control_Rift.mListener = new MyClickListener() {
//            @Override
//            public void clickListener(View v, Object data) {
//                boolean status = !(boolean) data;
//                if (!IsMake(true))
//                {
//                    return;
//                }
//                zhuandong_control_Rift.SetStatus(status);
//                int jd = (int) nifty_slider3.getValue();
//                ToastUtils.info("点击按钮：搅拌" + status + ".转动频率:" + jd);
//                ExecuteTheRecipe.WritePLC("转动速度", jd, new IWriteCallBack() {
//                    @Override
//                    public void onSuccess() {
//                        if (jd == 0) {
//                            ExecuteTheRecipe.WritePLC("翻转反转", false, null);
//                        } else {
//                            ExecuteTheRecipe.WritePLC("翻转反转", status, null);
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(String ErrorMsg) {
//                    }
//                });
//            }
//
//            @Override
//            public void clickListenerNew(View v, int k, Object data) {
//
//            }
//        };
        //endregion

        //抽水启动
//        choushui_control.mListener = new MyClickListener() {
//            @Override
//            public void clickListener(View v, Object data) {
//                boolean status = !(boolean) data;
////                if (!IsMake(true))
////                {
////                    return;
////                }
//                choushui_control.SetStatus(status);
//                ToastUtils.info("点击按钮：炒锅抽水" + status);
//                ExecuteTheRecipe.WritePLC("炒锅抽水", status, null);
//            }
//
//            @Override
//            public void clickListenerNew(View v, int k, Object data) {
//
//            }
//        };
//        //放水启动
//        fangshui_control.mListener = new MyClickListener() {
//            @Override
//            public void clickListener(View v, Object data) {
//                boolean status = !(boolean) data;
////                if (!IsMake(true))
////                {
////                    return;
////                }
//                fangshui_control.SetStatus(status);
//                ToastUtils.info("点击按钮：炒锅放水" + status);
//                ExecuteTheRecipe.WritePLC("炒锅放水", status, null);
//            }
//
//            @Override
//            public void clickListenerNew(View v, int k, Object data) {
//
//            }
//        };

        choushui_control.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Object ob = ExecuteTheRecipe.getListingValue("抽料位反馈");
                if (ob != null && (boolean) ob) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        ExecuteTheRecipe.WritePLC("炒锅抽水", true, null);
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        ExecuteTheRecipe.WritePLC("炒锅抽水", false, null);
                    }
                } else {
                    ToastUtils.warning("请先控制锅口朝向：抽料位");
                    ExecuteTheRecipe.WritePLC("炒锅抽水", false, null);
                }
                return false;
            }
        });
        fangshui_control.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Object ob = ExecuteTheRecipe.getListingValue("清洗位反馈");
                if (ob != null && (boolean) ob) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        ExecuteTheRecipe.WritePLC("炒锅放水", true, null);
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        ExecuteTheRecipe.WritePLC("炒锅放水", false, null);
                    }
                } else {
                    ToastUtils.warning("请先控制锅口朝向：清洗位");
                    ExecuteTheRecipe.WritePLC("炒锅放水", false, null);
                }
                return false;
            }
        });


        btn_jiaoban.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean ischick = btn_jiaoban.isChecked();

//                if (!IsMake(false))
//                {
//                    return;
//                }
                int jd = (int) nifty_slider2.getValue();
                ExecuteTheRecipe.WritePLC("搅拌速度", jd, new IWriteCallBack() {
                    @Override
                    public void onSuccess() {
                        if (jd == 0) {
                            ExecuteTheRecipe.WritePLC("搅拌", false, null);
                        } else {
                            ExecuteTheRecipe.WritePLC("搅拌", ischick, null);
                        }
                    }

                    @Override
                    public void onFailure(String ErrorMsg) {
                    }
                });
            }
        });

        //正转
        btn_zhuandong_control_left.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.e("鼠标", "按下: ");
                    if (!IsMake(false)) {
                        return false;
                    }
                    int jd = (int) nifty_slider3.getValue();
                    ExecuteTheRecipe.WritePLC("转动速度", jd, new IWriteCallBack() {
                        @Override
                        public void onSuccess() {
                            if (jd == 0) {
                                ExecuteTheRecipe.WritePLC("翻转正转", false, null);
                            } else {
                                ExecuteTheRecipe.WritePLC("翻转正转", true, null);
                            }
                        }

                        @Override
                        public void onFailure(String ErrorMsg) {
                        }
                    });
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    Log.e("鼠标", "松开: ");
                    ExecuteTheRecipe.WritePLC("翻转正转", false, null);
                }
                return false;
            }
        });

        //反转
        btn_zhuandong_control_Rift.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.e("鼠标", "按下: ");
                    if (!IsMake(false)) {
                        return false;
                    }
                    int jd = (int) nifty_slider3.getValue();
                    ExecuteTheRecipe.WritePLC("转动速度", jd, new IWriteCallBack() {
                        @Override
                        public void onSuccess() {
                            if (jd == 0) {
                                ExecuteTheRecipe.WritePLC("翻转反转", false, null);
                            } else {
                                ExecuteTheRecipe.WritePLC("翻转反转", true, null);
                            }
                        }

                        @Override
                        public void onFailure(String ErrorMsg) {
                        }
                    });
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    Log.e("鼠标", "松开: ");
                    ExecuteTheRecipe.WritePLC("翻转反转", false, null);
                }
                return false;
            }
        });


        MessageManager.getInstance().registerMessageReceiver(getActivity(), MessageName.IsStratMakeGood1, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ExecuteTheRecipe.StopForcedEnd();
                            SetBottonStatus(true);
                        }
                    });

                }
            }
        });
    }

    int gongxuIndex = 10000;
    ArrayList<BPA_GOODSRECIPE> goodsrecipesL = null;

    BPA_GOODSRECIPE MakeCipe = null;

    public Thread makeThread = null;
    public Thread makeThreadDC = null;
    public Thread makeThreadUI = null;

    /**
     * 商品制作线程
     */
    public void MakeThread() {
        ExecuteTheRecipe.context = context;

        makeThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (ConfigName.getInstance().IsShow) {
                    try {

                        if (ExecuteTheRecipe.MakeStatus && good != null) {
                            long startTime = System.currentTimeMillis(); //起始时间
                            ExecuteTheRecipe.showlog("--------------------------------------");
                            ExecuteTheRecipe.showlog("开始烹饪菜谱【" + good.name + "】");
                            ModbusTcpServer.get().WriteBool("M52.0", (boolean) true, null);
                            ExecuteTheRecipe.HandTime = 0;//默认将手动操作时间复位

                            try {
                                //获取工艺
                                ArrayList<BPA_GOODSRECIPE> goodsrecipes = QueryDB.GetGoodsSrecipeID(good.id);
                                goodsrecipesL = goodsrecipes;
                                gongxuIndex = 1;
                                int m = 0;
                                for (BPA_GOODSRECIPE item : goodsrecipes) {
                                    MakeCipe = item;
                                    gongxuIndex++;
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            gongxumiaoshu.setText("正在执行：" + item.processms);
                                        }
                                    });
                                    boolean status = ExecuteTheRecipe.Execute(item, goodsrecipes, m);
                                    m++;
                                }


                            } catch (Exception ex) {
                                ToastUtils.error("异常信息:" + ex.getMessage());
                            } finally {
                                ExecuteTheRecipe.WritePLC("搅拌", false, null);
                                ExecuteTheRecipe.WritePLC("加热", false, null);
                                ExecuteTheRecipe.WritePLC("暂停开关", false, null);
                                ConfigName.getInstance().IsOpenHuoLi = false;
                                ExecuteTheRecipe.BottomClick("平移-去1号位");
                                gongxuIndex = 10000;
                                MakeCipe = null;
                                goodsrecipesL = null;

                                long endTime = System.currentTimeMillis(); //结束时间
                                int time = (int) ((endTime - startTime) / 1000);
                                Log.e("运行时长", String.format("方法使用时间 %d s", time));
                                ExecuteTheRecipe.showlog("结束烹饪菜谱【" + good.name + "】,关闭搅拌、关闭加热," + String.format("方法使用时间 %d s", time));

                                if (!ExecuteTheRecipe.IsForcedEnd) {
                                    int ztime = time - ExecuteTheRecipe.HandTime;
                                    good.maketime = ztime > 0 ? ztime : time;
                                    QueryDB.UpdateGoodsMakeTime(good.id, good.maketime);
                                }
                                ExecuteTheRecipe.HandTime = 0;//默认将手动操作时间复位

                                ExecuteTheRecipe.all_list = new ArrayList<>();

                                Activity activity = getActivity();
                                if (activity != null) {
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            SetBottonStatus(false);
                                            if (ExecuteTheRecipe.IsForcedEnd)//强制结束
                                            {
                                                ToastUtils.info("客官,当前菜品已强制结束!!!");
                                                //初始化
                                                // ExecuteTheRecipe.BottomClick("初始化");
                                                ExecuteTheRecipe.showlog("菜谱【" + good.name + "】已强制结束...");
                                                if (ConfigName.getInstance().versionSelectionEnum.contains("一拖"))//通知任务结束
                                                {
                                                    ExecuteTheRecipe.WriteMainPLC("强制结束任务完成", true, null);//复位
                                                }
                                                ExecuteTheRecipe.StopForcedEnd();//设置恢复强制结束
                                            }
                                        }
                                    });
                                }
                                ExecuteTheRecipe.showlog("--------------------------------------");
                                ModbusTcpServer.get().WriteBool("M52.0", (boolean) false, null);
                            }
                        }
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        ToastUtils.info("异常信息:" + e.getMessage());
                    }
                }
            }
        });
        makeThread.start();

        makeThreadDC = new Thread(new Runnable() {
            @Override
            public void run() {
                while (ConfigName.getInstance().IsShow) {
                    try {

                        if (ExecuteTheRecipe.MakeStatus && good != null && gongxuIndex != 10000 && goodsrecipesL != null && MakeCipe != null) {
                            try {
                                if (ConfigName.getInstance().versionSelectionEnum.equals("大炒自动投料版本") || ConfigName.getInstance().versionSelectionEnum.equals("小炒版本")) {
                                    //获取工艺
                                    int k = 1;
                                    ArrayList<BPA_GOODSRECIPE> goodsrecipes = goodsrecipesL;
                                    BPA_GOODSRECIPE recipe = null;
                                    for (BPA_GOODSRECIPE item : goodsrecipes) {
                                        k++;
                                        if (k > gongxuIndex) {
                                            if (item.processname.contains("主料") && !MakeCipe.processname.equals("主料") && recipe == null) {
                                                recipe = item;
                                            }
                                        }
                                    }

                                    if (recipe != null) {
                                        HashMap<String, String> formulation = new HashMap<>();
                                        String text = recipe.processvalue;
                                        //region 获取仓号和值
                                        List<String> data = new ArrayList<>();
                                        if (text.contains("|")) {
                                            String[] res = text.split("[|]");
                                            for (int i = 0; i < res.length; i++) {
                                                data.add(res[i]);
                                            }
                                        } else {
                                            data.add(text);
                                        }
                                        for (String item : data) {
                                            if (!item.isEmpty() && item.contains(",")) {
                                                String[] wl = item.split("[,]");
                                                if (wl != null && wl.length == 2) {
                                                    String name = wl[0];
                                                    String val = wl[1];
                                                    formulation.put(name, val);
                                                }
                                            }
                                        }
                                        //endregion
                                        boolean ishand = true;

                                        //region 判断是否手动
                                        if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本")) {
                                            ishand = true;
                                        } else {
                                            for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
                                                String key = entry.getKey();
                                                String value = entry.getValue();
                                                if (key.contains("投料动作")) {
                                                    if (value.contains("手动投料")) {
                                                        ishand = true;
                                                    } else {
                                                        ishand = false;
                                                    }
                                                }
                                            }
                                        }
                                        //endregion

                                        if (!ishand) {
                                            String writeValue = "1号位";
                                            for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
                                                String key = entry.getKey();
                                                String value = entry.getValue();
                                                if (key.contains("主料位置")) {
                                                    writeValue = value;
                                                }
                                            }
                                            ExecuteTheRecipe.BottomClick1("平移-去" + writeValue);
                                            Log.d("移动去", writeValue);
                                        } else {
                                            ExecuteTheRecipe.BottomClick1("平移-去1号位");
                                            Log.d("移动去", "1号位");
                                        }
                                    } else {
                                        if (!MakeCipe.processname.equals("主料")) {
                                            ExecuteTheRecipe.BottomClick1("平移-去1号位");
                                            Log.d("移动去", "1号位");
                                        }
                                    }
                                }

                            } catch (Exception ex) {
                                ToastUtils.error("异常信息:" + ex.getMessage());
                            }
                        }
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        ToastUtils.info("异常信息:" + e.getMessage());
                    }
                }
            }
        });
        makeThreadDC.start();

        makeThreadUI = new Thread(new Runnable() {
            @Override
            public void run() {
                while (ConfigName.getInstance().IsShow) {
                    try {
                        SxUI();
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        ToastUtils.info("异常信息:" + e.getMessage());
                    }
                }
            }
        });
        makeThreadUI.start();

        ExecuteTheRecipe.NoticeHandSuspension = new IRunT() {
            @Override
            public void Run(Object o) {
                if (ConfigName.getInstance().IsShow) {
                    Activity activity = getActivity();
                    if (activity != null) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if ((boolean) o) {
                                    onRecordPause();
                                } else {
                                    onRecordPauseStart();
                                }
                            }
                        });
                    }
                }
            }
        };

        ExecuteTheRecipe.NoticeAtPresentTime = new IRunT() {
            @Override
            public void Run(Object o) {
                if (ConfigName.getInstance().IsShow) {
                    Activity activity = getActivity();
                    if (activity != null) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                gongxutime.setText("预计等待:" + (int) o + "s");
                            }
                        });
                    }
                }
            }
        };
    }

    /**
     * 温控开关 true 断开  false 闭合
     */
    public boolean TempBool = false;

    /**
     * 刷新UI界面
     */
    public void SxUI() {
        Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Object val_wd = ExecuteTheRecipe.getListingValue("当前锅底温度");
                    Object val_wz = ExecuteTheRecipe.getListingValue("编码器当前位值");
//                    Object val_jbpl = ExecuteTheRecipe.getListingValue("搅拌频率");
//                    Object val_fzpv = ExecuteTheRecipe.getListingValue("翻转频率");

                    //Object val_wd =new Random().nextInt(250);
                    if (val_wd != null) {
                        int dq_wd = (int) val_wd;//当前锅底温度
                        if (dq_wd >= (ConfigName.getInstance().MaxTemp - 5)) //如果当前温度大于最大温度限制  断开
                        {
                            TempBool = true;//设置断开
                        } else if (dq_wd <= (ConfigName.getInstance().MaxTemp - 20))//需要闭合
                        {
                            TempBool = false;//闭合
                        }

//                        if(ConfigName.getInstance().PlcIsConnect)
//                        {
//                            Object tempkg= ExecuteTheRecipe.ReadPLC("温控开关");
//                            if(tempkg!=null)
//                            {
//                                boolean kg=(boolean) tempkg;
//                                if(TempBool) //设置断开
//                                {
//                                    if(kg==false)
//                                    {
//                                        ExecuteTheRecipe.WritePLC("温控开关", true, null);//断开
//                                    }
//                                }else //设置闭合
//                                {
//                                    if(kg)
//                                    {
//                                        ExecuteTheRecipe.WritePLC("温控开关", false, null);//闭合
//                                    }
//                                }
//                            }
//                        }
                        wk_zhuangtai.setText(TempBool ? "断开" : "闭合");
                        wk_zhuangtai.setTextColor(TempBool ? Color.parseColor("#F44336") : Color.parseColor("#01675B"));
                        chaoguo_wendu.setText(val_wd + "");
                    } else {
                        wk_zhuangtai.setText("闭合");
                        wk_zhuangtai.setTextColor(Color.parseColor("#01675B"));
                        chaoguo_wendu.setText("未知");
                    }

                    if (val_wz != null) {
                        chaoguo_weizhi.setText(val_wz + "");
                    } else {
                        chaoguo_weizhi.setText("未知");
                    }

//                    if (val_jbpl != null) {
//                        int val=Integer.parseInt(String.valueOf(val_jbpl));
//                        nifty_slider2.setValue(val,true);
//                    }
//
//                    if (val_fzpv != null) {
//                        int val=Integer.parseInt(String.valueOf(val_jbpl));
//                        nifty_slider3.setValue(val,true);
//                    }

                    plc_zhuangtai.setImageResource(ConfigName.getInstance().PlcIsConnect ? R.mipmap.yjzt : R.mipmap.yjzt1);
                }
            });
        }
    }

    /**
     * 设置进度条百分比
     *
     * @param alltime
     * @param usertime 使用时间
     */
    public void SetProcesssUI(int alltime, int usertime) {
        try {
            jingdu.setProgress((usertime * 100) / alltime);
            jingdu.setSecondProgress((usertime * 100) / alltime);
            shengyushijian.setText("预计剩余时间：" + (alltime - usertime) + "s");
        } catch (Exception ex) {
            ToastUtils.error("异常信息:" + ex.getMessage());
        }
    }

    /**
     * 设置button状态
     *
     * @param status
     */
    public void SetBottonStatus(boolean status) {
        try {
            ExecuteTheRecipe.MakeStatus = status;
            if (status) {
                startbutton.setImageResource(R.mipmap.tzzz);
                TimerCount(good.maketime, true);//开始计时器,记录进度条
                gongxumiaoshu.setText("等待开始");
            } else {
                startbutton.setImageResource(R.mipmap.qdzz);
                TimerCount(0, false);//停止计时器
                gongxumiaoshu.setText("等待开始");
            }
            if (good != null) {
                SetProcesssUI(good.maketime, 0);
            }
        } catch (Exception ex) {
            ToastUtils.error("异常信息:" + ex.getMessage());
        }
    }

    private CountDownTimerExt countDownTimer = null;//计时器

    /**
     * 计时器
     * _
     *
     * @param alltime
     * @param status
     */
    public void TimerCount(int alltime, boolean status) {
        if (status) {
            if (countDownTimer == null) {
                countDownTimer = new CountDownTimerExt(alltime * 1000, 1000) {
                    @Override
                    public void onTimerTick(long millisUntilFinished) {
                        int overtime = (int) ((millisUntilFinished) / 1000);//剩余时间
                        SetProcesssUI(alltime, alltime - overtime);
                    }

                    @Override
                    public void onTimerFinish() {
                        SetProcesssUI(alltime, alltime);//进度条100%
                    }
                };
            }
            countDownTimer.start();
        } else {
            if (countDownTimer != null) {
                countDownTimer.stop();
                countDownTimer = null;
            }
        }
    }

    /**
     * 暂停
     */
    public void onRecordPause() {
        if (countDownTimer != null) {
            countDownTimer.pause();
        }
    }

    /**
     * 继续
     */
    public void onRecordPauseStart() {
        if (countDownTimer != null) {
            countDownTimer.resume();
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.xzcp, R.id.startbutton, R.id.qdjb
            , R.id.yaoqian, R.id.tingyao
            , R.id.ydw, R.id.dcw, R.id.clw, R.id.qxw, R.id.ccw1, R.id.ccw2, R.id.ccw3
            , R.id.chushihua, R.id.jiting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.xzcp://选择菜谱按钮点击
                skipToActivity(CpxzActivity.class);
                ToastUtils.info("打开菜谱选择界面");
                break;
            case R.id.startbutton:
                if (ExecuteTheRecipe.MakeStatus) {
//                    ToastUtils.info("客官菜谱正在制作过程中,请耐心等待一下,马上就好啦!");
//                    return;
                    //按钮点击
                    String title = "停止操作提示！";
                    String message = "请问客官确定要停止制作吗,小菠萝会生气的,啊啊啊啊啊啊啊...我的饭饭？";
                    AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            //强制结束
                            ExecuteTheRecipe.SetForcedEnd();
                            dialog.dismiss();
                        }
                    });
                } else {
                    if (good == null) {
                        ToastUtils.info("请先选择一个商品");
                        return;
                    }

                    if (!ConfigName.getInstance().PlcIsConnect) {
                        ToastUtils.warning("PLC未准备就绪!!!");
                        return;
                    }

                    Object chushiover = ExecuteTheRecipe.getListingValue("初始化完成");
                    if (chushiover == null || !(boolean) chushiover) {
                        ToastUtils.warning("设备未初始化,请先手动初始化设备!!!");
                        return;
                    }

                    //按钮点击
                    String title = "开始操作提示！";
                    String message = "请问客官确定要开始制作吗,小菠萝好开心呀,马上就有好吃的耶？";
                    AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            ExecuteTheRecipe.StopForcedEnd();
                            SetBottonStatus(true);
                            dialog.dismiss();
                        }
                    });
                }
                break;
            case R.id.qdjb://开始清洗
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.BottomClick("炒锅清洗");
                break;
            case R.id.yaoqian:
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.Write_PLC_YaoQian(MyStatus.Start);
                break;
            case R.id.tingyao:
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.Write_PLC_YaoQian(MyStatus.Stop);
                break;
            case R.id.ydw://R.id.ydw, R.id.dcw, R.id.clw,R.id.qxw,R.id.ccw1,R.id.ccw2,R.id.ccw3
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.BottomClick("原点位");
                break;
            case R.id.dcw:
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.BottomClick("倒菜位");
                break;
            case R.id.clw:
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.BottomClick("抽料位");
                break;
            case R.id.qxw:
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.BottomClick("清洗位");
                break;
            case R.id.ccw1:
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.BottomClick("炒菜位1");
                break;
            case R.id.ccw2:
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.BottomClick("炒菜位2");
                break;
            case R.id.ccw3:
                if (!IsMake(true)) {
                    return;
                }
                ExecuteTheRecipe.BottomClick("炒菜位3");
                break;
            case R.id.chushihua:
                ToastUtils.info("点击按钮：初始化");
                ExecuteTheRecipe.BottomClick("初始化");
                break;
            case R.id.jiting:
                ToastUtils.info("点击按钮：急停");
                ExecuteTheRecipe.BottomClick("停止");
                break;
        }
    }

    /**
     * 是否可以制作商品
     *
     * @return
     */
    public boolean IsMake(boolean k) {
        if (!ConfigName.getInstance().PlcIsConnect) {
            ToastUtils.warning("PLC未准备就绪!!!");
            return false;
        }

        Object chushiover = ExecuteTheRecipe.getListingValue("初始化完成");
        //Object jiting = ExecuteTheRecipe.getListingValue("设备急停");
        if (chushiover == null || !(boolean) chushiover) {
            ToastUtils.warning("设备未初始化,请先手动初始化设备!!!");
            return false;
        }

//        if (jiting == null || !(boolean) jiting) {
//            ToastUtils.warning("设备已急停,请检查设备!!!");
//            return false;
//        }

        if (ExecuteTheRecipe.MakeStatus && k) {
            ToastUtils.warning("客官,商品制作未结束请勿进行其他操作.请耐心等待商品制作结束!!!");
            return false;
        }


        return true;
    }

    /**
     * 跳转界面
     */
    private void skipToActivity(Class da) {
        // 跳转到登录页面
        Intent intent = new Intent(context, da);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("第一页销毁");
        ConfigName.getInstance().IsShow=false;
        if (makeThread != null) {
            makeThread = null;
        }
        if (makeThreadDC != null) {
            makeThreadDC = null;
        }
        if (makeThreadUI != null) {
            makeThreadUI = null;
        }
    }

    /**
     * 当在activity设置viewPager + BottomNavigation + fragment时，
     * 为防止viewPager左滑动切换界面，与fragment左滑返回上一界面冲突引起闪退问题，
     * 必须加上此方法，禁止fragment左滑返回上一界面。
     * <p>
     * 切记！切记！切记！否则会闪退！
     * <p>
     * 当在fragment设置viewPager + BottomNavigation + fragment时，则不会出现这个问题。
     */
    @Override
    protected boolean canDragBack() {
        return false;
    }
}
