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

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseActivity;
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.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.mode.fragment_gx;
import com.bonait.bnframework.modules.home.fragment.mode.huoli_control;
import com.bonait.bnframework.modules.home.fragment.mode.item_gx;
import com.litao.slider.NiftySlider;
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 java.util.ArrayList;

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

public class DiyMemoryActivity extends BaseActivity {

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    @BindView(R.id.gxchid)
    LinearLayout gxchid;//工序子集

    @BindView(R.id.start_bj)
    LinearLayout start_bj;//背景

    @BindView(R.id.startbutton)
    ImageView startbutton;//启动停止

    public boolean isRun = false;

    @BindView(R.id.runtime)
    Chronometer runtime;//运行时间

    @BindView(R.id.huoli)
    huoli_control huoli;//火力 控件

    @BindView(R.id.nifty_slider2)
    NiftySlider nifty_slider2;//搅拌挡位

//    @BindView(R.id.nifty_slider3)
//    NiftySlider nifty_slider3;//移动挡位


    @BindView(R.id.zhuliaotouliao)
    LinearLayout zhuliaotouliao;//
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diy_memory);
        ButterKnife.bind(this);
        initTopBar();
        initData();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        try {

            if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本") || ConfigName.getInstance().versionSelectionEnum.contains("一拖")) {
                zhuliaotouliao.setVisibility(View.GONE);
            } else {
                zhuliaotouliao.setVisibility(View.VISIBLE);
            }

            DataBus.getInstance().bpa_goodsrecipes.clear();
            gxchid.removeAllViews();
            ArrayList<BPA_MATERIAL> materials = QueryDB.GetMaterialALL();
            for (BPA_MATERIAL item2 : materials) {
                item_gx gx = new item_gx();
                gx.datatype = 0;//液体料都是数字
                gx.name = item2.name;
                gx.IsWL = true;
                fragment_gx gongxu = new fragment_gx(this, null, gx);
                gxchid.addView(gongxu);
            }
        } catch (Exception ex) {
        }
    }

    private void initTopBar() {
        mTopBar.setTitle("手动操作模式");
        mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isRun) {
                    ToastUtils.warning("请先结束烹饪！！！");
                } else {
                    finish();
                }
            }
        });
        //为Chronomter绑定事件监听器,超过一小时自动日内告知
        runtime.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                //如果计时到现在超过了一小时秒
                if (SystemClock.elapsedRealtime() - runtime.getBase() > 3600 * 1000) {
                    runtime.stop();
                }
            }
        });

        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 + "");
//            }
//        });
        nifty_slider2.setValue(0, true);
//        nifty_slider3.setValue(0, true);

        huoli.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
                if (isRunClick()) {
                    long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
                    int time = (int) (elapsedMillis / 1000);//当前点击多少秒
                    int time_c = time - ClikTime;

                    if (time_c > 0)//如果大于0，那么加一个延迟
                    {
                        DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
                    }

                    String sdstr = Get挡位((int) data);
                    BPA_GOODSRECIPE data1 = Get加热(sdstr);
                    DataBus.getInstance().bpa_goodsrecipes.add(data1);
                    ClikTime = time;
                    ExecuteTheRecipe.Write_PLC_HuoLI((int) data);
                }

            }

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

            }
        };
    }


    public int TimeOut = 0;//当前运行总时长
    public int ClikTime = 0;//上一次点击时间

    @OnClick({R.id.startbutton, R.id.querendangwei,
            R.id.chuliao, R.id.touliao1, R.id.touliao0,
            R.id.touliao2, R.id.touliao3,
            R.id.touliao4
            , R.id.ydw, R.id.dcw, R.id.clw
            , R.id.qxw, R.id.ccw1, R.id.ccw2, R.id.ccw3
            , R.id.zidongchucan
            , R.id.touliao_sd})
    public void onViewClicked(View view) {
        long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
        int time = (int) (elapsedMillis / 1000);//当前点击多少秒
        int time_c = time - ClikTime;

        switch (view.getId()) {
            case R.id.touliao_sd://手动投料
                ShouDongMainDish();
                break;
            case R.id.startbutton://启动 停止
                if (isRun) {
                    String title = "停止操作提示！";
                    String message = "请问客官确定要停止制作吗,小菠萝会生气的,啊啊啊啊啊啊啊...我的饭饭？";
                    AlertDialogUtils.showDialog(view.getContext(), title, message, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            StopTime();
                            dialog.dismiss();
                        }
                    });
                } else {

                    String title = "开始操作提示！";
                    String message = "请问客官确定要开始制作吗,小菠萝好开心呀,马上就有好吃的耶？";
                    AlertDialogUtils.showDialog(view.getContext(), title, message, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            StartTime();
                            dialog.dismiss();
                        }
                    });
                }
                break;
            case R.id.querendangwei://确认搅拌挡位
                if (isRunClick()) {
                    if (time_c > 0)//如果大于0，那么加一个延迟
                    {
                        DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
                    }

                    int sd = (int) nifty_slider2.getValue();
                    String sdstr = Get速度(sd);
                    BPA_GOODSRECIPE data = Get搅拌(sdstr);
                    DataBus.getInstance().bpa_goodsrecipes.add(data);
                    ExecuteTheRecipe.WritePLC("搅拌速度", sd, new IWriteCallBack() {
                        @Override
                        public void onSuccess() {
                            if (sd == 0) {
                                ExecuteTheRecipe.WritePLC("搅拌", false, null);
                            } else {
                                ExecuteTheRecipe.WritePLC("搅拌", true, null);
                            }
                        }

                        @Override
                        public void onFailure(String ErrorMsg) {
                        }
                    });
                    ClikTime = time;
                }
                break;
            case R.id.chuliao://出料
                if (isRunClick()) {
                    BPA_GOODSRECIPE data = GetSelectItemFromValue();
                    if (data != null) {
                        DataBus.getInstance().bpa_goodsrecipes.add(data);
                        MakeRecipe(data);
                        ClikTime = time;
                    }
                }
                break;
            case R.id.touliao0://主料1
                if (isRunClick()) {
                    ExecuteTheRecipe.BottomClick("平移-去1号位");
                }
                break;
            case R.id.touliao1://主料1
                ClickZL(time, time_c, 1);
                break;
            case R.id.touliao2://主料2
                ClickZL(time, time_c, 2);
                break;
            case R.id.touliao3://主料3
                ClickZL(time, time_c, 3);
                break;
            case R.id.touliao4://主料4
                ClickZL(time, time_c, 4);
                break;
            case R.id.ydw://原点位
                ClickWZ(time, time_c, "原点位");
                break;
            case R.id.dcw://到菜位
                ClickWZ(time, time_c, "倒菜位");
                break;
            case R.id.clw://出料位置
                ClickWZ(time, time_c, "抽料位");
                break;
            case R.id.qxw://清洗位置
                ClickWZ(time, time_c, "清洗位");
                break;
            case R.id.ccw1://炒菜位1
                ClickWZ(time, time_c, "炒菜位1");
                break;
            case R.id.ccw2://炒菜位2
                ClickWZ(time, time_c, "炒菜位2");
                break;
            case R.id.ccw3://炒菜位3
                ClickWZ(time, time_c, "炒菜位3");
                break;
            case R.id.zidongchucan://自动出餐
                if (isRunClick()) {
                    BPA_GOODSRECIPE data1 = Get出菜(time_c);
                    DataBus.getInstance().bpa_goodsrecipes.add(data1);
//                    BPA_GOODSRECIPE data2 = Get清洗(0);
//                    DataBus.getInstance().bpa_goodsrecipes.add(data2);
                    MakeRecipe(data1);
                    ClikTime = time;
                }
                break;
        }
    }

    //region 常用函数

    /**
     * 是否运行
     *
     * @return
     */
    public boolean isRunClick() {
        if (!isRun) {
            ToastUtils.warning("请先开始计时器！！！");
            return false;
        }

        if (isMake) {
            ToastUtils.warning("请等待上一步骤结束！！！");
            return false;
        }


//        if (!isRun) {
//            ToastUtils.info("请先开始计时器！！！");
//            return false;
//        }

        return true;
    }

    public void ClickZL(int time, int time_c, int num) {
//        Object sb = ExecuteTheRecipe.ReadPLC("平移轴在1号位");
//        if (sb != null) {
//            if ((boolean) (sb)) {
//
//            } else {
//                ToastUtils.warning("平移轴未复位!!!");
//            }
//        } else {
//            ToastUtils.warning("PLC未连接!!!");
//        }

        if (isRunClick()) {
            if (time_c > 0)//如果大于0，那么加一个延迟
            {
                DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
            }

            //控制去炒菜位
            BPA_GOODSRECIPE data1 = Get位置("高速", "炒菜位1");
            DataBus.getInstance().bpa_goodsrecipes.add(data1);

            BPA_GOODSRECIPE data = Get主料(num);
            DataBus.getInstance().bpa_goodsrecipes.add(data);
            MakeRecipe(data);//执行主料
            ClikTime = time;
        }

    }

    public void ClickWZ(int time, int time_c, String name) {
        if (isRunClick()) {
            if (time_c > 0)//如果大于0，那么加一个延迟
            {
                DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
            }

//            int sd = (int) nifty_slider3.getValue();
//            String sdstr= Get速度(sd);
            BPA_GOODSRECIPE data = Get位置("高速", name);
            DataBus.getInstance().bpa_goodsrecipes.add(data);
            MakeRecipe(data);
            ClikTime = time;
        }
    }

    public boolean isMake = false;

    public void MakeRecipe(BPA_GOODSRECIPE recipe) {
        isMake = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (recipe.materialType == 0)//正常物料
                {
                    BPA_GOODSRECIPE data1 = Get位置("高速", "抽料位");
                    ExecuteTheRecipe.ExecuteOperationSteps(data1.processname, data1.processvalue);

                    ExecuteTheRecipe.ExecuteMaterialIssuance(recipe.processvalue);
                } else if (recipe.materialType == 1)//工序模型
                {
                    if (recipe.processname.equals("主料")) {
                        BPA_GOODSRECIPE data1 = Get位置("高速", "炒菜位1");
                        ExecuteTheRecipe.ExecuteOperationSteps(data1.processname, data1.processvalue);
                        ExecuteTheRecipe.ExecuteOperationSteps(recipe.processname, recipe.processvalue);
                    } else {
                        if (recipe.processname.equals("出菜")) {
                            ExecuteTheRecipe.ExecuteOperationSteps(recipe.processname, recipe.processvalue);
                            BPA_GOODSRECIPE data2 = Get清洗(0);
                            ExecuteTheRecipe.ExecuteOperationSteps(data2.processname, data2.processvalue);
                        } else {
                            ExecuteTheRecipe.ExecuteOperationSteps(recipe.processname, recipe.processvalue);
                        }
                    }
                }
                isMake = false;
            }
        }).start();
    }

    /**
     * 手动投主菜品
     *
     * @param
     */
    public void ShouDongMainDish() {
        int time = (int) ((SystemClock.elapsedRealtime() - runtime.getBase()) / 1000);//当前点击多少秒
        int time_c = time - ClikTime;

        if (time_c > 0)//如果大于0，那么加一个延迟
        {
            DataBus.getInstance().bpa_goodsrecipes.add(Get延迟(time_c));
        }
        DataBus.getInstance().bpa_goodsrecipes.add(Get手动主料());
        ExecuteTheRecipe.WritePLC("暂停开关", true, null);
        String title = "手动投料-温馨提示！";
        String message = "客官请投入主料,投入后点击[确定]继续流程！";
        new QMUIDialog.MessageDialogBuilder(context)
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .setTitle(title)
                .setMessage(message)
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        ExecuteTheRecipe.WritePLC("暂停开关", false, null);
                        ClikTime = (int) ((SystemClock.elapsedRealtime() - runtime.getBase()) / 1000);
                        dialog.dismiss();
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();

    }

    /**
     * 获取选中行的变量
     *
     * @return
     */
    public BPA_GOODSRECIPE GetSelectItemFromValue() {
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        try {
            boolean IsVerify = true;
            String description = "";
            //  延迟,100|延迟,100|延迟,100|延迟,100|
            String data = "";
            String desc = "";

            pf.materialType = 0;
            for (int i = 0; i < gxchid.getChildCount(); i++) {
                fragment_gx gongxu = (fragment_gx) gxchid.getChildAt(i);
                String values = gongxu.GetValues();
                if (!values.isEmpty()) {
                    data += gongxu.model.name + "," + values + "|";
                    desc += values + ",";
                }
            }

            if (data.isEmpty()) {
                IsVerify = false;
                description += "物料-不能为空,请勾选一个物料\n";
            }


            if (IsVerify) {
                pf.processname = "液体料";
                pf.processms = "液体料" + "(" + desc.substring(0, desc.length() - 1) + ")";
                pf.processvalue = data.substring(0, data.length() - 1);
                return pf;
            } else {
                ToastUtils.error("数据验证失败,原因:" + description);
                return null;
            }
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 获取延迟
     *
     * @param time
     * @return
     */
    public BPA_GOODSRECIPE Get延迟(int time) {
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        pf.materialType = 1;
        pf.processname = "延迟";
        pf.processms = "延迟(" + time + ")";
        pf.processvalue = "延迟(秒)," + time;
        return pf;
    }

    /**
     * 获取清洗
     *
     * @return
     */
    public BPA_GOODSRECIPE Get清洗(int k) {
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        pf.materialType = 1;
        pf.processname = "清洗";
        pf.processms = "清洗(" + k + ")";
        pf.processvalue = "等待(秒)," + k;
        return pf;
    }

    /**
     * 获取主料
     *
     * @param wz
     * @return
     */
    public BPA_GOODSRECIPE Get主料(int wz) {
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        pf.materialType = 1;
        pf.processname = "主料";
        pf.processms = "主料(未知," + wz + "号位,0,直接投出,0)";
        pf.processvalue = "主料名称,未知|主料位置," + wz + "号位|主料重量,0|投料动作,直接投出|烹饪(秒),0";
        return pf;
    }

    /**
     * 获取手动主料
     *
     * @param
     * @return
     */
    public BPA_GOODSRECIPE Get手动主料() {
        String ms = "未知";
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        pf.materialType = 1;
        pf.processname = "主料";
        pf.processms = "主料(" + ms + ",1号位,0,手动投料,0)";
        pf.processvalue = "主料名称," + ms + "|主料位置,1号位|主料重量,0|投料动作,手动投料|烹饪(秒),0";
        return pf;
    }

    /**
     * 获取位置
     *
     * @param sd
     * @return
     */
    public BPA_GOODSRECIPE Get位置(String sd, String name) {
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        pf.materialType = 1;
        pf.processname = "位置";
        pf.processms = "位置(" + sd + "," + name + ",0)";
        pf.processvalue = "转动速度," + sd + "|位置动作," + name + "|延迟(秒),0";
        return pf;
    }

    /**
     * 获取搅拌
     *
     * @param sd
     * @return
     */
    public BPA_GOODSRECIPE Get搅拌(String sd) {
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        pf.materialType = 1;
        pf.processname = "搅拌";
        pf.processms = "搅拌(" + sd + ",0)";
        pf.processvalue = "搅拌速度," + sd + "|延迟(秒),0";
        return pf;
    }

    /**
     * 获取加热
     *
     * @param sd
     * @return
     */
    public BPA_GOODSRECIPE Get加热(String sd) {
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        pf.materialType = 1;
        pf.processname = "加热";
        pf.processms = "加热(" + sd + ",0)";
        pf.processvalue = "加热功率," + sd + "|延迟(秒),0";
        return pf;
    }

    /**
     * 获取出菜
     *
     * @return
     */
    public BPA_GOODSRECIPE Get出菜(int k) {
        BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
        pf.materialType = 1;
        pf.processname = "出菜";
        pf.processms = "出菜(" + k + ")";
        pf.processvalue = "等待(秒)," + k;
        return pf;
    }

    /**
     * 获取速度
     *
     * @return
     */
    public String Get速度(int speed) {
        if (speed >= 0 && speed < 5) {
            return "停止";
        } else if (speed >= 5 && speed < 15) {
            return "最低";
        } else if (speed >= 15 && speed < 25) {
            return "低速";
        } else if (speed >= 25 && speed < 35) {
            return "中速";
        } else if (speed >= 35 && speed < 45) {
            return "高速";
        } else if (speed >= 45 && speed < 55) {
            return "最高";
        } else {
            return "极高";
        }
    }

    /**
     * 获取挡位
     *
     * @return
     */
    public String Get挡位(int speed) {
        if (speed == 0) {
            return "停止";
        } else if (speed == 1) {
            return "一档";
        } else if (speed == 2) {
            return "二档";
        } else if (speed == 3) {
            return "三档";
        } else if (speed == 4) {
            return "四档";
        } else if (speed == 5) {
            return "五档";
        } else if (speed == 6) {
            return "六档";
        } else if (speed == 7) {
            return "七档";
        } else {
            return "八档";
        }
    }

    /**
     * 启动定时器
     */
    public void StartTime() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //设置开始计时时间
                runtime.setBase(SystemClock.elapsedRealtime());
                //启动计时器
                runtime.start();
                isRun = true;
                startbutton.setImageResource(R.mipmap.stop_js);
                //5700FF22
                //25FF9800
                start_bj.setBackgroundColor(Color.parseColor("#5700FF22"));

                DataBus.getInstance().bpa_goodsrecipes.clear();//清空所有工序
                TimeOut = 0;
                ClikTime = 0;
            }
        });

    }

    /**
     * 停止定时器
     */
    public void StopTime() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //启动计时器
                runtime.stop();
                isRun = false;
                startbutton.setImageResource(R.mipmap.start_js);

                start_bj.setBackgroundColor(Color.parseColor("#25FF9800"));

                long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
                TimeOut = (int) (elapsedMillis / 1000);//当前点击多少秒
                DataBus.getInstance().TimeOut = TimeOut;
                if (DataBus.getInstance().bpa_goodsrecipes.size() >= 0) {
                    MessageManager.getInstance().sendMessage(MessageName.DIY, "DIY");
                }

                ExecuteTheRecipe.WritePLC("搅拌", false, null);
                ExecuteTheRecipe.WritePLC("加热", false, null);
                ConfigName.getInstance().IsOpenHuoLi = false;
                ExecuteTheRecipe.BottomClick("平移-去1号位");
            }
        });

    }
    //endregion


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected boolean canDragBack() {
        return false;
    }
}