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

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bonait.bnframework.HBL.Interface.IRun;
import com.bonait.bnframework.HBL.Interface.IRunT;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
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.constant.MessageName;
import com.bonait.bnframework.common.cookie.CookieBar;
import com.bonait.bnframework.common.cookie.CookieHelper;
import com.bonait.bnframework.common.cookie.OnActionClickListener;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODPROPERTY;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPENAME;
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_ORDER;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
import com.bonait.bnframework.common.db.mode.BPA_SUBORDER;
import com.bonait.bnframework.common.db.res.AlertLogEnum;
import com.bonait.bnframework.common.db.res.ResGoodProperty;
import com.bonait.bnframework.common.db.res.ResGoodsMake;
import com.bonait.bnframework.common.db.res.ResGoodsRecipe;
import com.bonait.bnframework.common.db.res.SilosLsjyMode;
import com.bonait.bnframework.common.db.res.UserLogEnum;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.helper.WrapContentLinearLayoutManager;
import com.bonait.bnframework.common.linktab.LinkMode;
import com.bonait.bnframework.common.linktab.TopItemDecoration;
import com.bonait.bnframework.common.linktab.good.GoodLeftAdapter;
import com.bonait.bnframework.common.linktab.good.GoodRightAdapter;
import com.bonait.bnframework.common.linktab.makegood.MakeGoodLeftAdapter;
import com.bonait.bnframework.common.linktab.makegood.MakeGoodRightAdapter;
import com.bonait.bnframework.common.message.MessageLooper;
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.adapter.loadinggood_adapter;
import com.bonait.bnframework.modules.home.adapter.wl_adapter;
import com.bonait.bnframework.modules.home.fragment.mode.add_makegood_control;
import com.bonait.bnframework.modules.home.fragment.mode.add_manguan_control;
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_control;
import com.bumptech.glide.Glide;
import com.litao.slider.NiftySlider;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

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

public class MakeGoodFragment extends BaseFragment {

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;//顶部标题

    /**
     * 左边分类
     */
    @BindView(R.id.rv_left)
    RecyclerView rv_left;

    /**
     * 右边商品
     */
    @BindView(R.id.rv_right)
    RecyclerView rv_right;

    /**
     * 商品类型
     */
    ArrayList<BPA_GOODSTYPE> goodstypes = new ArrayList<>();

    /**
     * 商品制作列表
     */
    @BindView(R.id.datatab_paiduishangping)
    RecyclerView datatab_paiduishangping;

    /**
     * 增加配方
     */
    @BindView(R.id.add_makegood)
    add_makegood_control add_makegood;

    @BindView(R.id.add_manguan)
    add_manguan_control add_manguan;

    /**
     * 当前温度
     */
    @BindView(R.id.wendu1)
    TextView wendu1;
    //    @BindView(R.id.pf_ms)
//    TextView pf_ms;
    @BindView(R.id.plc_status)
    TextView plc_status;
    @BindView(R.id.dianzichen)
    TextView dianzichen;
    @BindView(R.id.loadgoodliebiao)
    RelativeLayout loadgoodliebiao;

    private Context context;

    public MakeGoodFragment() {
    }

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

    public Activity activity;

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

    public List<LinkMode> Fdata = new ArrayList<>();

    /**
     * 初始化数据
     */
    public void Initdata() {
        if (isAdded()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //刷新商品属性
                                DataBus.getInstance().GetMainGoodProperty();
                                //1.商品类型
                                goodstypes = QueryDB.GetGoodsTypeALL();

                                Fdata.clear();

                                int i = 0;
                                for (BPA_GOODSTYPE item : goodstypes) {
                                    ArrayList<BPA_GOODS> goodsm = QueryDB.GetGoodsTypeId(item.id);
                                    Fdata.add(new LinkMode(item, Arrays.asList(goodsm.toArray()), i == 0 ? true : false));
                                    i++;
                                }

                                LinearLayoutManager manager = (LinearLayoutManager) rv_right.getLayoutManager();
                                MakeGoodLeftAdapter leftAdapter = new MakeGoodLeftAdapter(R.layout.item_left_makegood, Fdata, getResources(), manager);
                                MakeGoodRightAdapter rightAdapter = new MakeGoodRightAdapter(R.layout.item_right_lc, Fdata, getResources());
                                rv_left.setAdapter(leftAdapter);
                                rv_right.setAdapter(rightAdapter);


                                //添加分组悬浮效果
                                List<String> typeListener = new ArrayList<>();
                                for (LinkMode item : Fdata) {
                                    typeListener.add(((BPA_GOODSTYPE) item.type).name);
                                }

                                if (rv_right.getItemDecorationCount() > 0) {
                                    rv_right.removeItemDecorationAt(0);
                                }
                                TopItemDecoration top = new TopItemDecoration(context, typeListener);
                                rv_right.addItemDecoration(top);

                                //左侧联动
                                rv_right.addOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        int firstItemPosition = manager.findFirstVisibleItemPosition();
                                        if (firstItemPosition != -1 && dy != 0) {
                                            rv_left.smoothScrollToPosition(firstItemPosition);
                                            leftAdapter.setChoose(firstItemPosition);
                                        }
                                    }
                                });

                                LoadingGood();
                            }
                        });

                    } catch (Exception e) {

                    }
                }
            }).start();
        }
    }

    /**
     * 加载商品
     */
    public void LoadingGood() {
//        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
//        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        datatab_paiduishangping.setLayoutManager(layoutManager);
        datatab_paiduishangping.setLayoutManager(new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false));

        DataBus.getInstance().loadinggoodAdapter = new loadinggood_adapter(context, myClickListener, getActivity());
        datatab_paiduishangping.setAdapter(DataBus.getInstance().loadinggoodAdapter);
    }


    /**
     * 点击商品 开始制作
     */
    public MyClickListener myClickListener = new MyClickListener() {
        @Override
        public void clickListener(View v, Object data) {
            ResGoodsMake makegood = (ResGoodsMake) data;
            if (!ConfigName.getInstance().PlcIsConnect) {
                ToastUtils.warning("设备已离线,请检查设备...");
                return;
            }

            if (DataBus.getInstance().ZDQX_IsStart) {
                ToastUtils.warning("自动清洗中,请等待清洗完成！");
                return;
            }

            if (ExecuteTheRecipe.IsMakeGood) {
                ToastUtils.warning("请耐心等待上一商品制作完成...");
                return;
            }

            if (makegood.subOrder.status == 1) {
                ToastUtils.warning("商品:" + makegood.good.name + ",已在制作中...");
                return;
            }

            if (makegood.subOrder.status == 2) {
                ToastUtils.warning("商品:" + makegood.good.name + ",已制作完成...");
                return;
            }

            if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机")) {
                if (!ExecuteTheRecipe.IsCup) {
                    ToastUtils.warning("出料口没有检测到器皿！");
                    return;
                }
            }

            String title = "温馨提示！";
            String message = "客官确定要开始制作【" + makegood.good.name + "】吗？";
            QMUIDialog dialog = AlertDialogUtils.showDialog111(context, title, message, new QMUIDialogAction.ActionListener() {
                @Override
                public void onClick(QMUIDialog dialog, int index) {
                    make(makegood);
                    dialog.dismiss();
                }
            });

            if (ConfigName.getInstance().versionSelectionEnum.equals("配料吧台")) {
                ExecuteTheRecipe.OnIngredientButtonPressedNotify = new IRun() {
                    @Override
                    public void Run() {
                        make(makegood);
                        dialog.dismiss();
                    }
                };
            }
            dialog.show();
        }

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

        }
    };

    public void make(ResGoodsMake makegood) {
        //判断温度是否到达
        if (!ConfigName.getInstance().versionSelectionEnum.equals("配料吧台")) {
            if (makegood.Gt1) {
                if (ExecuteTheRecipe.SugarTempLeft < ExecuteTheRecipe.SugarTempLeft_SZ) {
                    ToastUtils.warning("果糖左仓温度未达到设置值,不允许出料...");
                    return;
                }
            }
            if (makegood.Gt2) {
                if (ExecuteTheRecipe.SugarTempRight < ExecuteTheRecipe.SugarTempRight_SZ) {
                    ToastUtils.warning("果糖右仓温度未达到设置值,不允许出料...");
                    return;
                }
            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                //设置清洗模式
                ExecuteTheRecipe.WritePLC("清洗模式", false, null);
                ExecuteTheRecipe.WritePLC("砝码校准模式", false, null);
                ExecuteTheRecipe.WritePLC("手自切换", true, null);
            }
        }).start();
        ExecuteTheRecipe.Execute(makegood);
        ToastUtils.warning("商品:" + makegood.good.name + ",开始制作");
    }

    /**
     * 初始化TopBar
     */
    private void initTopBar() {

        mTopBar.setTitle("智慧菠萝点餐系统" + ConfigName.getInstance().Version);

        mTopBar.addLeftImageButton(R.mipmap.silos1, 1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add_manguan.SetData();
                add_manguan.setVisibility(View.VISIBLE);
            }
        });

        //打开
        MessageManager.getInstance().registerMessageReceiver(getActivity(), MessageName.ClickMakeGoodNew, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    BPA_GOODS goods = (BPA_GOODS) msg;

                    add_makegood.SetData(goods);
                    add_makegood.setVisibility(View.VISIBLE);
                }
            }
        });
        add_manguan.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {

            }

            @Override
            public void clickListenerNew(View v, int k, Object data) {
                add_manguan.setVisibility(View.GONE);
            }
        };
        add_makegood.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
            }

            @Override
            public void clickListenerNew(View v, int k, Object data) {
                if (k == 0) {
                    add_makegood.setVisibility(View.GONE);
                } else {
                    add_makegood.setVisibility(View.GONE);
                }
            }
        };
    }

    @OnClick({R.id.good_gengxin, R.id.cheng_clear, R.id.loadgood})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.good_gengxin://刷新
                Initdata();
                break;
            case R.id.cheng_clear://称重清零
                ExecuteTheRecipe.WritePLC("重量清零", true, new IWriteCallBack() {
                    @Override
                    public void onSuccess() {
                        ToastUtils.info("清零成功！");
                    }

                    @Override
                    public void onFailure(String ErrorMsg) {
                        ToastUtils.error("清零失败！");
                    }
                });
                break;
            case R.id.loadgood://加载数据
                if (loadgoodliebiao.getVisibility() == View.VISIBLE) {
                    loadgoodliebiao.setVisibility(View.GONE);
                } else {
                    loadgoodliebiao.setVisibility(View.VISIBLE);
                }
                break;

        }
    }


    String message = "";
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    plc_status.setText(ConfigName.getInstance().PlcIsConnect ? "正常" : "异常");
                    plc_status.setTextColor(ConfigName.getInstance().PlcIsConnect ? Color.parseColor("#4CAF50") : Color.parseColor("#D32F2F"));
                    wendu1.setText(ExecuteTheRecipe.WaterTemp + "°C");
                    dianzichen.setText(String.valueOf((int) ExecuteTheRecipe.OutletWeigh / 10.0) + " g");
                    break;
                case 1:
                    ToastUtils.warning(message);
                    break;
                case 2:
                    ToastUtils.info(message);
                    break;
            }

        }
    };

    int time=0;
    /**
     * 实时显示线程
     */
    public void Run() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        mHandler.sendEmptyMessage(0);
                        if(time>=60) //12秒执行一次
                        {
                            ArrayList<lcMode> lcModes = DataBus.getInstance().ResGetLc();
                            String title="";
                            for (lcMode item:lcModes)
                            {
                                //lcMode.warningValue >= lcMode.silosmargin
                                //总量大于0 绑定了物料 告警值设置了 告警大于余量 告警
                                if(item.siloszl>0 && !item.materialId.isEmpty() && item.warningValue>0 && item.warningValue >= item.silosmargin)
                                {
                                    title+="料仓"+item.num+"-"+item.materialName+"|";
                                }
                            }

                            if(!title.isEmpty())
                            {
                                String finalTitle = title;
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //0.6 --- 0.9
                                        CookieHelper.Show(activity, finalTitle +"-余量提示","料仓余量不足,请及时补料！若程序预警错误,请及时手动补充原料后,在料仓界面点击《补充原料》");
                                    }
                                });
                            }

                            time=0;
                        }
                        Thread.sleep(200);
                        time++;
                    } catch (Exception ex) {
                        ToastUtils.error("异常信息:" + ex.getMessage());
                    }
                }
            }
        }).start();

        //接收扫码信息
        ExecuteTheRecipe.OnScanTheCodeInformationT = new IRunT<String>() {
            @Override
            public void Run(String msg) {

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if ((msg != null) && (((String) msg).length() > 2) && ((String) msg).contains("|")) {
                            //拿到扫码数据
                            //例如 ORD001|P0003|A001,M002,T001|2
                            // OR001|A001|2,22|1

                            String[] res = ((String) msg).split("[|]");
                            if (res.length >= 4) {
                                String orderid = res[0];//ORD001
                                String goodid = res[1];//P0003  商品id
                                String ggid = res[2];//A001,M002,T001 配方ids

                                String ggids = "";//规格id集合
                                String names = "";

                                if (QueryDB.GetOrderthirdPartyIDIs(orderid)) {
                                    message = "已有订单,重复扫码!";
                                    mHandler.sendEmptyMessage(1);
                                    return;
                                }
                                int num = 1;
                                try {
                                    num = Integer.parseInt(res[3]);
                                    for (String item : ggid.split("[,]")) {
                                        for (ResGoodProperty k : DataBus.getInstance().bpa_goodproperties) {
                                            if (k.child != null && k.child.size() > 0) {
                                                for (ResGoodProperty chd : k.child) {
                                                    if (chd.foreignKeyRe != null && !chd.foreignKeyRe.isEmpty() && chd.foreignKeyRe.equals(item)) {
                                                        ggids += chd.id + ",";
                                                        names += "/" + chd.name;
                                                    }
                                                }
                                            }

                                        }
                                    }

                                    if (!ggids.isEmpty()) {
                                        ggids = ggids.substring(0, ggids.length() - 1);
                                    }
                                } catch (Exception ex) {
                                }

                                BPA_GOODS good = QueryDB.GetGoodsforeignKeyId(goodid);
                                if (good == null) {
                                    message = "没有查询到该商品!";
                                    mHandler.sendEmptyMessage(1);
                                } else {
                                    BPA_GOODSRECIPENAME goodsrecipename = QueryDB.GetGoodsRecipeNameDesignId(ggids, good.id);
                                    if (goodsrecipename != null) {
                                        BPA_ORDER order = new BPA_ORDER();
                                        order.thirdPartyID = orderid;
                                        order.status = 0;
                                        order.deviceID = ConfigName.getInstance().DeviceId;
                                        order.userID = ConfigName.getInstance().user.userID;
                                        QueryDB.AddOrder(order);

                                        for (int mm = 0; mm < num; mm++) {
                                            BPA_SUBORDER suborder = new BPA_SUBORDER();
                                            suborder.deviceID = ConfigName.getInstance().DeviceId;
                                            suborder.userID = ConfigName.getInstance().user.userID;
                                            suborder.orderID = order.id;
                                            suborder.goodsID = good.id;
                                            suborder.recipeID = goodsrecipename.id;
                                            suborder.number = 1;
                                            suborder.status = 0;
                                            suborder.exp = names;
                                            QueryDB.AddSubOrder(suborder);
                                            DataBus.getInstance().AddGoodsMake(suborder);
                                        }
                                        message = "加入订单队列成功!";
                                        mHandler.sendEmptyMessage(2);
                                    } else {
                                        message = "没有查询到该商品配方信息!";
                                        mHandler.sendEmptyMessage(1);
                                    }
                                }

                            } else {
                                message = "没有查询到该商品!";
                                mHandler.sendEmptyMessage(1);
                            }
                        } else {
                            message = "服务器异常，请稍后重试!";
                            mHandler.sendEmptyMessage(1);
                        }
                    }
                });

            }
        };


//        ThreadManager.Get().StartLong("商品制作线程1111111", true, new IThread() {
//            @Override
//            public void Run() throws InterruptedException {
//                try {
//                    if(DataBus.getInstance().GoodsMake.size()>0)
//                    {
//                        ResGoodsMake mmmmm= DataBus.getInstance().GoodsMake.get(0);
//                        ArrayList<ResGoodsRecipe> recipes= mmmmm.recipes;
//
//                        //region 根据物料配方排序Sort步骤分组
//                        LinkedHashMap<Integer, List<ResGoodsRecipe>> rgrs = new LinkedHashMap<>();
//                        for (int i = 0; i < recipes.size(); i++) {
//                            if (!rgrs.containsKey(recipes.get(i).sort))
//                                rgrs.put(recipes.get(i).sort, new ArrayList<>());
//                            rgrs.get(recipes.get(i).sort).add(recipes.get(i));
//                        }
//                        //endregion
//                        int count = 0;
//                        for (LinkedHashMap.Entry<Integer, List<ResGoodsRecipe>> entry : rgrs.entrySet()) {
//                            final Integer key = entry.getKey();
//                            List<ResGoodsRecipe> goodsRecipes = entry.getValue();
//                            //region 当前一次性下发物料集合
//                            String RecipesNames = "";
//                            for (ResGoodsRecipe item : goodsRecipes) {
//                                RecipesNames += item.materialName + ",";
//                            }
//                            count = 2;
//                            DataBus.getInstance().UpdateGoodsMake(mmmmm.subOrder.id, "步骤【" + key + "】准备下发物料:" + RecipesNames, count, key, false);
//                            Thread.sleep(1000);
//                        }
//
//                        DataBus.getInstance().DeleteGoodsMake(mmmmm.subOrder.id);
//                    }
//                } catch (Exception ex) {
//                    ToastUtils.error("异常信息:" + ex.getMessage());
//                }
//                Thread.sleep(500);
//            }
//            @Override
//            public void RunComplete() throws InterruptedException {
//
//            }
//        });
    }


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

        rv_right.setAdapter(null);
        Glide.get(getContext()).clearMemory();
    }

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