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

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
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.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.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.MyClickListener;
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.ModbusTcpMainServer;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.BottomNavigationBar;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.bonait.bnframework.modules.home.adapter.FragmentAdapter;
import com.bonait.bnframework.modules.home.fragment.Home1Fragment;
import com.bonait.bnframework.modules.home.fragment.Home2Fragment;
import com.bonait.bnframework.modules.home.fragment.Home4Fragment;
import com.bonait.bnframework.modules.home.fragment.HomeFragmentPR;
import com.bonait.bnframework.modules.home.fragment.HomeFragmentSBKZ;
import com.bonait.bnframework.modules.home.fragment.from.CookingActivity;
import com.bonait.bnframework.modules.mine.fragment.MyFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.lzy.okgo.OkGo;
import com.qmuiteam.qmui.widget.QMUIViewPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

public class BottomNavigationNewActivity extends BaseActivity {

    //region 变量
    @BindView(R.id.navigation)
    BottomNavigationBar bottomNavigationView;

    @BindView(R.id.viewpager)
    QMUIViewPager viewPager;

    @BindView(R.id.cooking)
    CookingActivity cooking;

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

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

    //region 界面私立
    public Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_navigation_new);
        ButterKnife.bind(this);
        activity = this;
        Init();
        initFragment();
        viewPager.addOnPageChangeListener(pageChangeListener);
        // 设置viewPager缓存多少个fragment
        viewPager.setOffscreenPageLimit(3);
        bottomNavigationView.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
                int index = (int) data;
                viewPager.setCurrentItem(index);
            }

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

            }
        };
        viewPager.setCurrentItem(1);
    }

    @Override
    protected void onDestroy() {
        ConfigData.getInstance().ColsePLC();
        ConfigName.getInstance().IsShowNew = false;
        if (makeThread != null) {
            makeThread = null;
        }
        if (makeThreadDC != null) {
            makeThreadDC = null;
        }
        super.onDestroy();
    }

    @Override
    protected boolean canDragBack() {
        return viewPager.getCurrentItem() == 0;
    }

    //endregion

    //region 私有函数

    /**
     * viewPager里添加fragment
     */
    private void initFragment() {
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
        fragmentAdapter.addFragment(new HomeFragmentPR());
        fragmentAdapter.addFragment(new Home4Fragment());
        fragmentAdapter.addFragment(new HomeFragmentSBKZ());
        viewPager.setAdapter(fragmentAdapter);

        MessageManager.getInstance().registerMessageReceiver(this, MessageName.SelectZY, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    int index = (int) msg;
                    viewPager.setCurrentItem(index);
                    cooking.setVisibility(View.GONE);
                    ShowMakeLoading();
                }
            }
        });

        //打开制作界面
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.OpenMakeGoodFrom, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String id = (String) msg;
                            goods = QueryDB.GetGoodsId(id);
                            cooking.initData(goods, activity, myClickListener);
                            cooking.setVisibility(View.VISIBLE);
                        }
                    });

                }
            }
        });

        //打开制作界面
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.IsStratMakeGood, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ExecuteTheRecipe.StopForcedEnd();
                            cooking.SetStartStaus(true);
                            ExecuteTheRecipe.IsPause = false;
                            ExecuteTheRecipe.WritePLC("暂停开关", false, null);
                            onRecordStart();
                        }
                    });

                }
            }
        });
    }

    /**
     * 配置ViewPager监听器，手指滑动监听
     */
    private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            bottomNavigationView.SelectIndexTab(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private long exitTime = 0;

    /**
     * 重写返回键，实现双击退出程序效果
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastUtils.normal("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                OkGo.getInstance().cancelAll();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                ActivityLifecycleManager.get().appExit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.penrenzhong
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.penrenzhong:
                if (goods != null) {
                    cooking.setVisibility(View.VISIBLE);
                    penrenzhong.setVisibility(View.GONE);
                }
                break;
        }
    }
    //endregion

    //region 公共函数

    /**
     * 是否显示制作中, 看菜谱 商品制作开始 商品制作结束
     */
    public void ShowMakeLoading() {
        if (cooking.getVisibility() == View.GONE && ExecuteTheRecipe.IsStart) {
            penrenzhong.setVisibility(View.VISIBLE);
        } else {
            penrenzhong.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化
     */
    public void Init() {
        //1.同步时间
        NetworkUtils.SynchronizationTime();
        //主持
        ConfigData.getInstance().GetOrganize(this);
        //判断连接环境
        ConfigData.getInstance().ToggleEnvironment();
        //2.初始化PLC
        ReconnectModbus();
        //制作线程
        MakeThread();
        //初始化阿里云连接
        //AliyunIOTManager.getInstance().OpenDev(this);
    }

    /**
     * 重新连接plc
     */
    public void ReconnectModbus() {
        try {
            ConfigName.getInstance().IsShowNew=true;
            ConfigName.getInstance().IsShow=false;
            ThreadManager.Get().StartLong("PLC断线重连线程新界面", true, new IThread() {
                @Override
                public void Run() throws InterruptedException {
                    try {
                        if (ConfigName.getInstance().IsShowNew) {
                            if (ConfigName.getInstance().PlcIsConnect) {
                                //ping 不通
                                boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
                                if (!status) //ping 不通 连接
                                {
                                    MessageLog.ShowInfo("新版本:PLC状态断开,尝试连接...");
                                    ConfigName.getInstance().PlcIsConnect = false;
                                }
                            } else {
                                boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
                                if (status) {
                                    MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接！");
                                    ModbusTcpServer.ConnectPLC();
                                } else {
                                    MessageLog.ShowInfo("新版本:PLC状态断开,尝试连接...");
                                    ConfigName.getInstance().PlcIsConnect = false;
                                }
                            }

                            if (ConfigName.getInstance().versionSelectionEnum.contains("一拖")) {
                                if (ConfigName.getInstance().PlcMainIsConnect) {
                                    //ping 不通
                                    boolean status = ModbusTcpMainServer.ping2(ConfigName.getInstance().MainAddress, 1, 1);
                                    if (!status) //ping 不通 连接
                                    {
                                        MessageLog.ShowInfo("新版本:主控PLC状态断开,尝试连接...");
                                        ConfigName.getInstance().PlcMainIsConnect = false;
                                    }
                                } else {
                                    boolean status = ModbusTcpMainServer.ping2(ConfigName.getInstance().MainAddress, 1, 1);
                                    if (status) {
                                        MessageLog.ShowInfo("设备 " + ConfigName.getInstance().MainAddress + " 主控PLC通讯正常,准备连接！");
                                        ModbusTcpMainServer.ConnectPLC();
                                    } else {
                                        MessageLog.ShowInfo("新版本:主控PLC状态断开,尝试连接...");
                                        ConfigName.getInstance().PlcMainIsConnect = false;
                                    }
                                }
                            }
                        }
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        Log.i("PLC", "PLC重连接失败!" + e.getMessage());
                    }
                }

                @Override
                public void RunComplete() throws InterruptedException {
                }
            });
        } catch (Exception e) {
            MessageLog.ShowInfo("重新连接Modbus异常，" + e.getMessage());
        }
    }
    //endregion

    //region 制作
    int gongxuIndex = 10000;
    ArrayList<BPA_GOODSRECIPE> goodsrecipesL = null;
    BPA_GOODSRECIPE MakeCipe = null;
    //商品
    public BPA_GOODS goods = null;


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

    /**
     * 商品制作线程
     */
    public void MakeThread() {
        ExecuteTheRecipe.context = this;
        makeThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (ConfigName.getInstance().IsShowNew) {
                    try {
                        if (ExecuteTheRecipe.IsStart && goods != null) {
                            long startTime = System.currentTimeMillis(); //起始时间
                            ExecuteTheRecipe.showlog("--------------------------------------");

                            ExecuteTheRecipe.showlog("开始烹饪菜谱【" + goods.name + "】");
                            ModbusTcpServer.get().WriteBool("M52.0", (boolean) true, null);
                            ExecuteTheRecipe.HandTime = 0;//默认将手动操作时间复位

                            try {
                                //获取工艺
                                ArrayList<BPA_GOODSRECIPE> goodsrecipes = QueryDB.GetGoodsSrecipeID(goods.id);
                                goodsrecipesL = goodsrecipes;
                                gongxuIndex = 1;
                                int m = 0;
                                for (BPA_GOODSRECIPE item : goodsrecipes) {
                                    while (ExecuteTheRecipe.IsPause) {
                                        ToastUtils.info("客官,当前菜品已暂停炒制!!!");
                                        Thread.sleep(1000);
                                    }
                                    MakeCipe = item;
                                    gongxuIndex++;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            cooking.SetMiaoShu("正在执行：" + 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;
                                ExecuteTheRecipe.IsStart = false;

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

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

                                ExecuteTheRecipe.all_list = new ArrayList<>();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        onRecordStop();
                                        if (ExecuteTheRecipe.IsForcedEnd)//强制结束
                                        {
                                            ToastUtils.info("客官,当前菜品已强制结束!!!");
                                            //初始化
                                            //ExecuteTheRecipe.BottomClick("初始化");
                                            ExecuteTheRecipe.showlog("菜谱【" + goods.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().IsShowNew) {
                    try {

                        if (ExecuteTheRecipe.IsStart && goods != 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.BottomClick("平移-去" + writeValue);
                                            Log.d("移动去", writeValue);
                                        } else {
                                            ExecuteTheRecipe.BottomClick("平移-去1号位");
                                            Log.d("移动去", "1号位");
                                        }
                                    } else {
                                        if (!MakeCipe.processname.equals("主料")) {
                                            ExecuteTheRecipe.BottomClick("平移-去1号位");
                                            Log.d("移动去", "1号位");
                                        }
                                    }
                                }

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

        ExecuteTheRecipe.NoticeHandSuspension = new IRunT() {
            @Override
            public void Run(Object o) {
                if (ConfigName.getInstance().IsShowNew) {
                    if (!isFinishing()) {
                        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().IsShowNew) {
                    int k = (int) o;
                    if (!isFinishing()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                cooking.SetMiaoShuTime(k);
                            }
                        });
                    }
                }
            }
        };

    }

    /**
     * 点击事件
     */
    public MyClickListener myClickListener = new MyClickListener() {
        @Override
        public void clickListener(View v, Object data) {
            boolean Status = (boolean) data;
            switch (v.getId()) {
                case R.id.start_goodmake://启动按钮
                    ExecuteTheRecipe.IsPause = false;
                    ExecuteTheRecipe.WritePLC("暂停开关", false, null);
                    if (Status) {
                        onRecordStart();
                    }
                    break;
                case R.id.zanting_goodmake://暂停按钮
                    ExecuteTheRecipe.IsPause = Status;
                    ExecuteTheRecipe.WritePLC("暂停开关", Status, null);
                    if (Status) {
                        onRecordPause();
                    } else {
                        onRecordPauseStart();
                    }
                    break;
            }
        }

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

        }
    };

    private CountDownTimerExt countDownTimer = null;//计时器

    /**
     * 启动
     */
    public void onRecordStart() {
        if (goods != null) {
            cooking.SetReset();
            cooking.SetZanTing(true);
            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();
            ExecuteTheRecipe.IsStart = true;
        }
    }

    /**
     * 停止
     */
    public void onRecordStop() {
        if (goods != null) {
            cooking.SetReset();
            cooking.SetRest1();
            SetProcess(goods.maketime, 0);

            if (countDownTimer != null) {
                countDownTimer.stop();
                countDownTimer = null;
            }
            ExecuteTheRecipe.IsStart = false;
        }
    }

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

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

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

    /**
     * 将毫秒转化为 分钟：秒 的格式    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;
            }
        }
    }
    //endregion
}