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


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

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

import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseFragment;
import com.bonait.bnframework.common.constant.DataBus;
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.ByteHelper;
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.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyLayoutManager;
import com.bonait.bnframework.modules.home.adapter.lc_adapter;
import com.bonait.bnframework.modules.home.fragment.from.CpxzActivity;
import com.bonait.bnframework.modules.home.fragment.mode.LocationStatus;
import com.bonait.bnframework.modules.home.fragment.mode.MyStatus;
import com.bonait.bnframework.modules.home.fragment.mode.huoli_control;
import com.capton.colorfulprogressbar.ColorfulProgressbar;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.QMUITopBar;
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 java.util.LinkedHashMap;
import java.util.List;

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

/**
 * A simple {@link Fragment} subclass.
 */
public class Home1Fragment extends BaseFragment {
    @BindView(R.id.topbar)
    QMUITopBar mTopBar;//顶部标题
    @BindView(R.id.xzcp)
    RelativeLayout xzcp;//选择菜谱
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;//料仓列表
    @BindView(R.id.caipumingcheng)
    QMUILinkTextView caipumingcheng;//菜谱名称
    @BindView(R.id.shengyushijian)
    QMUILinkTextView shengyushijian;//剩余时间
    @BindView(R.id.jingdu)
    ColorfulProgressbar jingdu;//进度条
    @BindView(R.id.huoli)
    huoli_control huoli;//火力控件
    @BindView(R.id.startbutton)
    ImageView startbutton;//启动安
    public boolean Status = false;
    /**
     * 当前制作商品信息
     */
    BPA_GOODS good = null;
    private Context context;

    public Home1Fragment() {
    }

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

        return root;
    }

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

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

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

    }

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

            DataBus.getInstance().lcadapter = new lc_adapter(getContext());
            recyclerView.setAdapter(DataBus.getInstance().lcadapter);
        } catch (Exception e) {
            ToastUtils.info("异常信息:" + e.getMessage());
        }
    }

    /**
     * 火力按钮点击
     */
    public void HuoLiClicked() {
        huoli.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
                ToastUtils.info("火力按钮点击,当前级别：" + data);
            }

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

            }
        };

        DataBus.getInstance().mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
                good = (BPA_GOODS) data;
                SetBottonStatus(false);
                caipumingcheng.setText(good.name);
                SetProcesssUI(good.maketime, 0);
            }

            @Override
            public void clickListenerNew(View v, int k, Object data) {
                ToastUtils.info("刷新界面");
                initData();
            }
        };
    }

    /**
     * 商品制作线程
     */
    public void MakeThread()
    {
        ThreadManager.Get().StartLong("商品制作线程-2023", true, new IThread() {
            @Override
            public void Run() throws InterruptedException {
                if(Status && good!=null)
                {
                    try
                    {
                        //获取工艺
                        ArrayList<BPA_GOODSRECIPE> goodsrecipes = QueryDB.GetGoodsSrecipeID(good.id);
                        for(BPA_GOODSRECIPE item:goodsrecipes)
                        {
                            ExecuteTheRecipe.Execute(item);
                        }
                    }catch (Exception ex)
                    {
                        ToastUtils.error("异常信息:" + ex.getMessage());
                    }finally {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                SetBottonStatus(false);
                            }
                        });
                    }
                }
                Thread.sleep(1000);
            }
            @Override
            public void RunComplete() throws InterruptedException {
            }
        });
    }

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

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

    private CountDownTimer countDownTimer = null;//计时器

    /**
     * 计时器
     * @param alltime
     * @param status
     */
    public void TimerCount(int alltime, boolean status) {
        if(status)
        {
            if(countDownTimer==null)
            {
                countDownTimer = new CountDownTimer(alltime * 1000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        int overtime = (int) ((millisUntilFinished) / 1000);//剩余时间
                        SetProcesssUI(alltime,alltime-overtime);
                    }
                    @Override
                    public void onFinish() {
                        SetProcesssUI(alltime,alltime);//进度条100%
                    }
                };
            }
            countDownTimer.start();
        }else
        {
            if(countDownTimer!=null)
            {
                countDownTimer.cancel();
                countDownTimer=null;
            }
        }
    }

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

                            dialog.dismiss();
                        }
                    });
                }
                break;
            case R.id.qdjb:
                ExecuteTheRecipe.Write_PLC_Clean(MyStatus.Start);
                break;
            case R.id.ztjb:
                ExecuteTheRecipe.Write_PLC_Clean(MyStatus.Paused);
                break;
            case R.id.tzjb:
                ExecuteTheRecipe.Write_PLC_Clean(MyStatus.Stop);
                break;
            case R.id.ccw:
                ExecuteTheRecipe.Write_PLC_Location(LocationStatus.InLocation);
                break;
            case R.id.chucw:
                ExecuteTheRecipe.Write_PLC_Location(LocationStatus.OutLocation);
                break;
            case R.id.dsw:
                ExecuteTheRecipe.Write_PLC_Location(LocationStatus.PourWaterLocation);
                break;
            case R.id.yaoqian:
                ExecuteTheRecipe.Write_PLC_YaoQian(MyStatus.Start);
                break;
            case R.id.tingyao:
                ExecuteTheRecipe.Write_PLC_YaoQian(MyStatus.Stop);
                break;
        }
    }

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

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

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