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

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.adapter.BaseCategoryAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
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.DaggerFoodIngredientsComponent;
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.FoodIngredientsContract;
import com.gingersoft.supply_chain.mvp.presenter.FoodIngredientsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.FoodListAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.OrderCategoryAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.order.ShoppingCatFragment;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaLinearLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;

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

import butterknife.BindView;
import butterknife.OnClick;

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

/**
 * Description: 食材管理
 */
public class FoodIngredientsFragment extends BaseSupplyChainFragment<FoodIngredientsPresenter> implements FoodIngredientsContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_food_ingredients)
    QMUITopBar topbarFoodIngredients;
    @BindView(R2.id.ed_food_ingredients_search)
    EditText edFoodIngredientsSearch;
    @BindView(R2.id.btn_food_ingredients_search)
    QMUIAlphaButton btnFoodIngredientsSearch;
    @BindView(R2.id.layout_food_ingredients_search)
    LinearLayout layoutFoodIngredientsSearch;
    @BindView(R2.id.rv_food_ingredients_category)
    RecyclerView rvLeftCategory;
    @BindView(R2.id.rv_food_ingredients)
    RecyclerView rvRightFoodIngredients;
    @BindView(R2.id.srl_supplier)
    LinearLayout srlSupplier;
    @BindView(R2.id.btn_new_food_ingredient)
    QMUIAlphaButton btnNewFoodIngredient;
    @BindView(R2.id.btn_food_ingredients_confirm)
    QMUIAlphaButton btnConfirm;
    @BindView(R2.id.btn_food_ingredients_cancel)
    QMUIAlphaButton btnCancel;
    @BindView(R2.id.rv_food_ingredients_second_category)
    RecyclerView rvSecondCategory;
    @BindView(R2.id.tv_switch_food_ingredients_show_type)
    TextView tvSwitchShowType;
    @BindView(R2.id.layout_switch_method)
    QMUIAlphaLinearLayout layoutSwitchMethod;
    @BindView(R2.id.layout_ingredients_left)
    LinearLayout leftLayout;
    @BindView(R2.id.tv_ingredients_food_num)
    TextView tvShoppingNum;
    /**
     * 左側分類recyclerview的高度的一半，用來自動滾動到中間，避免每次計算
     */
    private int halfLeftRvHeight;
    /**
     * 頁面類型
     * FOOD_INGREDIENTS 為編輯食材頁面
     * ADD_ORDER 為添加訂單頁面
     * ORDER_TYPE 為購物車頁面
     * 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 ORDER_TYPE = 3;
    public final static int GET_FOOD_BY_SUPPLIER = 4;

    private final static String pageTypeKey = "pageType";
    private final static String supplierIdKey = "supplierId";
    private final static String supplierNameKey = "supplierName";
    /**
     * 當前選中的供應商名字
     */
    private String currentSupplierName;
    /**
     * 當前選中的一級分類、二級分類、三級分類名，新建食材時需要用到
     */
//    private List<String> categoryNames;

    /**
     * 分類id，查詢此分類下的食品
     */
    private int categoryId = -1;
    /**
     * 當前分類的名字
     */
    private String currentCategoryName;

    /**
     * 供應商id，查詢此供應商下的食品
     */
    private int supplierId = -1;

    private FoodListAdapter foodListAdapter;
    /**
     * true：查看的是供應商的食材
     * false：查看分類下的食材
     */
    private boolean isSupplier = false;
    /**
     * 編輯食材 request_code
     */
    private final int EDIT_FOOD_REQUEST_CODE = 1050;
    /**
     * 在回到這個頁面時，購物車食材數量可能發生了變化，需要刷新當前頁面的食材數量
     */
    private boolean refreshList = false;
    /**
     * 當前顯示的是第幾級的分類
     * 現用於切換供應商再切換回來之後，顯示哪一級的分類
     */
    private int currentLevelCategory = OrderCategoryAdapter.PRIMARY_CATEGORY;

    private BaseCategoryAdapter listSelectAdapter;

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

    public static FoodIngredientsFragment newInstance(int supplierId, String supplierName) {
        FoodIngredientsFragment fragment = new FoodIngredientsFragment();
        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) {
        DaggerFoodIngredientsComponent //如找不到该类,请编译一下项目
                .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_food_ingredients, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            pageType = arguments.getInt(pageTypeKey);
        }
        loadService = LoadSir.getDefault().register(rvRightFoodIngredients, (Callback.OnReloadListener) v -> {
        });
        initTopBar();

        int foodNum = SupplyShoppingCart.getInstance().getCartFoods().size();
        setFoodNum(foodNum);

        loadDataByType();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (refreshList && foodListAdapter != null) {
            //在回到這個頁面時，購物車食材數量可能發生了變化，需要刷新當前頁面的食材數量
            mPresenter.refreshPageData(foodListAdapter.getData(), foodListAdapter.getIntegerMap());
            refreshList = false;
        }
    }

    private void loadDataByType() {
        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);
                //設置左側顯示數據
                CategoryBean categoryBean = new CategoryBean(supplierId, supplierName);
                mPresenter.setCategoryBeans(Collections.singletonList(categoryBean));
                //只顯示一個供應商信息，所以隱藏左邊側邊欄
//                showPrimaryCategory(View.GONE, View.GONE);
                leftLayout.setVisibility(View.GONE);
                //將顯示模式設置為顯示供應商
                isSupplier = true;
                //設置供應商信息
                this.supplierId = supplierId;
                setCurrentSupplierName(supplierName);
                //將當前供應商信息緩存到緩存中
                mPresenter.addToSupplierCacheInfo(supplierId, supplierName);
                //獲取該供應商數據
                getFoodsBySupplierId();
            } else {
                killMyself();
            }
        } else {
            mPresenter.getCategoryTrees();
        }
    }

    private void getSuppliers() {
        mPresenter.loadFoodIngredientsData(-1);
    }

    private void getFoodsBySupplierId() {
        if (supplierId == -1) {
            getSuppliers();
        } else {
            mPresenter.getFoodsBySupplierId(supplierId);
        }
    }

    private void getFoodsByCategoryId() {
        mPresenter.getFoodCacheByCategory(categoryId);
    }

    private void initTopBar() {
        if (pageType == FOOD_INGREDIENTS) {
            topbarFoodIngredients.setTitle("食材管理");
            btnNewFoodIngredient.setVisibility(View.VISIBLE);
            btnConfirm.setVisibility(View.GONE);
            btnCancel.setVisibility(View.GONE);
        } else if (pageType == ADD_ORDER) {
            topbarFoodIngredients.setTitle("採購單");
            btnNewFoodIngredient.setVisibility(View.GONE);
            btnConfirm.setVisibility(View.VISIBLE);
            btnCancel.setVisibility(View.VISIBLE);
            topbarFoodIngredients.addRightImageButton(R.drawable.ic_circle_new_food_ingredient, R.id.qmui_add_new_food_ingredients).setOnClickListener(v -> {
                //新增食材
                toCreateFood();
            });
        } else if (pageType == GET_FOOD_BY_SUPPLIER) {
            //根據供應商顯示食材
            //隱藏切換按鈕
            topbarFoodIngredients.setTitle("採購單");
            layoutSwitchMethod.setVisibility(View.GONE);
            btnConfirm.setVisibility(View.VISIBLE);
            btnCancel.setVisibility(View.VISIBLE);
            topbarFoodIngredients.addRightImageButton(R.drawable.ic_circle_new_food_ingredient, R.id.qmui_add_new_food_ingredients).setOnClickListener(v -> {
                //新增食材
                toCreateFood();
            });
        }
        topbarFoodIngredients.addLeftBackImageButton().setOnClickListener(v -> killMyself());
    }

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

    private void moveToCenter(LinearLayoutManager leftLayoutManager, int sectionPosition) {
        View childAt = rvLeftCategory.getChildAt(sectionPosition - leftLayoutManager.findFirstVisibleItemPosition());
//        if (halfLeftRvHeight == 0) {
        halfLeftRvHeight = rvLeftCategory.getHeight() / 2;
//        }
        if (childAt != null) {
            int y = (childAt.getTop() - halfLeftRvHeight);
            rvLeftCategory.smoothScrollBy(0, y);
        }
    }

    @OnClick({R2.id.layout_switch_method, R2.id.btn_new_food_ingredient, R2.id.btn_food_ingredients_search, R2.id.btn_food_ingredients_confirm, R2.id.btn_food_ingredients_cancel})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.layout_switch_method) {
            //切換
            isSupplier = !isSupplier;
            showPrimaryCategory(View.GONE, View.VISIBLE);
            if (isSupplier) {
                tvSwitchShowType.setText(getString(R.string.str_supplier));
                //獲取供應商，並且會獲取到第一個供應商的食材
                getFoodsBySupplierId();
            } else {
                //根據分類獲取食材
                if (currentLevelCategory != OrderCategoryAdapter.PRIMARY_CATEGORY) {
                    showPrimaryCategory(View.VISIBLE, View.GONE);
                }
                tvSwitchShowType.setText(getString(R.string.str_species));
                mPresenter.getCategoryTrees();
            }
        } else if (viewId == R.id.btn_new_food_ingredient) {
            //新增
            toCreateFood();
        } else if (viewId == R.id.btn_food_ingredients_search) {
            //搜索

        } else if (viewId == R.id.btn_food_ingredients_confirm) {
            //選擇完食品後,完成
            //把選中的數據取出
            if (foodListAdapter != null) {
                mPresenter.getSelectFood(foodListAdapter.getIntegerMap());
            }
            //需要先判斷是否有食品
            if (SupplyShoppingCart.getInstance().getCartFoods().size() > 0) {
                refreshList = true;
                start(ShoppingCatFragment.newInstance());
            } else {
                showMessage("請選擇食品");
            }
        } else if (viewId == R.id.btn_food_ingredients_cancel) {
            //取消
            killMyself();
        }
    }

    /**
     * 加載左側供應商列表
     */
    @Override
    public void loadLeftSupplierInfo(List<CategoryBean> categoryBeans) {
        if (supplierId == -1 && categoryBeans.size() > 0) {
            //設置默認第一個
            supplierId = categoryBeans.get(0).getId();
        }
        if (listSelectAdapter == null) {
            listSelectAdapter = new BaseCategoryAdapter(R.layout.item_base_category, categoryBeans);
            listSelectAdapter.setUnSelectColor(ContextCompat.getColor(mContext, R.color.color_3c))
                    .setSelectColor(ContextCompat.getColor(mContext, R.color.theme_color));
            listSelectAdapter.setOnItemClickListener((adapter, view, position) -> {
                listSelectAdapter.setSelectedIndex(position);
                moveToCenter((LinearLayoutManager) rvLeftCategory.getLayoutManager(), position);
                //獲取供應商的食品
                supplierId = categoryBeans.get(position).getId();
                setCurrentSupplierName(categoryBeans.get(position).getCategoryName());
                getFoodsBySupplierId();
            });
        } else {
            listSelectAdapter.setNewInstance(categoryBeans);
        }
        rvLeftCategory.setAdapter(listSelectAdapter);
    }

    /**
     * 加載右側食品數據
     */
    @Override
    public void loadRightFoodIngredients(List<PurchaseFoodBean> purchaseFoodListVos) {
        if (purchaseFoodListVos == null || purchaseFoodListVos.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
            return;
        } else {
            loadService.showSuccess();
        }
        if (foodListAdapter != null) {
            foodListAdapter.setList(purchaseFoodListVos);
        } else {
            foodListAdapter = new FoodListAdapter(mContext, purchaseFoodListVos, pageType);
            //將之前購物車的食材，添加到食材列表
            Map<Integer, PurchaseFoodBean> integerMap = foodListAdapter.getIntegerMap();
            for (PurchaseFoodBean purchaseFoodBean : SupplyShoppingCart.getInstance().getCartFoods()) {
                integerMap.put(purchaseFoodBean.getId(), purchaseFoodBean);
            }
            LinearLayoutManager rightLayoutManager = new LinearLayoutManager(mContext);
            rvRightFoodIngredients.setLayoutManager(rightLayoutManager);
            rvRightFoodIngredients.setAdapter(foodListAdapter);
            foodListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.iv_supplier_edit) {
                    //編輯食材
                    startForResult(NewFoodIngredientsFragment.newInstance(foodListAdapter.getData().get(position)), EDIT_FOOD_REQUEST_CODE);
                } else if (view.getId() == R.id.iv_supplier_delete) {
                    //刪除食材
                    PurchaseFoodBean purchaseFoodBean = foodListAdapter.getData().get(position);
                    new AppDialog().showWaringDialog(mContext, "是否確認刪除" + purchaseFoodBean.getName(), (view1, dialog) -> {
                        if (!isSupplier) {
                            purchaseFoodBean.setFoodCategoryName(getCurrentCategory());
                        }
                        mPresenter.deleteFood(purchaseFoodBean.getId(), purchaseFoodBean.getSupplierId(), purchaseFoodBean.getFoodCategoryId(), position);
                    });
                }
            });
//            foodListAdapter.setOnNumberChangeListener((beforeNumber, number, position) -> {
//                if (TextUtil.isNotEmptyOrNullOrUndefined(tvShoppingNum.getText())) {
//                    int foodNum = Integer.parseInt(tvShoppingNum.getText().toString());
//                    if (beforeNumber == 0 && number > 0) {
//                        setFoodNum(foodNum + 1);
//                    } else if (beforeNumber > 0 && number <= 0) {
//                        setFoodNum(foodNum - 1);
//                    }
//                } else {
//                    setFoodNum(1);
//                }
//                int size = foodListAdapter.getIntegerMap().size();
//                if (beforeNumber == 0 && number > 0) {
//                    setFoodNum(size + 1);
//                } else if (number <= 0) {
//                    setFoodNum(size - 1);
//                }
//            });
        }
    }

    /**
     * 修改食品數量顯示
     *
     * @param size
     */
    private void setFoodNum(int size) {
//        if (size > 0) {
//            tvShoppingNum.setVisibility(View.VISIBLE);
//        } else {
//            tvShoppingNum.setVisibility(View.GONE);
//        }
//        tvShoppingNum.setText(String.valueOf(size));
    }

    @Override
    public void onDeleteFoodSuccess(int position) {
        foodListAdapter.removeAt(position);
        if (foodListAdapter.getItemCount() <= 0) {
            loadService.showCallback(EmptyCallback.class);
        }
    }

    private OrderCategoryAdapter orderCategoryAdapter;
    private OrderCategoryAdapter secondCategoryAdapter;

    @Override
    public void loadCategory(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (foodCategoryTrees.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showSuccess();
            initPrimaryAdapter(foodCategoryTrees);
            orderCategoryAdapter.setOnSecondCategoryClickListener((foodCategoryTrees1, position) -> {
                //當前分類顯示的是一級分類和二級分類，二級分類的點擊事件
                //點擊二級分類時，隱藏一級和二級，顯示二級和三級分類數據
                if (orderCategoryAdapter.getCurrentLevelCategory() == OrderCategoryAdapter.PRIMARY_CATEGORY) {
                    currentLevelCategory = OrderCategoryAdapter.SECOND_CATEGORY;
                    setCurrentCategoryInfo(foodCategoryTrees1.get(position), OrderCategoryAdapter.SECOND_CATEGORY);
                    getFoodsByCategoryId();
                    initSecondAdapter(foodCategoryTrees1, position);
                }
            });
        }
    }

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

    @Override
    public void setCurrentSupplierName(String name) {
        currentSupplierName = name;
    }

    /**
     * 設置當前分類信息
     */
    private void setCurrentCategoryInfo(OrderCategoryBean.FoodCategoryTrees foodCategoryTrees, int level) {
        currentCategoryName = foodCategoryTrees.getName();
        categoryId = foodCategoryTrees.getId();
//        RxJavaUtils.doInIOThread(new RxIOTask<Object>(0) {
//            @Override
//            public Void doInIOThread(Object o) {
//                categoryId = foodCategoryTrees.getId();
//                if (categoryNames == null) {
//                    categoryNames = new ArrayList<>();
//                }
//                //將所選的一級。二級。三級分類都保存下來，新建食品時用到
//                if (level == OrderCategoryAdapter.PRIMARY_CATEGORY) {
//                    //切换到一級分類
//                    categoryNames.clear();
//                    categoryNames.add(foodCategoryTrees.getName());
//                } else if (level == OrderCategoryAdapter.SECOND_CATEGORY) {
//                    if (categoryNames.size() > 0) {
//                        //有一級分類
//                        String primaryCateName = categoryNames.get(0);
//                        categoryNames.clear();
//                        categoryNames.add(primaryCateName);
//                        categoryNames.add(foodCategoryTrees.getName());
//                    }
//                } else if (level == OrderCategoryAdapter.THIRD_CATEGORY) {
//                    if (categoryNames.size() > 2) {
//                        //有三級分類
//                        categoryNames.set(2, foodCategoryTrees.getName());
//                    } else if (categoryNames.size() == 2) {
//                        //有二級分類
//                        categoryNames.add(foodCategoryTrees.getName());
//                    }
//                }
//                return null;
//            }
//        });
    }

    private void initSecondAdapter
            (List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees, int position) {
        if (secondCategoryAdapter == null) {
            secondCategoryAdapter = new OrderCategoryAdapter(mContext, foodCategoryTrees);
            secondCategoryAdapter.setCurrentLevelCategory(OrderCategoryAdapter.SECOND_CATEGORY);
            secondCategoryAdapter.setOnItemChildClickListener((a, v, p) -> {
                //點擊返回，隱藏二級和三級分類，顯示一級和二級分類
                if (v.getId() == R.id.layout_order_category_back) {
                    showPrimaryCategory(View.GONE, View.VISIBLE);
                    currentLevelCategory = OrderCategoryAdapter.PRIMARY_CATEGORY;
                }
            });
            secondCategoryAdapter.setOnItemClickListener((adapter1, view1, secondPosition) -> {
                //當前分類顯示的是二級分類和三級分類，二級分類的點擊事件
                List<OrderCategoryBean.FoodCategoryTrees> data = secondCategoryAdapter.getData();
                secondCategoryAdapter.setSelectIndex(secondPosition);
                setCurrentCategoryInfo(data.get(secondPosition), OrderCategoryAdapter.SECOND_CATEGORY);
                getFoodsByCategoryId();
            });
            secondCategoryAdapter.setOnSecondCategoryClickListener((foodCategoryTrees1, thirdPosition) -> {
                //當前分類顯示的是二級分類和三級分類，三級分類的點擊事件
                setCurrentCategoryInfo(foodCategoryTrees1.get(thirdPosition), OrderCategoryAdapter.THIRD_CATEGORY);
                getFoodsByCategoryId();
            });
            rvSecondCategory.setAdapter(secondCategoryAdapter);
        } else {
            secondCategoryAdapter.setNewInstance(foodCategoryTrees);
        }
        //設置選中
        secondCategoryAdapter.setSelectIndex(position);
        showPrimaryCategory(View.VISIBLE, View.GONE);
    }

    /**
     * 切換一級分類和二級分類顯示
     *
     * @param secondVisible 二級分類顯示狀態
     * @param visible       一級分類顯示狀態
     */
    private void showPrimaryCategory(int secondVisible, int visible) {
        rvSecondCategory.setVisibility(secondVisible);
        rvLeftCategory.setVisibility(visible);
    }

    /**
     * 初始化一級分類
     *
     * @param foodCategoryTrees 分類數據
     */
    private void initPrimaryAdapter
    (List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        loadService.showSuccess();
        if (orderCategoryAdapter == null) {
            orderCategoryAdapter = new OrderCategoryAdapter(mContext, foodCategoryTrees);
        } else {
            orderCategoryAdapter.setNewInstance(foodCategoryTrees);
        }
        rvLeftCategory.setAdapter(orderCategoryAdapter);
        orderCategoryAdapter.setOnItemClickListener((adapter, view, position) -> {
            //當頁面顯示的是一級分類和二級分類時，一級分類的點擊事件
            //點擊之後顯示一級分類和所屬的二級分類
            setCurrentCategoryInfo(foodCategoryTrees.get(position), OrderCategoryAdapter.PRIMARY_CATEGORY);
            getFoodsByCategoryId();
            orderCategoryAdapter.setSelectIndex(position);
        });
        if (categoryId == -1 && orderCategoryAdapter.getItemCount() > 0) {
            //第一次進來，獲取默認的數據
            orderCategoryAdapter.getOnItemClickListener().onItemClick(orderCategoryAdapter, null, 0);
        }
        if (orderCategoryAdapter.getSelectIndex() != -1) {
            setCurrentCategoryInfo(foodCategoryTrees.get(orderCategoryAdapter.getSelectIndex()), OrderCategoryAdapter.PRIMARY_CATEGORY);
            getFoodsByCategoryId();
        }
    }

    /**
     * @return 當前選中的分類名
     */
    public String getCurrentCategory() {
        return currentCategoryName;
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == EDIT_FOOD_REQUEST_CODE && resultCode == EDIT_FOOD_RESULT_CODE) {
            //編輯食材後，判斷新增的食材是否在當前選中的分類或者供應商裡，如果是則刷新，如果不是，則將該供應商和分類下的緩存刪除掉
            if (data != null) {
                //獲取新增食材的所屬供應商
                String supplierName = data.getString(NewFoodIngredientsFragment.SUPPLIER_NAME_KEY);
                //獲取新增食材的分類名
                String categoryName = data.getString(NewFoodIngredientsFragment.CATEGORY_NAME_KEY);
                //從供應商的數據中將緩存移除掉，並拿到這個食材所屬的供應商
                int removeSupplierId = mPresenter.removeSupplierCache(supplierName);
                //當前頁面顯示的供應商緩存也要移除掉，重新查詢，避免用戶修改了供應商或者分類
                mPresenter.removeSupplierCacheById(supplierId);
                //從分類的數據中將緩存移除掉
                mPresenter.removeCacheByCategoryName(categoryName);
                //如果所屬供應商是當前選中的供應商，則調用接口重新獲取數據
                if (isSupplier) {
                    //根據供應商獲取食材
//                    if (supplierId == removeSupplierId) {
                    getFoodsBySupplierId();
//                    }
                } else if (TextUtil.isNotEmptyOrNullOrUndefined(getCurrentCategory())) {
                    //當前分類不為空
                    //新建食材的分類不為空，並且新建食材的分類和當前選中的分類一致，那麼就刷新數據
//                    if (TextUtil.isNotEmptyOrNullOrUndefined(categoryName) && categoryName.equals(getCurrentCategory())) {
                    //重新獲取當前分類下的數據
                    getFoodsByCategoryId();
//                    }
                }
            }
        }
    }
}
