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.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.OnScrollListener;

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.order.cart.ShoppingCart;
import com.gingersoft.gsa.cloud.ui.animator.CustomAnimation1;
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.BuyIngredientsBean;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.BuyIngredientsContract;
import com.gingersoft.supply_chain.mvp.presenter.BuyIngredientsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.BaseViewHolder;
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.GroupedRecyclerViewAdapter;
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.fragment.order.ShoppingCatFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.CenterLayoutManager;
import com.gingersoft.supply_chain.mvp.ui.widget.GoodsDetailsPopup;
import com.gingersoft.supply_chain.mvp.ui.widget.GroupedGridLayoutManager;
import com.gingersoft.supply_chain.mvp.ui.widget.ShowSecondCategoryPopup;
import com.gingersoft.supply_chain.mvp.ui.widget.StickyHeaderLayout;
import com.gingersoft.supply_chain.mvp.utils.ViewUtils;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
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.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import org.jetbrains.annotations.NotNull;

import java.util.Collections;
import java.util.List;

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

import static com.scwang.smartrefresh.layout.internal.InternalClassics.ID_TEXT_TITLE;

/**
 * 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)
    CollapsingToolbarLayout 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;
    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.view_stick_head)
    StickyHeaderLayout stickyHeaderLayout;
    @BindView(R2.id.fresh_header)
    ClassicsHeader classicsHeader;
    //購物車數量textview
    TextView tvShoppingCart;
    /**
     * 購物車中商品數量
     */
    int shoppingCartNum = 0;
    /**
     * 0單列
     * 1雙列
     */
    private boolean isSinger = true;
    /**
     * 是否顯示供應商食材
     * true 是 false 否，顯示分類食材
     */
    private boolean isShowSupplier = false;

    private LoadService fullRegister;
    /**
     * 頁面類型
     * FOOD_INGREDIENTS 為編輯食材頁面
     * ADD_ORDER 為添加訂單頁面
     * GET_FOOD_BY_SUPPLIER 根据供應商顯示食品列表
     */
    private int pageType = 1;
    public final static int FOOD_INGREDIENTS = 1;
    public final static int ADD_ORDER = 2;
    public final static int GET_FOOD_BY_SUPPLIER = 3;

    private final static String pageTypeKey = "pageType";
    private final static String supplierIdKey = "supplierId";
    private final static String supplierNameKey = "supplierName";

    public final static int TO_SHOPPING_CART_REQUESTCODE = 1001;

    public static BuyIngredientsFragment newInstance(int pageType) {
        BuyIngredientsFragment fragment = new BuyIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(pageTypeKey, pageType);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static BuyIngredientsFragment newInstance(int supplierId, String supplierName) {
        BuyIngredientsFragment fragment = new BuyIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(pageTypeKey, GET_FOOD_BY_SUPPLIER);
        bundle.putInt(supplierIdKey, supplierId);
        bundle.putString(supplierNameKey, supplierName);
        fragment.setArguments(bundle);
        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) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            pageType = arguments.getInt(pageTypeKey);
        }
        initTopBar();
        fullRegister = LoadSir.getDefault().register(layoutContent, (Callback.OnReloadListener) v -> {
        });
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            //在這裡不是刷新，而是獲取上一個分類的數據
            int i = firstLevelCategoryAdapter.getSelectedIndex() - 1;
            if (i >= 0) {
                loadFirstCategoryInfo(i, true, false);
            } else {
                Log.e("eee", "没有更多数据了" + i);
                setRefreshState(false);
            }
        }).setOnLoadMoreListener(refreshLayout -> {
            //加載下一個分類
            int i = firstLevelCategoryAdapter.getSelectedIndex() + 1;
            if (i < firstLevelCategoryAdapter.getItemCount()) {
                //判斷是否有緩存，把緩存拿出來，看看有沒有加載到列表中，如果已經加載了，繼續獲取下一個分類，一直到沒有加載的那個
                mPresenter.loadNextCategoryFood(isShowSupplier, i, firstLevelCategoryAdapter.getData());
            } else {
                Log.e("eee", "没有更多数据了" + i);
                finishLoad(true);
            }
        }).setEnableOverScrollBounce(false).setEnableAutoLoadMore(true);
        loadDataByType();
    }

    private void loadDataByType() {
        //將購物車中的食品數據導出
        //初始化購物車數量
        setTvShoppingCartNum(mPresenter.tranShoppingCartToCache());
        if (pageType == GET_FOOD_BY_SUPPLIER) {
            Bundle arguments = getArguments();
            if (arguments != null) {
                int supplierId = arguments.getInt(supplierIdKey);
                String supplierName = arguments.getString(supplierNameKey);
                //設置標題為這個供應商名字
                topbarFoodIngredients.setTitle(supplierName);
                //設置左側顯示數據
                OrderCategoryBean.FoodCategoryTrees supplierToCategory = new OrderCategoryBean.FoodCategoryTrees(supplierId, supplierName, 0);
                //只顯示一個供應商信息，所以隱藏左邊側邊欄
                layoutIngredientsLeft.setVisibility(View.GONE);
                //將顯示模式設置為顯示供應商
                isShowSupplier = true;
                //設置供應商信息
//                this.supplierId = supplierId;
//                setCurrentSupplierName(supplierName);
                //將當前供應商信息緩存到緩存中
//                mPresenter.addToSupplierCacheInfo(supplierId, supplierName);
                //獲取該供應商數據
//                getFoodsBySupplierId();
                mPresenter.getFoodsBySupplier(0, supplierToCategory, false, true);
            } else {
                killMyself();
            }
        } else {
            //獲取一級分類
            mPresenter.getCategoryTrees();
        }
    }

    private void initTopBar() {
        if (pageType == FOOD_INGREDIENTS) {
            initTopBar(topbarFoodIngredients, "食材管理");
            btnNewFoodIngredient.setVisibility(View.VISIBLE);
            layoutFoodIngredientsBtn.setVisibility(View.GONE);
            topbarFoodIngredients.addRightImageButton(R.drawable.ic_circle_new_food_ingredient, R.id.qmui_add_new_food_ingredients).setOnClickListener(v -> {
                //新增食材
                toCreateFood();
            });
        } else {
            initTopBar(topbarFoodIngredients, "採購單");
            layoutFoodIngredientsBtn.setVisibility(View.VISIBLE);
            View view = View.inflate(requireContext(), R.layout.view_shopping_car, null);
            tvShoppingCart = view.findViewById(R.id.tv_purchase_cart_number);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
            view.setLayoutParams(layoutParams);
            view.setOnClickListener(this);
            topbarFoodIngredients.addRightView(view, R.id.qmui_shopping_cart);
        }
    }

    /**
     * 新建食品
     */
    private void toCreateFood() {
        if (isShowSupplier) {
//            startForResult(NewFoodIngredientsFragment.newInstance(currentSupplierName, ""), EDIT_FOOD_REQUEST_CODE);
        } else {
//            startForResult(NewFoodIngredientsFragment.newInstance("", currentCategoryName), EDIT_FOOD_REQUEST_CODE);
        }
    }

    @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 || viewId == R.id.qmui_shopping_cart) {
            //確認
            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);
        rvFoodIngredients.setAdapter(adapter);
    }

    private int lastIndex = 0;
    /**
     * 是不是用戶滑動
     */
    private boolean isUser = true;

    private void setLayoutManager() {
        LinearLayoutManager linearLayoutManager = isSinger ? new LinearLayoutManager(requireContext()) : getDoubleRowManager();
        rvFoodIngredients.setLayoutManager(linearLayoutManager);
    }

    private RecyclerView.OnScrollListener mFoodScrollListener = new OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (!isUser) {
                //不是用戶手動滑動的，不執行下面的
                isUser = true;
                return;
            }
            int currentStickyGroup = stickyHeaderLayout.getCurrentStickyGroup();
            Log.e("eee", dy + "當前組下標：" + currentStickyGroup);
            //手指往上滑動，獲取下一個分類數據
            //記錄當前滑動到哪個header，如果和上次不一致，頂部的分類就切換選中
            if (currentStickyGroup != lastIndex) {
                if (currentStickyGroup == -1) {
                    return;
                }
                lastIndex = currentStickyGroup;
                //拿到當前顯示的分類信息
                BuyIngredientsBean headerDataByPosition = adapter.getHeaderDataByPosition(currentStickyGroup);
                if (headerDataByPosition == null) {
                    return;
                }
                Log.e("eee", "當前分類名稱：" + headerDataByPosition.categoryName);
                //頂部懸浮顯示的是一級分類
                if (headerDataByPosition.parentId == 0) {
                    //找到這個一級分類，左側一級分類切換到選中，頂部二級分類切換顯示
                    int firstLevelCategoryIndex = firstLevelCategoryAdapter.getItemPosition(new OrderCategoryBean.FoodCategoryTrees(headerDataByPosition.id, headerDataByPosition.categoryName, headerDataByPosition.parentId));
                    Log.e("eee", "一級分類下標：" + firstLevelCategoryIndex);
                    if (firstLevelCategoryIndex > -1) {
                        //判斷這個分類是否已經被加載了，如果已經加載過了，就需要往下找，一直找到沒有被加載那個
                        selectFirstCategoryByIndex(firstLevelCategoryIndex);
                    }
                } else {
                    //二級或三級分類，同時也要判斷是否要切換一級分類
                    OrderCategoryBean.FoodCategoryTrees currentStickyCategory = new OrderCategoryBean.FoodCategoryTrees(headerDataByPosition.id, headerDataByPosition.categoryName, headerDataByPosition.parentId);
                    int secondLevelCategoryIndex = secondCategoryAdapter.getItemPosition(currentStickyCategory);
                    Log.e("eee", "二級分類下標：" + secondLevelCategoryIndex);
                    if (secondLevelCategoryIndex >= 0) {
                        secondCategorySelect(secondLevelCategoryIndex, true);
                    } else {
                        //沒有這個二級或三級分類，判斷是否切換了一級分類
                        BuyIngredientsBean firstCategory = mPresenter.getFirstCategoryByIndex(currentStickyGroup);
                        if (firstCategory != null) {
                            Log.e("eee", "一級分類：" + firstCategory.categoryName);
                            OrderCategoryBean.FoodCategoryTrees foodCategoryTrees = new OrderCategoryBean.FoodCategoryTrees(firstCategory.id, firstCategory.categoryName, firstCategory.parentId);
                            int firstCategoryIndex = firstLevelCategoryAdapter.getItemPosition(foodCategoryTrees);
                            Log.e("eee", "一級分類下標：" + firstCategoryIndex);
                            if (firstCategoryIndex != firstLevelCategoryAdapter.getSelectedIndex()) {
                                if (firstCategoryIndex >= 0 && firstCategoryIndex != firstLevelCategoryAdapter.getSelectedIndex() && firstCategoryIndex < firstLevelCategoryAdapter.getItemCount()) {
                                    selectFirstCategoryByIndex(firstCategoryIndex);
                                    //切換一級分類後，再切換二級分類
//                                    int secondLevelCategoryIndex2 = secondCategoryAdapter.getItemPosition(currentStickyCategory);
//                                    secondCategorySelect(secondLevelCategoryIndex2, secondLevelCategoryIndex2 >= 0);
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    private void secondCategorySelect(int secondLevelCategoryIndex2, boolean select) {
        if (select) {
            secondCategoryAdapter.setSelectedIndex(secondLevelCategoryIndex2);
            rvSecondCategory.post(() -> ViewUtils.moveToCenterByHorizontal(rvSecondCategory, secondLevelCategoryIndex2));
        }
    }

    /**
     * 切換顯示分類或供應商
     */
    private void switchShowCategoryOrSupplier() {
        isShowSupplier = !isShowSupplier;
        if (isShowSupplier) {
            //獲取供應商
            layoutCategory.setVisibility(View.GONE);
            mPresenter.loadFoodIngredientsData(-1, true);
        } else {
            //獲取分類
            layoutCategory.setVisibility(View.VISIBLE);
            mPresenter.getCategoryTrees();
        }
        setShowTypeBtn();
    }

    private void setShowTypeBtn() {
        if (isShowSupplier) {
            tvSwitchFoodIngredientsShowType.setText(getString(R.string.str_supplier));
        } else {
            tvSwitchFoodIngredientsShowType.setText(getString(R.string.str_species));
        }
    }

    /**
     * 展開二級分類
     */
    private void unfoldCategory() {
        if (secondCategoryAdapter == null) {
            return;
        }
        new XPopup.Builder(requireContext())
                .atView(layoutCategory)
                .popupPosition(PopupPosition.Bottom)
                .hasShadowBg(false)
                .borderRadius(0)
                .asCustom(new ShowSecondCategoryPopup(requireContext(), layoutCategory.getMeasuredWidth(), secondCategoryAdapter.getSelectIndex(), secondCategoryAdapter.getData()).setOnCategoryClickListener(new ShowSecondCategoryPopup.OnCategoryClickListener() {
                    @Override
                    public void onClick(OrderCategoryBean.FoodCategoryTrees foodCategoryTrees, int position, int categoryLevel) {
                        //如果是二級分類，選中這個二級分類
                        secondCategorySelect(position, categoryLevel == 2);
                        //加載當前分類下的食品
                        //二級分類點擊
                        //列表要定位到指定位置
                        //找到這個分類的下標
                        int categoryIndex = mPresenter.getIndexInAllFood(adapter.getData(), foodCategoryTrees);
                        if (categoryIndex != -1) {
                            scrollToPosition(categoryIndex, (LinearLayoutManager) rvFoodIngredients.getLayoutManager());
                            isUser = false;
                        }
                    }
                }))
                .show();
    }

    /**
     * 確認，進入購物車頁面
     */
    private void confirm() {
        SupplyShoppingCart.getInstance().clear();
        List<PurchaseFoodBean> purchaseFood = mPresenter.getPurchaseFood();
        SupplyShoppingCart.getInstance().addAllFood(mPresenter.getPurchaseFood());
        if (CollectionUtils.isNotNullOrEmpty(purchaseFood)) {
            startForResult(ShoppingCatFragment.newInstance(), TO_SHOPPING_CART_REQUESTCODE);
        } else {
            showMessage("請選擇食材");
        }
    }

    /**
     * 一级分类
     *
     * @param foodCategoryTrees 所有分類層級信息
     */
    @Override
    public void initCategoryInfo(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (CollectionUtils.isNotNullOrEmpty(foodCategoryTrees)) {
            fullRegister.showSuccess();
            if (firstLevelCategoryAdapter == null) {
                firstLevelCategoryAdapter = new FirstLevelCategoryAdapter(foodCategoryTrees, requireContext());
                rvFirstCategory.setAdapter(firstLevelCategoryAdapter);
                firstLevelCategoryAdapter.setOnItemClickListener((adapter, view, position) -> {
                    firstCategoryClick(position);
                });
            } else {
                scrollToPosition(0, (LinearLayoutManager) rvFirstCategory.getLayoutManager());
                firstLevelCategoryAdapter.setNewInstance(foodCategoryTrees);
            }
            //默認選中第0個分類
            firstCategoryClick(0);
        } else {
            fullRegister.showCallback(EmptyCallback.class);
        }
    }

    /**
     * 加載一級分類數據
     *
     * @param position 一級分類下標
     */
    private void loadFirstCategoryInfo(int position, boolean addToHead, boolean isReset) {
        //切換右側顯示的二級分類和食材
        // 现在改为在滑動事件中切換
//        selectFirstCategoryByIndex(position);
        Log.e("eee", "loadFirstCategoryInfo：" + position);
        if (!mPresenter.isHasLocationInfo(isShowSupplier, position)) {
            //本地沒有緩衝才去查找
            //獲取點擊的分類的所有食材
            if (isShowSupplier) {
                mPresenter.getFoodsBySupplier(position, firstLevelCategoryAdapter.getItem(position), addToHead, isReset);
            } else {
                mPresenter.getFoodByCategory(position, firstLevelCategoryAdapter.getItem(position), addToHead, isReset);
            }
            Log.e("eee", "没有缓存");
        } else {
            //本地有緩存，拿緩存中的數據
            Log.e("eee", "讀緩存：" + position);
            mPresenter.loadCacheFood(isShowSupplier, position, addToHead, isReset);
        }
    }

    @Override
    public void selectFirstCategoryByIndex(int position) {
        Log.e("eee", "selectFirstCategoryByIndex");
        firstLevelCategoryAdapter.setSelectedIndex(position);
        loadSecondCategory(firstLevelCategoryAdapter.getItem(position).getFoodCategoryTrees());
        ViewUtils.moveToCenterByVertical(rvFirstCategory, position);
    }

    /**
     * 一級分類點擊，判斷列表中有沒有這個分類的數據，有的話就滾動
     *
     * @param position 分類下標
     */
    private void firstCategoryClick(int position) {
        if (position > firstLevelCategoryAdapter.getItemCount()) {
            return;
        }
        Log.e("eee", "一级分类点击" + position);
        //這個分類的數據是否已經在顯示列表中
        int categoryIndex = mPresenter.isShowGoods(firstLevelCategoryAdapter.getItem(position));
        Log.e("eee", "是否找到" + categoryIndex);
        if (categoryIndex == -1) {
            //未顯示
            //清空食材列表，重新加載當前下標分類的食品數據
            mPresenter.clearShowFoods();
            selectFirstCategoryByIndex(position);
            loadFirstCategoryInfo(position, false, true);
        } else {
            //已經在列表中了，只需要滾動到指定位置
            //通過分類下標，拿到列表食物下標
            selectFirstCategoryByIndex(position);
            scrollToPosition(mPresenter.getFoodIndexByCategoryIndex(categoryIndex));
        }
    }

    @Override
    public void loadFail() {

    }

    @Override
    public void finishLoad(boolean noData) {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        if (noData) {
            refreshLayout.finishRefreshWithNoMoreData();
        }
    }

    /**
     * 加載二級分類
     *
     * @param foodCategoryTrees
     */
    private void loadSecondCategory(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (secondCategoryAdapter != null && CollectionUtils.isNullOrEmpty(foodCategoryTrees)) {
            Log.e("eee", "沒有二級分類");
            secondCategoryAdapter.setNewInstance(null);
            return;
        }
        if (secondCategoryAdapter == null) {
            secondCategoryAdapter = new SecondCategoryAdapter(requireContext(), foodCategoryTrees);
            rvSecondCategory.setLayoutManager(new CenterLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false));
            rvSecondCategory.setAdapter(secondCategoryAdapter);
            OnItemClickListener onItemClickListener = (a, view, position2) -> {
                secondCategorySelect(position2, true);
                //加載當前分類下的食品
                //二級分類點擊
                //列表要定位到指定位置
                //找到這個分類的下標
                int categoryIndex = mPresenter.getIndexInAllFood(adapter.getData(), secondCategoryAdapter.getItem(position2));
                scrollToPosition(categoryIndex, (LinearLayoutManager) rvFoodIngredients.getLayoutManager());
                isUser = false;
            };
            secondCategoryAdapter.setOnItemClickListener(onItemClickListener);
        } else {
            secondCategoryAdapter.setNewInstance(foodCategoryTrees);
        }
        Log.e("eee", "二級分類加載完成" + foodCategoryTrees.size());
        //默認選中第0個
//        secondCategorySelect(0, foodCategoryTrees != null && foodCategoryTrees.size() > 0);
        layoutCategory.setVisibility(View.VISIBLE);
    }

    /**
     * 加載食品，找到這些食品最近的上一個分類，將數據添加到這個分類下面,如果沒有，就添加到最頂部
     */
    @Override
    public void loadFood(List<BuyIngredientsBean> buyIngredientsBeans, boolean addToHead, boolean isReset) {
        setRefreshState(false);
        if (adapter == null) {
            adapter = new BuyIngredientsAdapter(requireContext(), buyIngredientsBeans);
            rvFoodIngredients.setAdapter(adapter);
            adapter.setOnChildClickListener((a, holder, groupPosition, childPosition) -> {
                BuyIngredientsBean buyIngredientsBean = adapter.getData().get(groupPosition);
                PurchaseFoodBean purchaseFoodBean = buyIngredientsBean.purchaseFoodList.get(childPosition);
                //显示弹窗
                new XPopup.Builder(requireContext())
                        .autoOpenSoftInput(false)
                        .autoFocusEditText(false)
                        .asCustom(new GoodsDetailsPopup(requireContext(), purchaseFoodBean)
                                .setOnFoodNumberChangeListener((purchaseFoodBean1, p, c, beforeNum, currentNum) -> {
                                    foodNumberChanger(purchaseFoodBean, groupPosition, beforeNum, currentNum);
                                    //需要刷新列表
                                    adapter.notifyChildChanged(groupPosition, childPosition);
                                }))
                        .show();
            });
            adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);
            adapter.setOnFoodNumberChangeListener((purchaseFoodBean, parentCategoryIndex, categoryIndex, beforeNum, currentNum) -> foodNumberChanger(purchaseFoodBean, parentCategoryIndex, beforeNum, currentNum));
            rvFoodIngredients.removeOnScrollListener(mFoodScrollListener);
            rvFoodIngredients.addOnScrollListener(mFoodScrollListener);
            setLayoutManager();
        } else {
            if (isReset) {
                adapter.setNewInstance(buyIngredientsBeans);
            } else {
                int startIndex = 0;
                int endIndex = 0;
                if (!addToHead) {
                    //添加到尾部
                    startIndex = adapter.getItemCount() + 1;
                }
                for (BuyIngredientsBean buyIngredientsBean : buyIngredientsBeans) {
                    endIndex += buyIngredientsBean.purchaseFoodList.size() + 1;
                }
                endIndex += startIndex;
                Log.e("eee", "開始：" + startIndex + "結束：" + endIndex);
                adapter.addData(addToHead ? 0 : adapter.getData().size(), buyIngredientsBeans, startIndex, endIndex);
            }
        }
    }

    /**
     * 食品数量改变时调用
     *
     * @param purchaseFoodBean    食品信息
     * @param parentCategoryIndex 食品分类下标：食品所属分类在列表中的下标
     * @param beforeNum           改变之前的数量
     * @param currentNum          改变之后的数量
     */
    private void foodNumberChanger(PurchaseFoodBean purchaseFoodBean, int parentCategoryIndex, int beforeNum, int currentNum) {
        BuyIngredientsBean firstCategory = mPresenter.getFirstCategoryByIndex(parentCategoryIndex);
        Log.e("eee", parentCategoryIndex + "一級分類" + (firstCategory == null ? "null" : firstCategory.toString()));
        if (firstCategory != null) {
            int firstCategoryByIndex = firstLevelCategoryAdapter.getItemPosition(new OrderCategoryBean.FoodCategoryTrees(firstCategory.id, firstCategory.categoryName, firstCategory.parentId));
            //找到一級分類下標
            Log.e("eee", "一級分類下標：" + firstCategoryByIndex);
            if (beforeNum == 0 || currentNum == 0) {
                Log.e("eee", beforeNum + "數量：" + currentNum);
                OrderCategoryBean.FoodCategoryTrees item = firstLevelCategoryAdapter.getItem(firstCategoryByIndex);
                //正
                if (item.getSize() < 0) {
                    item.setSize(0);
                }
                if (beforeNum == 0) {
                    item.setSize(item.getSize() + 1);
                } else {
                    item.setSize(item.getSize() - 1);
                }
                firstLevelCategoryAdapter.notifyItemChanged(firstCategoryByIndex);
            }
        }
        mPresenter.addFood(purchaseFoodBean);
        shoppingCartNum += currentNum - beforeNum;
        setTvShoppingCartNum(shoppingCartNum);
    }

    private void setTvShoppingCartNum(int num) {
        tvShoppingCart.setText(String.valueOf(shoppingCartNum));
        if (num > 0) {
            tvShoppingCart.setVisibility(View.VISIBLE);
        } else {
            tvShoppingCart.setVisibility(View.GONE);
        }
    }

    private void setRefreshState(boolean noMoreData) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setNoMoreData(noMoreData);
    }

    @Override
    public void scrollToPosition(int index) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        scrollToPosition(index, (LinearLayoutManager) rvFoodIngredients.getLayoutManager());
    }

    @NotNull
    private GroupedGridLayoutManager getDoubleRowManager() {
        val gridLayoutManager = new GroupedGridLayoutManager(requireContext(), 2, adapter);
        return gridLayoutManager;
    }

    public void scrollToPosition(int n, LinearLayoutManager linearLayoutManager) {
        isUser = false;
        linearLayoutManager.scrollToPositionWithOffset(n, 0);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == TO_SHOPPING_CART_REQUESTCODE && resultCode == RESULT_OK) {
            //之前去到購物車頁面，現在回到這個頁面
            //購物車食材數量發生了變化，需要刷新當前頁面的食材數量
            mPresenter.tranShoppingCartToCache();
            //如果修改了供應商和分類信息，可以清除掉緩存再獲取，就能刷新頁面
            mPresenter.clearShowFoods();
            mPresenter.clearCategoryFoods();
            mPresenter.clearSupplierFoods();
            mPresenter.clearSupplierCache();
            mPresenter.clearCategoryTreesCache();
            if (isShowSupplier) {
                mPresenter.loadFoodIngredientsData(-1, true);
            } else {
                mPresenter.getCategoryTrees();
            }
        }
    }
}
