package com.gingersoft.supply_chain.mvp.ui.fragment.food;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerBuyIngredientsComponent;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.contract.BuyIngredientsContract;
import com.gingersoft.supply_chain.mvp.presenter.BuyIngredientsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.BuyIngredientsAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.FirstLevelCategoryAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.SecondCategoryAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.CenterLayoutManager;
import com.gingersoft.supply_chain.mvp.ui.widget.ShowSecondCategoryPopup;
import com.gingersoft.supply_chain.mvp.utils.ViewUtils;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import lombok.val;


/**
 * Description: 選購食材
 */
public class BuyIngredientsFragment extends BaseSupplyChainFragment<BuyIngredientsPresenter> implements BuyIngredientsContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_food_ingredients)
    QMUITopBar topbarFoodIngredients;
    @BindView(R2.id.layout_purchase_food_content)
    RelativeLayout layoutContent;
    @BindView(R2.id.ed_food_ingredients_search)
    EditText edFoodIngredientsSearch;
    @BindView(R2.id.layout_food_ingredients_search)
    LinearLayout layoutFoodIngredientsSearch;
    @BindView(R2.id.tv_switch_food_ingredients_show_type)
    QMUIAlphaTextView tvSwitchFoodIngredientsShowType;
    @BindView(R2.id.rv_food_ingredients_category)
    RecyclerView rvFirstCategory;
    private FirstLevelCategoryAdapter firstLevelCategoryAdapter;

    @BindView(R2.id.layout_ingredients_left)
    LinearLayout layoutIngredientsLeft;
    @BindView(R2.id.rv_food_ingredients_second_category)
    RecyclerView rvSecondCategory;
    private SecondCategoryAdapter secondCategoryAdapter;

    @BindView(R2.id.section_food_ingredients)
    QMUIStickySectionLayout sectionFood;
    private BuyIngredientsAdapter adapter;
    //    @BindView(R2.id.rv_food_ingredients)
//    RecyclerView rvFoodIngredients;
    @BindView(R2.id.srl_supplier)
    LinearLayout srlSupplier;
    @BindView(R2.id.btn_new_food_ingredient)
    QMUIAlphaButton btnNewFoodIngredient;
    @BindView(R2.id.btn_food_ingredients_confirm)
    QMUIAlphaButton btnFoodIngredientsConfirm;
    @BindView(R2.id.tv_ingredients_food_num)
    TextView tvIngredientsFoodNum;
    @BindView(R2.id.btn_food_ingredients_cancel)
    QMUIAlphaButton btnFoodIngredientsCancel;
    @BindView(R2.id.layout_food_ingredients_btn)
    LinearLayout layoutFoodIngredientsBtn;
    @BindView(R2.id.btn_switch_row)
    QMUIAlphaImageButton btnSwitchRow;
    @BindView(R2.id.layout_category)
    LinearLayout layoutCategory;
    @BindView(R2.id.card_show_more_category)
    CardView cardMoreCategory;
    @BindView(R2.id.iv_unfold_arrow)
    ImageView ivUnfoldArrow;
    @BindView(R2.id.tv_unfold_category)
    TextView tvUnfoldCategory;
    TextView tvShoppingCart;
    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    /**
     * 0單列
     * 1雙列
     */
    private boolean isSinger = true;

    private LoadService fullRegister;

    public static BuyIngredientsFragment newInstance() {
        BuyIngredientsFragment fragment = new BuyIngredientsFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerBuyIngredientsComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_buy_ingredients, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTopBar();
//        loadService = LoadSir.getDefault().register(layoutRightContent, (Callback.OnReloadListener) v -> {
//        });
        fullRegister = LoadSir.getDefault().register(layoutContent, (Callback.OnReloadListener) v -> {
        });
//        refreshLayout.setEnableOverScrollBounce(false);
//        refreshLayout.setEnableOverScrollDrag(false);
//        refreshLayout.setEnablePureScrollMode(true);
//        refreshLayout.resetNoMoreData();
        refreshLayout.setEnableOverScrollBounce(false)
                .setFooterTriggerRate(0.1f);

//        refreshLayout.setOnRefreshListener(refreshLayout -> {
//            //在這裡不是刷新，而是獲取上一個分類的數據
//            int i = firstLevelCategoryAdapter.getSelectedIndex() - 1;
//            if (i >= 0) {
//                firstLevelCategoryAdapter.getOnItemClickListener().onItemClick(firstLevelCategoryAdapter, null, i);
//            } else {
//                refreshLayout.finishRefreshWithNoMoreData();
//            }
//        });
//        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
//            //加載下一個分類
//            int itemCount = firstLevelCategoryAdapter.getItemCount();
//            int i = firstLevelCategoryAdapter.getSelectedIndex() + 1;
//            if (i < itemCount) {
//                firstLevelCategoryAdapter.getOnItemClickListener().onItemClick(firstLevelCategoryAdapter, null, i);
//            } else {
//                refreshLayout.finishLoadMoreWithNoMoreData();
//            }
//        });
        //獲取一級分類
        mPresenter.getCategoryTrees();
    }

    private void initTopBar() {
        initTopBar(topbarFoodIngredients, "食材管理");
        View view = View.inflate(requireContext(), R.layout.view_shopping_car, null);
        tvShoppingCart = view.findViewById(R.id.tv_purchase_cart_number);
        topbarFoodIngredients.addRightView(view, R.id.qmui_shopping_cart);
    }

    @OnClick({R2.id.layout_food_ingredients_search, R2.id.tv_switch_food_ingredients_show_type, R2.id.btn_food_ingredients_confirm,
            R2.id.btn_food_ingredients_cancel, R2.id.btn_switch_row, R2.id.card_show_more_category})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.layout_food_ingredients_search) {
            //跳轉搜索頁面
            jumpToSearch();
        } else if (viewId == R.id.btn_switch_row) {
            //切換顯示單雙列
            switchShowSingerOrDouble();
        } else if (viewId == R.id.tv_switch_food_ingredients_show_type) {
            //切換顯示分類或是顯示供應商
            switchShowCategoryOrSupplier();
        } else if (viewId == R.id.card_show_more_category) {
            //展開分類
            unfoldCategory();
        } else if (viewId == R.id.btn_food_ingredients_confirm) {
            //確認
            confirm();
        } else if (viewId == R.id.btn_food_ingredients_cancel) {
            //取消
            killMyself();
        }
    }

    /**
     * 跳轉到搜索頁面
     */
    private void jumpToSearch() {

    }

    /**
     * 切換顯示單列或雙列
     */
    private void switchShowSingerOrDouble() {
        //切換單雙列
        isSinger = !isSinger;
        setLayoutManager();
        adapter.setShowSingerRow(isSinger);

        btnSwitchRow.setImageResource(isSinger ? R.drawable.ic_single_row : R.drawable.ic_double_row);
        sectionFood.setAdapter(adapter);
    }

    private int lastIndex = 0;
    /**
     * 0為滑動到頂部
     * 1為滑動到底部
     * 2為用戶點擊加載
     */
    private int isTailOrHead = 0;
    private boolean isNextCategory = false;

    private void setLayoutManager() {
        LinearLayoutManager linearLayoutManager = isSinger ? new LinearLayoutManager(requireContext()) : getDoubleRowManager();
        sectionFood.setLayoutManager(linearLayoutManager);
        sectionFood.getRecyclerView().clearOnScrollListeners();

        sectionFood.getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                    int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                    //手指往上滑動，獲取下一個分類數據
                    //記錄當前滑動到哪個header，如果和上次不一致，頂部的分類就切換選中
                    if (!mPresenter.isLoadFood()) {
                        if (lastVisibleItemPosition == adapter.getItemCount() - 1) {
                            //最後一個，獲取下一個一級分類的數據
                            //當前一級分類不是最後一個
                            if (firstLevelCategoryAdapter.getSelectedIndex() != firstLevelCategoryAdapter.getItemCount() - 1) {
                                isTailOrHead = 1;
                                mPresenter.setLoadFood(true);
                                mPresenter.getFood(firstLevelCategoryAdapter.getItem(firstLevelCategoryAdapter.getSelectedIndex() + 1).getId());
                            }
                        } else if (firstVisibleItemPosition == 0) {
                            //第一個，獲取上一個一級分類的數據
                            //當前一級分類不是第一個
                            if (firstLevelCategoryAdapter.getSelectedIndex() != 0) {
                                isTailOrHead = 0;
                                mPresenter.setLoadFood(true);
                                mPresenter.getFood(firstLevelCategoryAdapter.getItem(firstLevelCategoryAdapter.getSelectedIndex() - 1).getId());
                            }
                        }
                    }
                }
            }


            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
//                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                int sectionIndex = adapter.getSectionIndex(firstVisibleItemPosition);
//                //手指往上滑動，獲取下一個分類數據
//                //記錄當前滑動到哪個header，如果和上次不一致，頂部的分類就切換選中
//                if (!mPresenter.isLoadFood()) {
//                    if (lastVisibleItemPosition == adapter.getItemCount() - 1) {
//                        //最後一個，獲取下一個一級分類的數據
//                        //當前一級分類不是最後一個
//                        if (firstLevelCategoryAdapter.getSelectedIndex() != firstLevelCategoryAdapter.getItemCount() - 1) {
//                            isTailOrHead = 1;
//                            mPresenter.setLoadFood(true);
//                            mPresenter.getFood(firstLevelCategoryAdapter.getItem(firstLevelCategoryAdapter.getSelectedIndex() + 1).getId());
//                        }
//                    } else if (firstVisibleItemPosition == 0) {
//                        //第一個，獲取上一個一級分類的數據
//                        //當前一級分類不是第一個
//                        if (firstLevelCategoryAdapter.getSelectedIndex() != 0) {
//                            isTailOrHead = 0;
//                            mPresenter.setLoadFood(true);
//                            mPresenter.getFood(firstLevelCategoryAdapter.getItem(firstLevelCategoryAdapter.getSelectedIndex() - 1).getId());
//                        }
//                    }
//                }
                if (sectionIndex != lastIndex) {
                    QMUISection<CategoryBean, PurchaseFoodBean> sectionDirectly = adapter.getSectionDirectly(sectionIndex);
                    if (sectionDirectly != null && sectionDirectly.getHeader() != null) {
                        Integer id = sectionDirectly.getHeader().getId();
                        List<OrderCategoryBean.FoodCategoryTrees> data = secondCategoryAdapter.getData();
                        for (int i = lastIndex; i < data.size(); i = dy > 0 ? i + 1 : i - 1) {
                            if (i < 0) {
                                break;
                            }
                            if (data.get(i).getId() == id) {
                                secondCategoryAdapter.setSelectedIndex(i);
                                CenterLayoutManager layoutManager = (CenterLayoutManager) rvSecondCategory.getLayoutManager();
                                layoutManager.smoothScrollToPosition(rvSecondCategory, new RecyclerView.State(), i);
                                break;
                            }
                        }
                        lastIndex = sectionIndex;
                    }
                }
            }
        });
    }

    private void switchCategory(BaseQuickAdapter<OrderCategoryBean.FoodCategoryTrees, ? extends RecyclerView.ViewHolder> adapter, RecyclerView recyclerView, Integer id) {
        List<OrderCategoryBean.FoodCategoryTrees> data = adapter.getData();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getId() == id) {
                if (adapter instanceof SecondCategoryAdapter) {
                    ((SecondCategoryAdapter) adapter).setSelectedIndex(i);
                } else if (adapter instanceof FirstLevelCategoryAdapter) {
                    ((FirstLevelCategoryAdapter) adapter).setSelectedIndex(i);
                }
                CenterLayoutManager layoutManager = (CenterLayoutManager) recyclerView.getLayoutManager();
                layoutManager.smoothScrollToPosition(recyclerView, new RecyclerView.State(), i);
                if (i == data.size() - 1) {
                    if (adapter instanceof FirstLevelCategoryAdapter) {

                    } else {

                    }
                    //現在是最後一個二級分類，這時候去獲取下一個一級分類的內容
                    if (!isNextCategory) {
                        isNextCategory = true;
                    } else {
                        //是一級分類最後一個
                        refreshLayout.setNoMoreData(true);
                    }
                } else {
                    isNextCategory = false;
                }
                return;
            }
        }
    }

    /**
     * 切換顯示分類或供應商
     */
    private void switchShowCategoryOrSupplier() {

    }

    /**
     * 展開二級分類
     */
    private void unfoldCategory() {
        if (secondCategoryAdapter == null) {
            return;
        }
        new XPopup.Builder(requireContext())
                .atView(layoutCategory)
                .hasShadowBg(false)
                .popupPosition(PopupPosition.Bottom)
                .asCustom(new ShowSecondCategoryPopup(requireContext(), secondCategoryAdapter.getSelectIndex(), layoutCategory.getMeasuredWidth(), secondCategoryAdapter.getData(), (adapter, view, position) -> {
                    //二級分類滾動顯示，當前彈窗顯示三級分類，顯示三級分類在popup內部處理
                    secondCategoryAdapter.getOnItemClickListener().onItemClick(secondCategoryAdapter, view, position);
                }))
                .show();
    }

    /**
     * 確認，進入購物車頁面
     */
    private void confirm() {

    }

    @Override
    public void loadCategory(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (foodCategoryTrees.size() > 0) {
            fullRegister.showSuccess();
            if (firstLevelCategoryAdapter == null) {
                firstLevelCategoryAdapter = new FirstLevelCategoryAdapter(foodCategoryTrees, requireContext());
                rvFirstCategory.setAdapter(firstLevelCategoryAdapter);
                firstLevelCategoryAdapter.setOnItemClickListener((adapter, view, position) -> {
                    //切換右側顯示的二級分類和食材
                    firstLevelCategoryAdapter.setSelectedIndex(position);
                    ViewUtils.moveToCenterByVertical(rvFirstCategory, position);
                    loadSecondCategory(firstLevelCategoryAdapter.getData().get(position).getFoodCategoryTrees());
                    //獲取當前分類所有食材
                    mPresenter.getFood(firstLevelCategoryAdapter.getItem(position).getId());
                });
                //默認選中第0個分類
                firstLevelCategoryAdapter.getOnItemClickListener().onItemClick(firstLevelCategoryAdapter, null, 0);
            } else {
                firstLevelCategoryAdapter.setList(foodCategoryTrees);
            }
        } else {
            fullRegister.showCallback(ErrorCallback.class);
        }
    }

    @Override
    public void loadRightFoodIngredients(List<PurchaseFoodBean> purchaseFoodListVOS) {
        // 點擊一二三級分類，都是清空當前頁面所有食材，然後顯示當前級別分類下的食材
        // 滑動則是判斷底部，一直累加數據
        sectionFood.setLayoutManager(new LinearLayoutManager(requireContext()));
    }

    @Override
    public void loadFail() {
//        loadService.showCallback(EmptyCallback.class);
    }

    /**
     * 加載二級分類
     *
     * @param foodCategoryTrees
     */
    private void loadSecondCategory(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (secondCategoryAdapter == null) {
            secondCategoryAdapter = new SecondCategoryAdapter(requireContext(), foodCategoryTrees);
            rvSecondCategory.setLayoutManager(new CenterLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false));
            rvSecondCategory.setAdapter(secondCategoryAdapter);
            OnItemClickListener onItemClickListener = (adapter, view, position) -> {
                secondCategoryAdapter.setSelectedIndex(position);
                ViewUtils.moveToCenterByHorizontal(rvSecondCategory, position);
                //加載當前分類下的食品

            };
            secondCategoryAdapter.setOnItemClickListener(onItemClickListener);
        } else {
            secondCategoryAdapter.setNewInstance(foodCategoryTrees);
        }
        //默認選中第0個
        if (foodCategoryTrees != null && foodCategoryTrees.size() > 0) {
            secondCategoryAdapter.getOnItemClickListener().onItemClick(secondCategoryAdapter, rvSecondCategory, 0);
        }
    }

    /**
     * 加載食品，找到這些食品最近的上一個分類，將數據添加到這個分類下面,如果沒有，就添加到最頂部
     *
     * @param categoryId 當前分類id
     * @param food       食品
     */
    @Override
    public void loadFood(int categoryId, List<QMUISection<CategoryBean, PurchaseFoodBean>> food) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        food.addAll(food);
        food.addAll(food);

        if (adapter == null) {
            adapter = new BuyIngredientsAdapter(requireContext(), food);
            adapter.setCallback(new QMUIStickySectionAdapter.Callback<CategoryBean, PurchaseFoodBean>() {
                @Override
                public void loadMore(QMUISection<CategoryBean, PurchaseFoodBean> section, boolean loadMoreBefore) {

                }

                @Override
                public void onItemClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {

                }

                @Override
                public boolean onItemLongClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                    return false;
                }
            });
            sectionFood.setAdapter(adapter);
            setLayoutManager();
//            mPresenter.setLoadFood(false);
        } else {
//            if (isTailOrHead == 2) {
            adapter.setData(food);
//            } else {
//                List<QMUISection<CategoryBean, PurchaseFoodBean>> currentData = CollectionUtils.deepCopy(adapter.getCurrentData());
//                if (isTailOrHead == 0) {
//                    currentData.addAll(0, food);
//                } else {
//                    currentData.addAll(food);
//                }
//                adapter.setData(currentData);
//            }
//            mPresenter.setLoadFood(false);
        }
    }


    @NotNull
    private GridLayoutManager getDoubleRowManager() {
        val gridLayoutManager = new GridLayoutManager(requireContext(), 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.getItemIndex(position) < 0 ? gridLayoutManager.getSpanCount() : 1;
            }
        });
        return gridLayoutManager;
    }
}
