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.purchase.NotGoodsCallback;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
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.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.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.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.List;

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

import static com.gingersoft.supply_chain.mvp.ui.fragment.food.NewFoodIngredientsFragment.EDIT_FOOD_RESULT_CODE;

/**
 * Description: 選購食材
 *
 * @author admin
 */
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;
    protected FirstLevelCategoryAdapter firstLevelCategoryAdapter;

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

    protected 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.layout_choose_size)
    LinearLayout layoutChooseSize;
    @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.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.view_stick_head)
    StickyHeaderLayout stickyHeaderLayout;
    @BindView(R2.id.fresh_header)
    ClassicsHeader classicsHeader;
    @BindView(R2.id.tv_select_food_size)
    TextView tvSelectFoodSize;
    @BindView(R2.id.layout_food_ingredients_top)
    LinearLayout mLayoutFoodSearch;
    /**
     * 購物車數量textview
     */
    TextView tvShoppingCart;
    /**
     * 購物車中商品數量
     */
    int shoppingCartNum = 0;
    /**
     * 0單列
     * 1雙列
     */
    protected boolean isSinger = true;
    /**
     * 是否顯示供應商食材
     * true 是 false 否，顯示分類食材
     */
    protected boolean isShowSupplier = false;
    protected LoadService fullRegister;
    /**
     * 購物車requestCode
     */
    protected final static int TO_SHOPPING_CART_REQUEST_CODE = 1001;
    /**
     * 新增/編輯食材 request_code
     */
    protected final int EDIT_FOOD_REQUEST_CODE = 1050;

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

    @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();
        initPage();
        initLoadSir();
        initRefresh();
        //將購物車中的食品數據導出
        //初始化購物車數量
        setTvShoppingCartNum(mPresenter.statisticsFoodQuantity());
        loadDataByType();
    }

    /**
     * 初始化下拉刷新上拉加載
     */
    private void initRefresh() {
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            //在這裡不是刷新，而是獲取上一個分類的數據
            int i = firstLevelCategoryAdapter.getSelectedIndex() - 1;
            if (i >= 0) {
                loadFirstCategoryInfo(i, true, false);
            } else {
                setRefreshState(false);
            }
        }).setOnLoadMoreListener(refreshLayout -> {
            //加載下一個分類
            int i = firstLevelCategoryAdapter.getSelectedIndex() + 1;
            if (i < firstLevelCategoryAdapter.getItemCount()) {
                //判斷是否有緩存，把緩存拿出來，看看有沒有加載到列表中，如果已經加載了，繼續獲取下一個分類，一直到沒有加載的那個
                mPresenter.loadNextCategoryFood(isShowSupplier, i, firstLevelCategoryAdapter.getData());
            } else {
                finishLoad(true);
            }
        }).setEnableOverScrollBounce(false).setEnableAutoLoadMore(true);
    }

    private void initLoadSir() {
        fullRegister = LoadSir.getDefault().register(layoutContent, (Callback.OnReloadListener) v -> {
            if (v.getId() == R.id.layout_not_commodity) {
                //新增食材
                toCreateFood();
            }
        });
    }

    /**
     * 根據類型加載數據
     */
    protected void loadDataByType() {
        setSecondCategoryShowState(View.VISIBLE);
        //獲取一級分類
        mPresenter.getCategoryTrees();
    }

    protected void initTopBar() {
        initTopBar(topbarFoodIngredients, getString(R.string.str_title_purchase_order));
        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);
    }

    protected void initPage() {
        layoutChooseSize.setVisibility(View.GONE);
        layoutFoodIngredientsBtn.setVisibility(View.VISIBLE);
    }

    /**
     * 新建食品
     */
    protected void toCreateFood() {
        String defaultName = getCurrentCategoryName();
        if (isShowSupplier) {
            startForResult(NewFoodIngredientsFragment.newInstance(defaultName, ""), EDIT_FOOD_REQUEST_CODE);
        } else {
            startForResult(NewFoodIngredientsFragment.newInstance("", defaultName), 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);
    }

    /**
     * 食材recyclerview滑動監聽
     */
    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();
            //手指往上滑動，獲取下一個分類數據
            //記錄當前滑動到哪個header，如果和上次不一致，頂部的分類就切換選中
            if (currentStickyGroup != lastIndex) {
                if (currentStickyGroup == -1) {
                    return;
                }
                lastIndex = currentStickyGroup;
                //拿到當前顯示的分類信息
                BuyIngredientsBean headerDataByPosition = adapter.getHeaderDataByPosition(currentStickyGroup);
                if (headerDataByPosition == null) {
                    return;
                }
                //頂部懸浮顯示的是一級分類
                if (headerDataByPosition.parentId == 0) {
                    //找到這個一級分類，左側一級分類切換到選中，頂部二級分類切換顯示
                    int firstLevelCategoryIndex = firstLevelCategoryAdapter.getItemPosition(new OrderCategoryBean.FoodCategoryTrees(headerDataByPosition.id, headerDataByPosition.categoryName, headerDataByPosition.parentId));
                    if (firstLevelCategoryIndex > -1) {
                        //判斷這個分類是否已經被加載了，如果已經加載過了，就需要往下找，一直找到沒有被加載那個
                        selectFirstCategoryByIndex(firstLevelCategoryIndex);
                    }
                } else {
                    //二級或三級分類，同時也要判斷是否要切換一級分類
                    OrderCategoryBean.FoodCategoryTrees currentStickyCategory = new OrderCategoryBean.FoodCategoryTrees(headerDataByPosition.id, headerDataByPosition.categoryName, headerDataByPosition.parentId);
                    int secondLevelCategoryIndex = secondCategoryAdapter.getItemPosition(currentStickyCategory);
                    if (secondLevelCategoryIndex >= 0) {
                        secondCategorySelect(secondLevelCategoryIndex, true);
                    } else {
                        //沒有這個二級或三級分類，判斷是否切換了一級分類
                        BuyIngredientsBean firstCategory = mPresenter.getFirstCategoryByIndex(currentStickyGroup);
                        if (firstCategory != null) {
                            OrderCategoryBean.FoodCategoryTrees foodCategoryTrees = new OrderCategoryBean.FoodCategoryTrees(firstCategory.id, firstCategory.categoryName, firstCategory.parentId);
                            int firstCategoryIndex = firstLevelCategoryAdapter.getItemPosition(foodCategoryTrees);
                            if (firstCategoryIndex != firstLevelCategoryAdapter.getSelectedIndex()) {
                                if (firstCategoryIndex >= 0 && firstCategoryIndex != firstLevelCategoryAdapter.getSelectedIndex() && firstCategoryIndex < firstLevelCategoryAdapter.getItemCount()) {
                                    //切換一級分類
                                    selectFirstCategoryByIndex(firstCategoryIndex);
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    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) {
            //獲取供應商
            setSecondCategoryShowState(View.GONE);
            mPresenter.loadFoodIngredientsData(-1, true);
        } else {
            //獲取分類
            setSecondCategoryShowState(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();
    }

    /**
     * 確認，進入購物車頁面
     */
    protected void confirm() {
        List<PurchaseFoodBean> purchaseFood = mPresenter.getPurchaseFood();
        if (CollectionUtils.isNotNullOrEmpty(purchaseFood)) {
            startForResult(ShoppingCatFragment.newInstance(), TO_SHOPPING_CART_REQUEST_CODE);
            setFragmentResult(RESULT_OK, null);
        } 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(NotGoodsCallback.class);
        }
    }

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

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

    /**
     * 一級分類點擊，判斷列表中有沒有這個分類的數據，有的話就滾動
     *
     * @param position 分類下標
     */
    private void firstCategoryClick(int position) {
        if (position > firstLevelCategoryAdapter.getItemCount()) {
            return;
        }
        //這個分類的數據是否已經在顯示列表中
        int categoryIndex = mPresenter.isShowGoods(firstLevelCategoryAdapter.getItem(position));
        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)) {
            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);
        }
        setSecondCategoryShowState(View.VISIBLE);
    }

    /**
     * 加載食品，找到這些食品最近的上一個分類，將數據添加到這個分類下面,如果沒有，就添加到最頂部
     */
    @Override
    public void loadFood(List<BuyIngredientsBean> buyIngredientsBeans, boolean addToHead, boolean isReset) {
        setRefreshState(false);
        fullRegister.showSuccess();
        if (adapter == null) {
            adapter = new BuyIngredientsAdapter(requireContext(), buyIngredientsBeans);
            rvFoodIngredients.setAdapter(adapter);
            adapter.setOnItemClickListener((a, holder, groupPosition, childPosition) -> {
                BuyIngredientsBean buyIngredientsBean = adapter.getData().get(groupPosition);
                PurchaseFoodBean purchaseFoodBean = buyIngredientsBean.purchaseFoodList.get(childPosition);
                //显示弹窗
                GoodsDetailsPopup foodDetailsPopup = getFoodDetailsPopup(purchaseFoodBean)
                        .setOnFoodNumberChangeListener((purchaseFoodBean1, p, c, beforeNum, currentNum) -> {
                            foodNumberChanger(purchaseFoodBean, groupPosition, beforeNum, currentNum);
                            //需要刷新列表
                            adapter.notifyChildChanged(groupPosition, childPosition);
                        });
                new XPopup.Builder(requireContext())
                        .autoOpenSoftInput(false)
                        .autoFocusEditText(false)
                        .asCustom(foodDetailsPopup)
                        .show();
            });
            adapter.setOnItemChildClickListener((a, view, groupPosition, position) -> {
                if (groupPosition < adapter.getData().size()) {
                    if (position < adapter.getData().get(groupPosition).purchaseFoodList.size()) {
                        PurchaseFoodBean purchaseFoodBean = adapter.getData().get(groupPosition).purchaseFoodList.get(position);
                        if (view.getId() == R.id.iv_commodity_edit) {
                            //編輯
                            startForResult(NewFoodIngredientsFragment.newInstance(purchaseFoodBean), EDIT_FOOD_REQUEST_CODE);
                        } else if (view.getId() == R.id.iv_commodity_delete) {
                            //刪除食材
                            AppDialog.getInstance().showWaringDialog(mContext, "是否確認刪除" + purchaseFoodBean.getName(), () -> {
                                mPresenter.deleteFood(purchaseFoodBean.getId(), isShowSupplier ? -1 : firstLevelCategoryAdapter.getSelectedIndex(), groupPosition, position);
                            });
                        }
                        return;
                    }
                }
                showMessage(getString(R.string.str_data_info));
            });
            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;
                adapter.addData(addToHead ? 0 : adapter.getData().size(), buyIngredientsBeans, startIndex, endIndex);
            }
        }
    }

    protected GoodsDetailsPopup getFoodDetailsPopup(PurchaseFoodBean purchaseFoodBean) {
        return new GoodsDetailsPopup(requireContext(), purchaseFoodBean);
    }

    /**
     * 食品数量改变时调用
     *
     * @param purchaseFoodBean    食品信息
     * @param parentCategoryIndex 食品分类下标：食品所属分类在列表中的下标
     * @param beforeNum           改变之前的数量
     * @param currentNum          改变之后的数量
     */
    private void foodNumberChanger(PurchaseFoodBean purchaseFoodBean, int parentCategoryIndex, int beforeNum, int currentNum) {
        BuyIngredientsBean firstCategory = mPresenter.getFirstCategoryByIndex(parentCategoryIndex);
        if (firstCategory != null) {
            int firstCategoryByIndex = firstLevelCategoryAdapter.getItemPosition(new OrderCategoryBean.FoodCategoryTrees(firstCategory.id, firstCategory.categoryName, firstCategory.parentId));
            //找到一級分類下標
            if (beforeNum == 0 || currentNum == 0) {
                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);
    }

    protected void setSecondCategoryShowState(int visibility) {
        layoutCategory.setVisibility(visibility);
    }

    private void setTvShoppingCartNum(int num) {
        tvSelectFoodSize.setText(String.valueOf(num));
        //食材管理頁面，這個tvShoppingCart為空
        if (tvShoppingCart != null) {
            tvShoppingCart.setText(String.valueOf(num));
            if (num > 0) {
                tvShoppingCart.setVisibility(View.VISIBLE);
            } else {
                tvShoppingCart.setVisibility(View.GONE);
            }
        }
        shoppingCartNum = num;
    }

    public 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());
    }

    /**
     * 獲取雙列的recyclerview的layoutManager
     */
    @NotNull
    private GroupedGridLayoutManager getDoubleRowManager() {
        val gridLayoutManager = new GroupedGridLayoutManager(requireContext(), 2, adapter);
        return gridLayoutManager;
    }

    /**
     * 滾動到指定位置
     *
     * @param n                   下標
     * @param linearLayoutManager recyclerview的layoutManager
     */
    public void scrollToPosition(int n, LinearLayoutManager linearLayoutManager) {
        isUser = false;
        linearLayoutManager.scrollToPositionWithOffset(n, 0);
    }

    /**
     * 獲取當前分類名稱
     *
     * @return 當前分類名稱
     */
    private String getCurrentCategoryName() {
        String defaultName = "";
        if (firstLevelCategoryAdapter != null) {
            if (firstLevelCategoryAdapter.getItemCount() > firstLevelCategoryAdapter.getSelectedIndex()) {
                defaultName = firstLevelCategoryAdapter.getItem(firstLevelCategoryAdapter.getSelectedIndex()).getName();
            }
        }
        return defaultName;
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == TO_SHOPPING_CART_REQUEST_CODE && resultCode == RESULT_OK) {
            resetData();
        } else if (requestCode == EDIT_FOOD_REQUEST_CODE && resultCode == EDIT_FOOD_RESULT_CODE) {
            resetData();
        }
    }

    private void resetData() {
        //之前去到購物車頁面，現在回到這個頁面
        //如果修改了供應商和分類信息，可以清除掉緩存再獲取，就能刷新頁面
        //購物車食材數量發生了變化，需要刷新當前頁面的食材數量
        setTvShoppingCartNum(mPresenter.statisticsFoodQuantity());
        mPresenter.clearShowFoods();
        mPresenter.clearCategoryFoods();
        mPresenter.clearSupplierFoods();
        mPresenter.clearSupplierCache();
        mPresenter.clearCategoryTreesCache();
        refreshData();
    }

    protected void refreshData() {
        if (isShowSupplier) {
//            if (pageType == GET_FOOD_BY_SUPPLIER) {
//                mPresenter.getFoodsBySupplier(0, firstLevelCategoryAdapter.getItem(0), false, true);
//            } else {
            mPresenter.loadFoodIngredientsData(-1, true);
//            }
        } else {
            mPresenter.getCategoryTrees();
        }
    }
}
