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.appcompat.widget.SearchView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;
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.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.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.helper.SoftKeyBoardListener;
import com.bonait.bnframework.common.linktab.LinkMode;
import com.bonait.bnframework.common.linktab.TopItemDecoration;
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.model.mode.CloudGood;
import com.bonait.bnframework.common.model.mode.GoodsTypeInfo;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.good_adapter;
import com.bonait.bnframework.modules.home.fragment.from.CookingActivity;
import com.bonait.bnframework.modules.home.fragment.from.CookingSimulatedActivity;
import com.bonait.bnframework.modules.home.fragment.from.DiyUpdate1Activity;
import com.bonait.bnframework.modules.home.fragment.from.DiyUpdateActivity;
import com.bonait.bnframework.modules.home.fragment.mode.SectionHeader;
import com.bonait.bnframework.modules.home.fragment.mode.SectionItem;
import com.bonait.bnframework.modules.home.fragment.mode.add_qupenren;
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 com.qmuiteam.qmui.widget.section.QMUISection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

public class HomeFragmentPR extends BaseFragment {
    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;//顶部标题

//    @BindView(R.id.recycler_view)
//    RecyclerView recycler_view;//商品

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

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

    @BindView(R.id.quanbucaipu)
    TextView quanbucaipu;//全部菜谱

    @BindView(R.id.yunduancaipu)
    TextView yunduancaipu;//云端菜谱

    @BindView(R.id.search_view)
    SearchView search_view;//查询框

    @BindView(R.id.qupenren)
    add_qupenren qupenren;//确认烹饪弹窗

    /**
     * 选中行
     */
    public int SelectIndex = 1;

    private Context context;

    public Activity activity = null;

    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home_pr, 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();
        SelectTab(1);

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.obj.toString() == "MSG_REFRESH") {
                initData();
            }
        }
    };

    /**
     * 初始化TopBar
     */
    private void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.topbj1));
        mTopBar.setTitle("菜谱");
        mTopBar.addRightTextButton("设备状态：" + (ConfigName.getInstance().PlcIsConnect ? "已连接" : "未连接"), R.id.status_image);
        SoftKeyBoardListener.setListener(activity, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                search_view.clearFocus();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTopBar.removeAllRightViews();
                                mTopBar.addRightTextButton("设备状态：" + (ConfigName.getInstance().PlcIsConnect ? "已连接" : "未连接"), R.id.status_image);
                            }
                        });
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }).start();
        /**
         * 刷新菜品
         */
        MessageManager.getInstance().registerMessageReceiver(activity, MessageName.GetOrganize, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null && isAdded()) {
                    ConfigData.getInstance().GetGevGood(context, mHandler);
                }
            }
        });
        /**
         * 刷新菜品
         */
        MessageManager.getInstance().registerMessageReceiver(activity, MessageName.ScGood, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null && isAdded()) {
                    String str = (String) msg;
                    if (str.equals("Good")) {
                        initData();
                        if (qupenren.getVisibility() == View.VISIBLE) {
                            qupenren.RefreshData();
                        }
                    } else {
                        ConfigData.getInstance().GetGevGood(context, mHandler);
                    }
                }
            }
        });

        search_view.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                initData();
                return false;
            }
        });
    }


    /**
     * 初始化显示数据
     */
    private void initData() {

        ArrayList<BPA_GOODS> good = new ArrayList<>();
        List<CloudGood> cloudGoods = new ArrayList<>();

        String name = search_view.getQuery().toString();
        if (name.isEmpty()) {
            good = QueryDB.GetGoodsALL();
            cloudGoods=ConfigName.getInstance().cloudGoods;
        } else {
            good = QueryDB.GetGoodsLike(name);
            for (CloudGood kk:ConfigName.getInstance().cloudGoods)
            {
                if(kk.goods_Name.contains(name))
                {
                    cloudGoods.add(kk);
                }
            }
        }

        List<String> typeIds = new ArrayList<>();
        List<GoodsTypeInfo> type = new ArrayList<>();
        if (ConfigName.getInstance().cloudData != null && ConfigName.getInstance().cloudData.goodsTypeInfo != null) {
            for (GoodsTypeInfo mm : ConfigName.getInstance().cloudData.goodsTypeInfo) {
                type.add(mm);
                typeIds.add(mm.id);
            }
        }
        GoodsTypeInfo info = new GoodsTypeInfo();
        info.id = "其他";
        info.goodsType_Name = "其他";
        type.add(info);

        List<String> Bendi_id = new ArrayList<>();
        List<LinkMode> Bdata = new ArrayList<>();
        List<LinkMode> Ydata = new ArrayList<>();

        int i = 0;
        for (GoodsTypeInfo itemtype : type) {
            ArrayList<SectionItem> contents = new ArrayList<>();
            for (BPA_GOODS item : good) {
                if (item.userID != null && !item.userID.isEmpty() && item.userID.equals(itemtype.id)) {
                    if (item.url == null || item.url.isEmpty()) {
                        item.url = "未知";
                    }
                    contents.add(new SectionItem(item.name, String.valueOf(item.maketime), item.id, item.url, item.issc == 1, false, true));
                    Bendi_id.add(item.id);
                } else {
                    if (itemtype.id.equals("其他") && !typeIds.contains(item.userID == null ? item.userID = "" : item.userID)) {
                        if (item.url == null || item.url.isEmpty()) {
                            item.url = "未知";
                        }
                        contents.add(new SectionItem(item.name, String.valueOf(item.maketime), item.id, item.url, item.issc == 1, false, true));
                        Bendi_id.add(item.id);
                    }
                }
            }
            if (contents.size() > 0) {
                Bdata.add(new LinkMode(itemtype, Arrays.asList(contents.toArray()), i == 0 ? true : false));
                i++;
            }
        }

        i = 0;
        for (GoodsTypeInfo itemtype : type) {
            ArrayList<SectionItem> contents = new ArrayList<>();
            for (CloudGood item : cloudGoods) {
                if (item.goods_TypeID.equals(itemtype.id)) {
                    contents.add(new SectionItem(item.goods_Name, "180", item.id, item.goods_ImgUrl, false, true, Bendi_id.contains(item.id) ? true : false));
                } else {
                    if (itemtype.id.equals("其他") && !typeIds.contains(item.goods_TypeID)) {
                        contents.add(new SectionItem(item.goods_Name, "180", item.id, item.goods_ImgUrl, false, true, Bendi_id.contains(item.id) ? true : false));
                        Bendi_id.add(item.id);
                    }
                }
            }
            if (contents.size() > 0) {
                Ydata.add(new LinkMode(itemtype, Arrays.asList(contents.toArray()), i == 0 ? true : false));
                i++;
            }
        }
        MakeGoodLeftAdapter leftAdapter = null;
        MakeGoodRightAdapter rightAdapter = null;
        LinearLayoutManager manager = (LinearLayoutManager) rv_right.getLayoutManager();
        if (SelectIndex == 1) {
            leftAdapter = new MakeGoodLeftAdapter(R.layout.item_left_makegood, Bdata, getResources(), manager);
            rightAdapter = new MakeGoodRightAdapter(R.layout.item_right_lc, Bdata, getResources(), myClickListener, context);
            rv_left.setAdapter(leftAdapter);
            rv_right.setAdapter(rightAdapter);

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

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

        } else {
            leftAdapter = new MakeGoodLeftAdapter(R.layout.item_left_makegood, Ydata, getResources(), manager);
            rightAdapter = new MakeGoodRightAdapter(R.layout.item_right_lc, Ydata, getResources(), myClickListener, context);
            rv_left.setAdapter(leftAdapter);
            rv_right.setAdapter(rightAdapter);

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

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

        //左侧联动
        MakeGoodLeftAdapter finalLeftAdapter = leftAdapter;
        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.findLastVisibleItemPosition();
                if (firstItemPosition != -1 && dy != 0) {
                    rv_left.smoothScrollToPosition(firstItemPosition);
                    finalLeftAdapter.setChoose(firstItemPosition);
                }
            }
        });
//        StaggeredGridLayoutManager layout = new StaggeredGridLayoutManager
//                (3, StaggeredGridLayoutManager.VERTICAL);
//        recycler_view.setLayoutManager(layout);
//
//        ArrayList<BPA_GOODS> good = new ArrayList<>();
//        String name = search_view.getQuery().toString();
//        if (name.isEmpty()) {
//            good = QueryDB.GetGoodsALL();
//        } else {
//            good = QueryDB.GetGoodsLike(name);
//        }
//
//        List<String> Bendi_id = new ArrayList<>();
//        ArrayList<SectionItem> contents_bdcp = new ArrayList<>();
//        ArrayList<SectionItem> contents_ydcp = new ArrayList<>();
//        for (BPA_GOODS item : good) {
//            if (item.url == null) {
//                item.url = "未知";
//            }
//            contents_bdcp.add(new SectionItem(item.name, String.valueOf(item.maketime), item.id, item.url, item.issc == 1, false, true));
//            Bendi_id.add(item.id);
//        }
//
//        for (CloudGood item : ConfigName.getInstance().cloudGoods) {
//            contents_ydcp.add(new SectionItem(item.goods_Name, "180", item.id, item.goods_ImgUrl, false, true, Bendi_id.contains(item.id) ? true : false));
//        }
//
//        if (SelectIndex == 1) {
//            good_adapter adapter = new good_adapter(context, contents_bdcp, myClickListener);
//            recycler_view.setAdapter(adapter);
//        } else {
//            good_adapter adapter = new good_adapter(context, contents_ydcp, myClickListener);
//            recycler_view.setAdapter(adapter);
//        }
    }

    public MyClickListener myClickListener = new MyClickListener() {
        @Override
        public void clickListener(View v, Object data) {

        }

        @Override
        public void clickListenerNew(View v, int k, Object data) {
            SectionItem item = (SectionItem) data;
            String goodid = item.getAccount();//商品id
            switch (k) {

                case 1:
                    QueryDB.DeleteGoodsid(goodid);
                    QueryDB.DeleteGoodsSrecipeList(goodid);
                    initData();
                    break;
                case 2:
                    initData();
                    break;
                case 3:
                    Intent intent = new Intent(getContext(), DiyUpdate1Activity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("id", goodid);
                    startActivity(intent);
                    qupenren.setVisibility(View.GONE);
                    break;
                case 99:
                    Intent intent1 = new Intent(getContext(), CookingSimulatedActivity.class);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent1.putExtra("id", goodid);
                    startActivity(intent1);
                    qupenren.setVisibility(View.GONE);
                    break;
                case 4: //打开查看窗体
                    qupenren.SetData(item, myClickListener);
                    qupenren.setVisibility(View.VISIBLE);
                    break;
                case 5: //打开制作窗体
                    //判断是否正在制作
                    if (ExecuteTheRecipe.IsStart) {
                        ToastUtils.warning("请耐心等待商品制作结束!!!");
                    } else {
                        MessageManager.getInstance().sendMessage(MessageName.OpenMakeGoodFrom, goodid);
                        qupenren.setVisibility(View.GONE);
                    }
                    break;
                case 0://关闭窗体
                    qupenren.setVisibility(View.GONE);
                    break;
            }
        }
    };


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.quanbucaipu, R.id.yunduancaipu
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.quanbucaipu:
                SelectTab(1);
                break;
            case R.id.yunduancaipu:
                SelectTab(2);
                break;
        }
    }

    /**
     * 选中tab行
     *
     * @param index
     */
    public void SelectTab(int index) {
        SelectIndex = index;
        switch (index) {
            case 1:
                quanbucaipu.setTextColor(Color.parseColor("#BEAA6A"));
                yunduancaipu.setTextColor(Color.parseColor("#797373"));
                initData();
                break;
            case 2:
                quanbucaipu.setTextColor(Color.parseColor("#797373"));
                yunduancaipu.setTextColor(Color.parseColor("#BEAA6A"));
                initData();
                break;
        }
    }

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

}