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

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

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

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_SILOS;
import com.bonait.bnframework.common.helper.CountDownTimerExt;
import com.bonait.bnframework.common.helper.I.IRunT;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.image.MyBitmapUtils;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.mode.imagebuttom;
import com.bonait.bnframework.modules.home.fragment.mode.imagebuttom3;
import com.bonait.bnframework.modules.home.fragment.mode.jingdutiao;
import com.bonait.bnframework.modules.home.fragment.mode.newhuoli_control;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

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

public class CookingSimulatedActivity extends BaseActivity {
    //region 变量
    @BindView(R.id.device_image)
    ImageView device_image;

    @BindView(R.id.touliao_k)
    LinearLayout touliao_k;

    @BindView(R.id.touliao_m)
    LinearLayout touliao_m;

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

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

    @BindView(R.id.runtime)
    TextView runtime;//计时器 倒计时

    @BindView(R.id.t_jindu)
    jingdutiao t_jindu;//计时器

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

    @BindView(R.id.huoli)
    newhuoli_control huoli;

    @BindView(R.id.fanchaoshudu)
    imagebuttom3 fanchaoshudu;


    @BindView(R.id.guokoucaoxiang)
    imagebuttom3 guokoucaoxiang;

//    @BindView(R.id.chushui)
//    imagebuttom3 chushui;

    @BindView(R.id.touliao1)
    imagebuttom3 touliao1;

    @BindView(R.id.touliao2)
    imagebuttom3 touliao2;

    @BindView(R.id.touliao3)
    imagebuttom3 touliao3;

    @BindView(R.id.touliao4)
    imagebuttom3 touliao4;

    @BindView(R.id.yeliao1)
    imagebuttom3 yeliao1;
    @BindView(R.id.yeliao2)
    imagebuttom3 yeliao2;
    @BindView(R.id.yeliao3)
    imagebuttom3 yeliao3;

    @BindView(R.id.yeliao4)
    imagebuttom3 yeliao4;

    @BindView(R.id.showbuttomtop)
    RelativeLayout showbuttomtop;

    public BPA_GOODS goods = new BPA_GOODS();
    public ArrayList<BPA_GOODSRECIPE> goodsrecipes = new ArrayList<>();
    //endregion

    //region 界面实例

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

        Intent intent = getIntent();
        String id = intent.getStringExtra("id");
        if (!id.isEmpty()) {
            goods = QueryDB.GetGoodsId(id);
            if (goods != null) {
                goodsrecipes = QueryDB.GetGoodsSrecipeID(goods.id);
            }
        }
        initData();
        SxUIThread();
    }
    //endregion

    //region 公共方法

    /**
     * 初始化数据
     */
    public void initData() {
        if (ConfigName.getInstance().versionSelectionEnum.equals("大炒版本") || ConfigName.getInstance().versionSelectionEnum.contains("一拖")) {
            touliao_k.setVisibility(View.GONE);
            touliao_m.setVisibility(View.GONE);
            device_image.setImageResource(R.mipmap.device00);
        }else
        {
            touliao_k.setVisibility(View.VISIBLE);
            touliao_m.setVisibility(View.VISIBLE);
            device_image.setImageResource(R.mipmap.device1);
        }

        yeliao1.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(1) + "");
        yeliao1.Init();

        yeliao2.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(2) + "");
        yeliao2.Init();

        yeliao3.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(3) + "");
        yeliao3.Init();

        yeliao4.setTag(ConfigName.getInstance().SilosDisplayMaterial.get(4) + "");
        yeliao4.Init();

        ConcurrentHashMap<Integer, String> resultData = DataBus.getInstance().GetMainDisplayText(goods.id);
        touliao1.setTag(resultData.get(1) + "-按钮");
        touliao1.Init();

        touliao2.setTag(resultData.get(2) + "-按钮");
        touliao2.Init();

        touliao3.setTag(resultData.get(3) + "-按钮");
        touliao3.Init();

        touliao4.setTag(resultData.get(4) + "-按钮");
        touliao4.Init();

        goodname.setText(goods.name + "");
        runtime.setText(formatTime(goods.maketime));
        showbuttomtop.setVisibility(View.VISIBLE);
        Stop();
    }

    /**
     * 设置描述
     *
     * @param text
     */
    public void SetMiaoShu(String text) {
        gongxumiaoshu.setText(text + "");
    }

    /**
     * 设置进度条
     *
     * @param
     */
    public void SetProcess(int alltime, int usertime) {
        try {
            t_jindu.SetValue((usertime * 100) / alltime);
            runtime.setText(formatTime((alltime - usertime)));
        } catch (Exception ex) {
            ToastUtils.error("异常信息:" + ex.getMessage());
        }
    }


    public void Stop() {
        if (flicker_buttom != null) {
            flicker_buttom.setVisibility(View.VISIBLE);
            flicker_buttom.SetStatusKK(false);
            flicker_buttom = null;
        }
        huoli.SetLevel(0);
        SetMiaoShu("等待开始...");
        SetProcess(goods.maketime, 0);
    }
    //endregion

    //region 私有方法

    /**
     * 将毫秒转化为 分钟：秒 的格式    100* 1000
     *
     * @param millisecond 毫秒
     * @return
     */
    public String formatTime(long millisecond) {
        int minute;//分钟
        int second;//秒数
        minute = (int) ((millisecond / 1) / 60);
        second = (int) ((millisecond / 1) % 60);
        if (minute < 10) {
            if (second < 10) {
                return "0" + minute + " : " + "0" + second;
            } else {
                return "0" + minute + " : " + second;
            }
        } else {
            if (second < 10) {
                return minute + " : " + "0" + second;
            } else {
                return minute + " : " + second;
            }
        }
    }

    /**
     * 初始化顶部弹框
     */
    private void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.topbj1));
        mTopBar.setTitle("模拟炒制");
        mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.kaishimoni, R.id.jieshutuichu, R.id.tuichu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.kaishimoni:
                StartSimulated();
                break;
            case R.id.tuichu:
            case R.id.jieshutuichu:
                finish();
                break;
        }
    }

    /**
     * 闪烁buttom
     */
    public imagebuttom3 flicker_buttom = null;

    /**
     * 刷新UI界面
     */
    public void SxUIThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true) {
                    try {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //闪烁
                                if (flicker_buttom != null) {
                                    flicker_buttom.setVisibility(flicker_buttom.getVisibility() == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
                                }
                            }
                        });
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        ToastUtils.info("异常信息:" + e.getMessage());
                    }
                }
            }
        }).start();
    }
    //endregion

    //region 外部调用
    private CountDownTimerExt countDownTimer = null;//计时器

    /**
     * 启动
     */
    public void onRecordStart() {
        if (goods != null) {
            int time = goods.maketime;
            SetProcess(time, 0);
            if (countDownTimer == null) {
                countDownTimer = new CountDownTimerExt(time * 1000, 1000) {
                    @Override
                    public void onTimerTick(long value) {
                        int overtime = (int) ((value) / 1000);//剩余时间
                        SetProcess(time, time - overtime);
                    }

                    @Override
                    public void onTimerFinish() {
                        SetProcess(time, time);
                    }
                };
            }
            countDownTimer.start();
        }
    }

    /**
     * 停止
     */
    public void onRecordStop() {
        if (goods != null) {
            SetProcess(goods.maketime, 0);
            SetMiaoShu("等待开始...");
            if (countDownTimer != null) {
                countDownTimer.stop();
                countDownTimer = null;
            }
            Stop();
        }
    }

    /**
     * 启动模拟播放
     */
    public void StartSimulated() {
        showbuttomtop.setVisibility(View.GONE);
        onRecordStart();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (BPA_GOODSRECIPE recipe : goodsrecipes) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SetMiaoShu("正在执行：" + recipe.processms);
                        }
                    });

                    try {
                        String ms = "";
                        String text = recipe.processvalue;
                        if (recipe.materialType == 0)//正常物料
                        {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    CarryOut("位置|抽料位");
                                }
                            });
                            Thread.sleep(2000);
                            if (!text.isEmpty()) {
                                //仓号 值
                                HashMap<Integer, Integer> formulation = new HashMap<>();
                                //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];
                                            int val = (int) Math.round((Double.parseDouble(wl[1]) * 10));
                                            //int val = Integer.parseInt(wl[1]);
                                            List<BPA_SILOS> bpa_silos = QueryDB.GetSolisByMaterialName(name);
                                            if (bpa_silos.size() > 0 && val > 0) {
                                                BPA_SILOS silos = bpa_silos.get(0);
                                                formulation.put(silos.num, val);
                                            }
                                        }
                                    }
                                }
                                //endregion
                                //写入PLC,直接出料，不用等待
                                for (Map.Entry<Integer, Integer> entry : formulation.entrySet()) {
                                    Integer key = entry.getKey();
                                    Integer value = entry.getValue();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            CarryOut("液体料|" + key);
                                        }
                                    });
                                    Thread.sleep(2000);
                                }
                            }
                        } else if (recipe.materialType == 1)//工序模型
                        {
                            if (recipe.processname.equals("抽水")) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        CarryOut("位置|抽料位");
                                    }
                                });
                                Thread.sleep(2000);
                            } else if (recipe.processname.equals("主料")) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        CarryOut("位置|炒菜位1");
                                    }
                                });
                                Thread.sleep(2000);
                            }

                            //工序名称和值
                            HashMap<String, String> formulation = new HashMap<>();
                            //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

                            switch (recipe.processname) {
                                case "搅拌":
                                case "位置":
                                case "加水":
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            CarryOut(recipe.processname + "|未知");
                                        }
                                    });
                                    Thread.sleep(2000);
                                    break;
                                case "加热":
                                    int val = 0;
                                    for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
                                        String key = entry.getKey();
                                        String value = entry.getValue();
                                        if (key.contains("(秒)")) {
                                            val = Integer.parseInt(value);
                                        } else {
                                            ToastUtils.info("工序:" + key + "," + value);
                                            int writeValue = ExecuteTheRecipe.GetMXValue(key, value);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    CarryOut(recipe.processname + "|" + writeValue);
                                                }
                                            });
                                            Thread.sleep(2000);
                                        }
                                    }

                                    if (val > 0) {
                                        Thread.sleep(val * 1000);
                                    }
                                    break;
                                case "主料":
                                    String writeValue = "1号位";
                                    val = 0;

                                    for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
                                        String key = entry.getKey();
                                        String value = entry.getValue();
                                        if (key.contains("主料位置")) {
                                            writeValue = value;
                                            String finalWriteValue = writeValue;
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    CarryOut(recipe.processname + "|" + finalWriteValue);
                                                }
                                            });
                                            Thread.sleep(2000);
                                        } else if (key.contains("(秒)")) {
                                            val = Integer.parseInt(value);
                                        }
                                    }

                                    if (val > 0) {
                                        Thread.sleep(val * 1000);
                                    }
                                    break;
                                case "延迟":
                                    for (HashMap.Entry<String, String> entry : formulation.entrySet()) {
                                        String key = entry.getKey();
                                        String value = entry.getValue();
                                        ToastUtils.info("工序:" + key + "," + value);
                                        if (key.contains("(秒)")) {
                                            int val11 = Integer.parseInt(value);
                                            Thread.sleep(val11 * 1000);
                                        }
                                    }
                                    break;
                            }

                        }
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onRecordStop();
                        showbuttomtop.setVisibility(View.VISIBLE);
                    }
                });
            }
        }).start();
    }

    public void CarryOut(String data) {
        if (data.contains("|")) {
            String[] K = data.split("[|]");
            if (K.length >= 2) {
                String name = K[0];
                String val = K[1];
                if (flicker_buttom != null) {
                    flicker_buttom.setVisibility(View.VISIBLE);
                    flicker_buttom.SetStatusKK(false);
                }
                flicker_buttom = null;
                switch (name) {
                    case "搅拌":
                        flicker_buttom = fanchaoshudu;
                        flicker_buttom.SetStatusKK(true);
                        break;
                    case "位置":
                        flicker_buttom = guokoucaoxiang;
                        flicker_buttom.SetStatusKK(true);
                        break;
                    case "加热":
                        huoli.SetLevel(Integer.parseInt(val));
                        break;
                    case "主料":
                        if (val.equals("1号位")) {
                            flicker_buttom = touliao1;
                        } else if (val.equals("2号位")) {
                            flicker_buttom = touliao2;
                        } else if (val.equals("3号位")) {
                            flicker_buttom = touliao3;
                        } else if (val.equals("4号位")) {
                            flicker_buttom = touliao4;
                        }
                        flicker_buttom.SetStatusKK(true);
                        break;
                    case "加水":
//                        flicker_buttom = chushui;
//                        flicker_buttom.SetStatusKK(true);
                        break;
                    case "液体料":
                        if (val.equals("1")) {
                            flicker_buttom = yeliao1;
                            flicker_buttom.SetStatusKK(true);
                        } else if (val.equals("2")) {
                            flicker_buttom = yeliao2;
                            flicker_buttom.SetStatusKK(true);
                        } else if (val.equals("3")) {
                            flicker_buttom = yeliao3;
                            flicker_buttom.SetStatusKK(true);
                        }else if (val.equals("4")) {
                            flicker_buttom = yeliao4;
                            flicker_buttom.SetStatusKK(true);
                        }
                        break;
                }
            }
        }
    }
    //endregion
}