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

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

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
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.BaseFragment;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.QueryDB;
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_SILOS;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.model.mode.MouthFacingEnum;
import com.bonait.bnframework.common.model.mode.SpeedEnum;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.mode.imagebuttom3;
import com.bonait.bnframework.modules.home.fragment.mode.newhuoli_control;
import com.orhanobut.logger.Logger;

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

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

public class HomeFragmentSBKZ extends BaseFragment {

    //region 变量
    @BindView(R.id.touliao_k)
    LinearLayout touliao_k;

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

    @BindView(R.id.plcstatus1)
    ImageView plcstatus1;

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

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

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


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

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

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

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

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

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


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

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

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

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

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

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


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

    @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.chuchan)
    imagebuttom3 chuchan;

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

    @BindView(R.id.device_image)
    ImageView device_image;
    //endregion

    //region 界面
    private Context context;
    public Activity activity = null;

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = getContext();
        activity = getActivity();
        initTopBar();
        initData();
        SxUIThread();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("第一页销毁");
    }

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

    //region 私立函数

    /**
     * 初始化TopBar
     */
    private void initTopBar() {
        fanchaoshudu.mListener = myClickListener;
        fanchaoshudu_k.mListener = myClickListener;
        fanchaoshudu_z.mListener = myClickListener;
        fanchaoshudu_m.mListener = myClickListener;
        fanchaoshudu_t.mListener = myClickListener;

        guokoucaoxiang.mListener = myClickListener;
        guokoucaoxiang_cc.mListener = myClickListener;
        guokoucaoxiang_cl.mListener = myClickListener;
        guokoucaoxiang_dc.mListener = myClickListener;
        guokoucaoxiang_qx.mListener = myClickListener;

        touliao1.mListener = myClickListener;
        touliao2.mListener = myClickListener;
        touliao3.mListener = myClickListener;
        touliao4.mListener = myClickListener;

        chushui.SetOnTounch(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) {
                        SetIDTouch(R.id.chushui, true);
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        SetIDTouch(R.id.chushui, false);
                    }
                } else {
                    ToastUtils.warning("请先控制锅口朝向：抽料位");
                    SetIDTouch(R.id.chushui, false);
                }
                return false;
            }
        });
        xiguoshui.SetOnTounch(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) {
                        SetIDTouch(R.id.xiguoshui, true);
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        SetIDTouch(R.id.xiguoshui, false);
                    }
                } else {
                    ToastUtils.warning("请先控制锅口朝向：清洗位");
                    SetIDTouch(R.id.xiguoshui, false);
                }
                return false;
            }
        });
        yeliao1.SetOnTounch(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) {
                        SetIDTouch(R.id.yeliao1, true);
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        SetIDTouch(R.id.yeliao1, false);
                    }
                } else {
                    ToastUtils.warning("请先控制锅口朝向：抽料位");
                    SetIDTouch(R.id.yeliao1, false);
                }
                return false;
            }
        });
        yeliao2.SetOnTounch(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) {
                        SetIDTouch(R.id.yeliao2, true);
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        SetIDTouch(R.id.yeliao2, false);
                    }
                } else {
                    ToastUtils.warning("请先控制锅口朝向：抽料位");
                    SetIDTouch(R.id.yeliao2, false);
                }
                return false;
            }
        });
        yeliao3.SetOnTounch(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) {
                        SetIDTouch(R.id.yeliao3, true);
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        SetIDTouch(R.id.yeliao3, false);
                    }
                } else {
                    ToastUtils.warning("请先控制锅口朝向：抽料位");
                    SetIDTouch(R.id.yeliao3, false);
                }
                return false;
            }
        });

        huoli.mListener = myClickListener;
        chuchan.mListener = myClickListener;
        DataBus.getInstance().SilosRefresh = new IRun() {
            @Override
            public void Run() {
                RefreshLiquidSilo();
            }
        };
    }

    /**
     * 初始化显示数据
     */
    private void initData() {
        SetStirFrySpeed(SpeedEnum.停, false);
        RefreshLiquidSilo();

        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);
        }
    }

    /**
     * 刷新液料仓
     */
    public void RefreshLiquidSilo() {
        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();
    }

    /**
     * 刷新UI界面
     */
    public void SxUIThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        if (activity != null && isAdded()) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Object val_wd = ExecuteTheRecipe.getListingValue("当前锅底温度");
                                    if (val_wd != null) {
                                        chaoguo_wendu.setText(val_wd + "°C");
                                    } else {
                                        chaoguo_wendu.setText("??°C");
                                    }

                                    plcstatus1.setImageResource(ConfigName.getInstance().PlcIsConnect ? R.mipmap.plc1 : R.mipmap.plc2);
                                }
                            });
                        }
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        ToastUtils.info("异常信息:" + e.getMessage());
                    }
                }
            }
        }).start();
    }

    @OnClick({
            R.id.zidongqingxi,
            R.id.chushihua,
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.chushihua://初始化
                ExecuteTheRecipe.BottomClick("初始化");
                ToastUtils.warning("初始化");
                break;
            case R.id.zidongqingxi://自动清洗
                ExecuteTheRecipe.BottomClick("炒锅清洗");
                ToastUtils.warning("自动清洗");
                break;
        }
    }

    /**
     * 点击事件
     */
    public MyClickListener myClickListener = new MyClickListener() {
        @Override
        public void clickListener(View v, Object data) {
            boolean isclick = false;
            int hl = 0;
            if (v.getId() == R.id.huoli) {
                hl = (int) data;
            } else {
                isclick = (boolean) data;
            }
            switch (v.getId()) {
                case R.id.fanchaoshudu:
                    fanchaoshudu_1.setVisibility(isclick ? View.VISIBLE : View.GONE);
                    break;
                case R.id.fanchaoshudu_k:
                    SetStirFrySpeed(SpeedEnum.快, isclick);
                    break;
                case R.id.fanchaoshudu_z:
                    SetStirFrySpeed(SpeedEnum.中, isclick);
                    break;
                case R.id.fanchaoshudu_m:
                    SetStirFrySpeed(SpeedEnum.慢, isclick);
                    break;
                case R.id.fanchaoshudu_t:
                    SetStirFrySpeed(SpeedEnum.停, isclick);
                    break;
                case R.id.guokoucaoxiang:
                    guokoucaoxiang_1.setVisibility(isclick ? View.VISIBLE : View.GONE);
                    break;
                case R.id.guokoucaoxiang_cc:
                    SetMouthFacing(MouthFacingEnum.炒菜位);
                    break;
                case R.id.guokoucaoxiang_cl:
                    SetMouthFacing(MouthFacingEnum.抽料位);
                    break;
                case R.id.guokoucaoxiang_dc:
                    SetMouthFacing(MouthFacingEnum.倒菜位);
                    break;
                case R.id.guokoucaoxiang_qx:
                    SetMouthFacing(MouthFacingEnum.清洗位);
                    break;
                case R.id.touliao1:
                    MainDish(1);
                    break;
                case R.id.touliao2:
                    MainDish(2);
                    break;
                case R.id.touliao3:
                    MainDish(3);
                    break;
                case R.id.touliao4:
                    MainDish(4);
                    break;
                case R.id.huoli:
                    SetFire(hl);
                    break;
                case R.id.chuchan:
                    GoOutToDinner();
                    break;

            }
        }

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

        }
    };

    /**
     * 设置是否按下
     *
     * @param id
     * @param ismode
     */
    public void SetIDTouch(int id, boolean ismode) {
        switch (id) {
            case R.id.chushui:
                //PumpWater(ismode);
                Pumping(4, ismode);
                Log.e("锅内加水", ismode ? "按下" : "松开");
                break;
            case R.id.xiguoshui:
                PotWashingWater(ismode);
                Log.e("洗锅水枪", ismode ? "按下" : "松开");
                break;
            case R.id.yeliao1:
                Pumping(1, ismode);
                Log.e("液料1号", ismode ? "按下" : "松开");
                break;
            case R.id.yeliao2:
                Pumping(2, ismode);
                Log.e("液料2号", ismode ? "按下" : "松开");
                break;
            case R.id.yeliao3:
                Pumping(3, ismode);
                Log.e("液料3号", ismode ? "按下" : "松开");
                break;
        }
    }
    //endregion

    //region 公共函数

    /**
     * 设置翻炒速度
     * int 60 快 中 慢 停
     *
     * @param
     */
    public void SetStirFrySpeed(SpeedEnum speed, boolean isselectd) {
        int _speed = 0;
        if (isselectd) {
            switch (speed) {
                case 快:
                    _speed = 60;
                    //fanchaoshudu_k.SetStatus(true);
                    fanchaoshudu_z.SetStatus(false);
                    fanchaoshudu_m.SetStatus(false);
                    fanchaoshudu_t.SetStatus(false);
                    fanchaoshudu.setTag("翻炒速度 快-按钮");
                    break;
                case 中:
                    _speed = 40;
                    fanchaoshudu_k.SetStatus(false);
                    //fanchaoshudu_z.SetStatus(true);
                    fanchaoshudu_m.SetStatus(false);
                    fanchaoshudu_t.SetStatus(false);
                    fanchaoshudu.setTag("翻炒速度 中-按钮");
                    break;
                case 慢:
                    _speed = 20;
                    fanchaoshudu_k.SetStatus(false);
                    fanchaoshudu_z.SetStatus(false);
                    //fanchaoshudu_m.SetStatus(true);
                    fanchaoshudu_t.SetStatus(false);
                    fanchaoshudu.setTag("翻炒速度 慢-按钮");
                    break;
                case 停:
                    _speed = 0;
                    fanchaoshudu_k.SetStatus(false);
                    fanchaoshudu_z.SetStatus(false);
                    fanchaoshudu_m.SetStatus(false);
                    //fanchaoshudu_t.SetStatus(true);
                    fanchaoshudu.setTag("翻炒速度 停-按钮");
                    break;
            }
        } else {
            _speed = 0;
            fanchaoshudu_k.SetStatus(false);
            fanchaoshudu_z.SetStatus(false);
            fanchaoshudu_m.SetStatus(false);
            fanchaoshudu_t.SetStatus(true);
            fanchaoshudu.setTag("翻炒速度 停-按钮");
        }
        fanchaoshudu_1.setVisibility(View.GONE);
        fanchaoshudu.Init();

        ToastUtils.warning("设置翻炒速度：" + speed.name());

        int final_speed = _speed;
        ExecuteTheRecipe.WritePLC("搅拌速度", _speed, new IWriteCallBack() {
            @Override
            public void onSuccess() {
                if (final_speed == 0) {
                    ExecuteTheRecipe.WritePLC("搅拌", false, null);
                } else {
                    ExecuteTheRecipe.WritePLC("搅拌", true, null);
                }
            }

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

    /**
     * 设置锅口朝向
     *
     * @param
     */
    public void SetMouthFacing(MouthFacingEnum mouth) {
        switch (mouth) {
            case 炒菜位:
                ExecuteTheRecipe.BottomClick("炒菜位1");
                guokoucaoxiang.setTag("锅口朝向\n 炒菜位-按钮");
                break;
            case 抽料位:
                ExecuteTheRecipe.BottomClick("抽料位");
                guokoucaoxiang.setTag("锅口朝向\n 抽料位-按钮");
                break;
            case 倒菜位:
                ExecuteTheRecipe.BottomClick("倒菜位");
                guokoucaoxiang.setTag("锅口朝向\n 倒菜位-按钮");
                break;
            case 清洗位:
                ExecuteTheRecipe.BottomClick("清洗位");
                guokoucaoxiang.setTag("锅口朝向\n 清洗位-按钮");
                break;
        }
        guokoucaoxiang_1.setVisibility(View.GONE);
        guokoucaoxiang.Init();

        ToastUtils.warning("当前锅口朝向：" + mouth.name());
    }

    /**
     * 抽水
     */
    public void PumpWater(boolean isselectd) {
        ExecuteTheRecipe.WritePLC("炒锅抽水", isselectd, null);
        //ToastUtils.warning("锅内加水：" + (isselectd ? "打开" : "关闭"));
    }

    /**
     * 洗锅水枪
     *
     * @param isselectd
     */
    public void PotWashingWater(boolean isselectd) {
        ExecuteTheRecipe.WritePLC("炒锅放水", isselectd, null);
        //ToastUtils.warning("洗锅水枪：" + (isselectd ? "打开" : "关闭"));
    }

    public boolean isMake = false;

    /**
     * 投主菜品
     *
     * @param num
     */
    public void MainDish(int num) {
//        Object sb = ExecuteTheRecipe.ReadPLC("平移轴在1号位");
//        if (sb != null) {
//            if ((boolean) (sb)) {
//
//            } else {
//                ToastUtils.warning("平移轴未复位!!!");
//            }
//        } else {
//            ToastUtils.warning("PLC未连接!!!");
//        }
        if (isMake == false) {
            isMake = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    BPA_GOODSRECIPE data1 = Get位置("高速", "炒菜位1");
                    ExecuteTheRecipe.ExecuteOperationSteps(data1.processname, data1.processvalue);

                    BPA_GOODSRECIPE data = Get主料(num);
                    ExecuteTheRecipe.ExecuteOperationSteps(data.processname, data.processvalue);
                    ToastUtils.warning("主料：" + num + "号仓投放");
                    isMake = false;
                }
            }).start();
        }else
        {
            ToastUtils.warning("请耐心等待上一次投料结束!!!");
        }
    }

    /**
     * 抽料
     *
     * @param num
     */
    public void Pumping(int num, boolean isselectd) {
        ExecuteTheRecipe.WritePLC("料仓" + (num) + "手动开关", isselectd, null);
        //ToastUtils.warning("料仓：" + num + "," + (isselectd ? "打开" : "关闭"));
    }

    /**
     * 设置火力
     *
     * @param data
     */
    public void SetFire(int data) {
        ExecuteTheRecipe.Write_PLC_HuoLI((int) data);
        ToastUtils.warning("设置火力：" + data + "档");
    }

    /**
     * 出餐
     *
     * @param
     */
    public void GoOutToDinner() {
        ExecuteTheRecipe.BottomClick("出菜");
        ToastUtils.warning("出餐");
    }


    /**
     * 获取主料
     *
     * @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 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;
    }
    //endregion
}