package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;
import android.util.Log;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.AppConstant;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.mvp.bean.BuyIngredientsBean;
import com.gingersoft.supply_chain.mvp.bean.FoodByCategoryResultBean;
import com.gingersoft.supply_chain.mvp.bean.FoodListInfoBean;
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.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import javax.inject.Inject;

import com.gingersoft.supply_chain.mvp.contract.BuyIngredientsContract;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Description: 選購食材
 */
@FragmentScope
public class BuyIngredientsPresenter extends BasePresenter<BuyIngredientsContract.Model, BuyIngredientsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    /**
     * 分類數據的緩存,之後加載就讀取這裡面的
     */
    private List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees;
    /**
     * 供應商信息轉為分類之後的緩存,之後加載就讀取這裡面的
     */
    private List<OrderCategoryBean.FoodCategoryTrees> supplierTranCategoryCache;
//    /**
//     * 用戶選購的食材列表
//     */
//    private Map<Integer, PurchaseFoodBean> purchaseFoodBeanMap = new HashMap<>();

    /**
     * 分類商品緩存，用於根據一級分類下標獲取下面的分類和食材
     */
    private List<List<BuyIngredientsBean>> categoryFoods = new ArrayList<>();
    /**
     * 供應商商品緩存,根據下標獲取食材和供應商信息
     */
    private List<BuyIngredientsBean> supplierFoods = new ArrayList<>();
    /**
     * 列表顯示的食品，不管是分類還是供應商的商品，都轉換到這個集合中用於顯示到列表中，這個集合就代表列表中所有商品
     */
    private List<BuyIngredientsBean> showFoods = new ArrayList<>();

    @Inject
    public BuyIngredientsPresenter(BuyIngredientsContract.Model model, BuyIngredientsContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    /**
     * 統計食品數量
     */
    public int statisticsFoodQuantity() {
        List<PurchaseFoodBean> cartFoods = SupplyShoppingCart.getInstance().getCartFoods();
        int foodSize = 0;
        for (PurchaseFoodBean cartFood : cartFoods) {
            foodSize += cartFood.getFoodQuantity();
        }
        return foodSize;
    }

    /**
     * 跟據供應商id統計食品數量
     */
    public int statisticsFoodQuantityBySupplierId(int supplierId) {
        List<PurchaseFoodBean> cartFoods = SupplyShoppingCart.getInstance().getCartFoods();
        int foodSize = 0;
        for (PurchaseFoodBean cartFood : cartFoods) {
            if (cartFood.getSupplierId() == supplierId) {
                foodSize += cartFood.getFoodQuantity();
            }
        }
        return foodSize;
    }


    /**
     * 獲取分類的結構：所有分類和分類的子分類都有
     */
    public void getCategoryTrees() {
        if (foodCategoryTrees != null) {
            initCategoryGoodsSize(foodCategoryTrees);
            mRootView.initCategoryInfo(foodCategoryTrees);
            return;
        }
        Map<String, Object> map = new HashMap<>(2);
        AppConstant.addBrandId(map);
        AppConstant.addRestaurantId(map);
        mModel.getCategoryTrees(map)//發送請求
                .subscribeOn(Schedulers.io())//切換到io異步線程
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))//顯示加載提示框
                .subscribeOn(AndroidSchedulers.mainThread())//切換到主線程，上面的提示框就在主線程
                .observeOn(AndroidSchedulers.mainThread())//切換到主線程，隱藏提示框在主線程
                .doAfterTerminate(() -> mRootView.hideLoading())//任務執行完成後，隱藏提示框
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//綁定生命週期，頁面隱藏時斷開請求
                .observeOn(AndroidSchedulers.mainThread())//切換到主線程
                .subscribe(new ErrorHandleSubscriber<OrderCategoryBean>(mErrorHandler) {//mErrorHandler是統一的錯誤處理
                    @Override
                    public void onNext(OrderCategoryBean orderCategoryBean) {//數據處理
                        if (orderCategoryBean.isSuccess()) {
                            List<OrderCategoryBean.FoodCategoryTrees> data = orderCategoryBean.getData();
                            if (data != null) {
                                //將分類食品的list容量設置為一級分類的數量，這樣就不用擔心之後加載不同position的分類數據時，計算位置了
                                categoryFoods = new ArrayList<>(data.size());
                                for (OrderCategoryBean.FoodCategoryTrees ignored : data) {
                                    categoryFoods.add(null);
                                }
                                foodCategoryTrees = new ArrayList<>();
                                foodCategoryTrees.addAll(data);
                            }
                            //第一次加載初始化數量
                            initCategoryGoodsSize(data);
                            mRootView.initCategoryInfo(data);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(orderCategoryBean.getErrMsg())) {
                            mRootView.showMessage(orderCategoryBean.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 根據一級分類獲取下面所有包括子分類的食品
     *
     * @param position      一級分類下標
     * @param categoryTrees 一級分類信息
     * @param addToHead     是否添加到頭部
     */
    public void getFoodByCategory(int position, OrderCategoryBean.FoodCategoryTrees categoryTrees, boolean addToHead, boolean isReset) {
        //先看看這個分類的食材有沒有緩存，沒有緩衝再加載
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        AppConstant.addBrandId(map);
        AppConstant.addRestaurantId(map);
        map.put("parentId", categoryTrees.getId());
        mModel.getFoodByCategory(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
//                    mRootView.showLoading(Constant.GET_INFO_LOADING)
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterNext(dis -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodByCategoryResultBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull FoodByCategoryResultBean info) {
                        if (info.isSuccess()) {
                            //拿到所有食品
                            List<PurchaseFoodBean> foodBeans = info.getData();
                            //初始化分類和食品的顯示集合
                            List<BuyIngredientsBean> buyIngredientsBeans = new ArrayList<>();
                            conversionShowInfo(foodBeans, categoryTrees, buyIngredientsBeans, 0);
                            //將數據插入緩衝中
                            categoryFoods.set(position, buyIngredientsBeans);
                            if (addToHead) {
                                showFoods.addAll(0, buyIngredientsBeans);
                            } else {
                                showFoods.addAll(buyIngredientsBeans);
                            }
                            mRootView.loadFood(buyIngredientsBeans, addToHead, isReset);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                            mRootView.loadFail();
                        } else {
                            mRootView.loadFail();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }

                    /**
                     * 將食品數據，分類信息進行合併轉換處理
                     *
                     * @param foodBeans           食品信息
                     * @param foodCategoryTree    分類
                     * @param buyIngredientsBeans 遞歸用到，這個分類轉換後的
                     * @param foodSize            遞歸用到的數量，用於記錄遍歷了多少個食品
                     */
                    private void conversionShowInfo(List<PurchaseFoodBean> foodBeans, OrderCategoryBean.FoodCategoryTrees foodCategoryTree, List<BuyIngredientsBean> buyIngredientsBeans, int foodSize) {
                        BuyIngredientsBean buyIngredientsBean = new BuyIngredientsBean();
                        buyIngredientsBean.id = foodCategoryTree.getId();
                        buyIngredientsBean.parentId = foodCategoryTree.getParentId();
                        buyIngredientsBean.categoryName = foodCategoryTree.getName();
                        buyIngredientsBean.purchaseFoodList = new ArrayList<>();
                        if (foodBeans != null && foodSize != foodBeans.size()) {
                            boolean haveThisCategoryBean = true;
                            int categoryFoodSize = 0;
                            for (PurchaseFoodBean foodBean : foodBeans) {
                                //將食品按分類隔開
                                PurchaseFoodBean cachePurchaseFoodBean = SupplyShoppingCart.getInstance().getFoodByFoodId(foodBean.getId());
                                if (cachePurchaseFoodBean != null) {
                                    foodBean.setFoodQuantity(cachePurchaseFoodBean.getFoodQuantity());
                                    categoryFoodSize++;
                                }
                                if (foodBean.getFoodCategoryId() == foodCategoryTree.getId()) {
                                    buyIngredientsBean.purchaseFoodList.add(foodBean);
                                    haveThisCategoryBean = false;
                                    foodSize++;
                                } else if (!haveThisCategoryBean) {
                                    //因為食品是按順序排列，如果之前已經有這個分類的食品，後來沒了，之後的數據就不用遍歷了
                                    break;
                                }
                            }
                            foodCategoryTree.setSize(categoryFoodSize);
                        }
                        buyIngredientsBeans.add(buyIngredientsBean);
                        List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees = foodCategoryTree.getFoodCategoryTrees();
                        //遍歷子分類
                        if (foodCategoryTrees != null) {
                            for (OrderCategoryBean.FoodCategoryTrees categoryTree : foodCategoryTrees) {
                                conversionShowInfo(foodBeans, categoryTree, buyIngredientsBeans, foodSize);
                            }
                        }
                    }
                });
    }

    /**
     * 初始化分類商品數量
     *
     * @param foodCategoryTrees 所有分類
     */
    public void initCategoryGoodsSize(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        //先將食品數量置0
        for (OrderCategoryBean.FoodCategoryTrees foodCategoryTree : foodCategoryTrees) {
            foodCategoryTree.setSize(0);
        }
        for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
            int size = foodCategoryTrees.size();
            for (int i = 0; i < size; i++) {
                OrderCategoryBean.FoodCategoryTrees categoryTrees = foodCategoryTrees.get(i);
                if (cartFood.getFoodCategoryId() == categoryTrees.getId()) {
                    categoryTrees.setSize(categoryTrees.getSize() + 1);
                    break;
                } else {
                    initCategorySize(categoryTrees, categoryTrees.getFoodCategoryTrees(), cartFood);
                }
            }
        }
    }

    /**
     * 遞歸多級分類，統計食品在分類下的數量，最後都計在父分類下
     *
     * @param parentFoodCategory 父分類
     * @param foodCategoryTrees  子分類
     * @param value              商品
     */
    public void initCategorySize(OrderCategoryBean.FoodCategoryTrees parentFoodCategory, List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees, PurchaseFoodBean value) {
        if (CollectionUtils.isNotNullOrEmpty(foodCategoryTrees)) {
            //遍歷二級，找到這個食品
            int size = foodCategoryTrees.size();
            for (int i = 0; i < size; i++) {
                OrderCategoryBean.FoodCategoryTrees categoryTrees = foodCategoryTrees.get(i);
                if (value.getFoodCategoryId() == categoryTrees.getId()) {
                    parentFoodCategory.setSize(parentFoodCategory.getSize() + 1);
                    categoryTrees.setSize(categoryTrees.getSize() + 1);
                    break;
                } else {
                    initCategorySize(parentFoodCategory, categoryTrees.getFoodCategoryTrees(), value);
                }
            }
        }
    }

    /**
     * 獲取數據，供應商
     *
     * @param supplierId 供應商id, -1就是加載所有供應商
     */
    public void loadFoodIngredientsData(int supplierId, boolean isReset) {
        if (supplierTranCategoryCache != null) {
            //如果有緩存,直接加載緩存的,需要和用戶已採購食材合併數量
            initSupplierGoodsSize(supplierTranCategoryCache);
            mRootView.initCategoryInfo(supplierTranCategoryCache);
            return;
        }
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        AppConstant.addBrandId(map);
        AppConstant.addRestaurantId(map);
        if (supplierId != -1) {
            map.put("supplierId", supplierId);
        }
        mModel.getFoodIngredientsData(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodListInfoBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull FoodListInfoBean info) {
                        if (info.isSuccess() && info.getData() != null) {
                            List<FoodListInfoBean.DataBean> data = info.getData();
                            if (data != null) {
                                initSupplierFoods(data.size());
                                supplierTranCategoryCache = new ArrayList<>(data.size());
                                //將顯示的商品列表清空
                                clearShowFoods();
                                //遍歷供應商，這裡接口返回了第一個供應商的食品信息，添加進去、
                                // 其他供應商先佔位，設為空
                                int size = data.size();
                                for (int i = 0; i < size; i++) {
                                    FoodListInfoBean.DataBean dataBean = data.get(i);
                                    OrderCategoryBean.FoodCategoryTrees supplierToCategory = new OrderCategoryBean.FoodCategoryTrees(dataBean.getId(), dataBean.getSupplierName(), 0);
                                    if (i == 0) {
                                        BuyIngredientsBean buyIngredientsBean = conversionSupplierToShowInfo(supplierToCategory, dataBean.getPurchaseFoodListVOS());
                                        showFoods.add(buyIngredientsBean);
                                        supplierFoods.set(i, buyIngredientsBean);
                                    } else {
                                        supplierFoods.set(i, null);
                                    }
                                    supplierTranCategoryCache.add(supplierToCategory);
                                }
                                //第一次需要初始化每個供應商下已採購的食品數量
                                initSupplierGoodsSize(supplierTranCategoryCache);
                                mRootView.initCategoryInfo(supplierTranCategoryCache);
                                loadFood(showFoods.get(0), false, true);
                            }
                        }
                    }
                });
    }

    /**
     * 初始化供應商的分類的商品數量
     *
     * @param foodCategoryTrees 分類，供應商也是分類
     */
    private void initSupplierGoodsSize(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        //先將食品數量置0
        for (OrderCategoryBean.FoodCategoryTrees foodCategoryTree : foodCategoryTrees) {
            foodCategoryTree.setSize(0);
        }
        for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
            int size = foodCategoryTrees.size();
            for (int i = 0; i < size; i++) {
                OrderCategoryBean.FoodCategoryTrees categoryTrees = foodCategoryTrees.get(i);
                if (cartFood.getSupplierId() == categoryTrees.getId()) {
                    categoryTrees.setSize(categoryTrees.getSize() + 1);
                }
            }
        }
    }

    /**
     * 將供應商食材和用戶已點的食材數量合併
     *
     * @param supplierToCategory  供應商信息
     * @param purchaseFoodListVOS 供應商食材信息
     * @return 用於顯示的信息
     */
    private BuyIngredientsBean conversionSupplierToShowInfo(OrderCategoryBean.FoodCategoryTrees supplierToCategory, List<PurchaseFoodBean> purchaseFoodListVOS) {
        //這裡已經返回了第一個供應商的商品
        BuyIngredientsBean buyIngredientsBean = new BuyIngredientsBean();
        buyIngredientsBean.id = supplierToCategory.getId();
        buyIngredientsBean.categoryName = supplierToCategory.getName();
        if (CollectionUtils.isNotNullOrEmpty(purchaseFoodListVOS)) {
            int foodSize = 0;
            for (PurchaseFoodBean foodBean : purchaseFoodListVOS) {
                //將食品按分類隔開
                PurchaseFoodBean cachePurchaseFoodBean = SupplyShoppingCart.getInstance().getFoodByFoodId(foodBean.getId());
                if (cachePurchaseFoodBean != null) {
                    foodBean.setFoodQuantity(cachePurchaseFoodBean.getFoodQuantity());
                    foodSize++;
                }
            }
            supplierToCategory.setSize(foodSize);
        }
        buyIngredientsBean.purchaseFoodList = purchaseFoodListVOS;
        return buyIngredientsBean;
    }

    /**
     * 獲取數據，供應商
     *
     * @param position          供應商下標
     * @param foodCategoryTrees 供應商轉換為分類後的信息
     */
    public void getFoodsBySupplier(int position, OrderCategoryBean.FoodCategoryTrees foodCategoryTrees, boolean addToHead, boolean isReset) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        AppConstant.addBrandId(map);
        AppConstant.addRestaurantId(map);
        if (foodCategoryTrees != null) {
            map.put("supplierId", foodCategoryTrees.getId());
        }
        mModel.getFoodBySupplierId(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    //mRootView.showLoading(Constant.GET_INFO_LOADING)
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                    //mRootView.hideLoading()
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info.isSuccess() && info.getData() != null) {
                            List<PurchaseFoodBean> purchaseFoodListVOS = JsonUtils.parseArray(info.getData(), PurchaseFoodBean.class);
                            BuyIngredientsBean buyIngredientsBean = conversionSupplierToShowInfo(foodCategoryTrees, purchaseFoodListVOS);
                            supplierFoods.set(position, buyIngredientsBean);
                            showFoods.add(addToHead ? 0 : showFoods.size(), buyIngredientsBean);
                            loadFood(buyIngredientsBean, addToHead, isReset);
                        }
                    }
                });
    }

    private void loadFood(BuyIngredientsBean buyIngredientsBean, boolean addToHead, boolean isReset) {
        ArrayList<BuyIngredientsBean> buyIngredientsBeans = new ArrayList<>();
        buyIngredientsBeans.add(buyIngredientsBean);
        mRootView.loadFood(buyIngredientsBeans, addToHead, isReset);
    }

    /**
     * 刪除食品
     *
     * @param categoryPosition 分類在一級分類的位置，用戶如果現在顯示的是供應商，則值為-1
     * @param groupPosition    組下標
     * @param position         在組中的下標
     */
    public void deleteFood(int foodId, int categoryPosition, int groupPosition, int position) {
        mModel.deleteFood(foodId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.DELETE_LOADING))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterNext(dis -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            //需要在供應商和分類的緩存中這個食品移除
//                            categoryFoods
//                                    supplierFoods
                            //列表中刪除掉這個食品
                            showFoods.get(groupPosition).purchaseFoodList.remove(position);
                            //移除在購物車中的緩存
                            SupplyShoppingCart.getInstance().removeFoodsByFoodId(foodId);
                            //刷新頁面
                            mRootView.loadFood(new ArrayList<>(showFoods), true, true);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.DELETE_FAIL);
                        }
                    }
                });
    }

    /**
     * 如果頁面單是顯示一個供應商食材，那麼外部就要調用到這個，長度設置為一
     */
    public void initSupplierFoods(int length) {
        supplierFoods = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            supplierFoods.add(null);
        }
    }

    /**
     * @return 用戶採購的食材
     */
    public List<PurchaseFoodBean> getPurchaseFood() {
        return SupplyShoppingCart.getInstance().getCartFoods();
    }

    /**
     * 添加食品到採購map中
     *
     * @param purchaseFoodBean 採購的食品
     */
    public void addFood(PurchaseFoodBean purchaseFoodBean) {
        if (purchaseFoodBean.getFoodQuantity() == 0) {
            SupplyShoppingCart.getInstance().removeFoodsByFoodId(purchaseFoodBean.getId());
        } else {
            SupplyShoppingCart.getInstance().addFood(purchaseFoodBean);
        }
    }

    /**
     * 清除顯示的食材
     */
    public void clearShowFoods() {
        showFoods.clear();
    }

    /**
     * 清除分類食材緩存
     */
    public void clearCategoryFoods() {
        int size = categoryFoods.size();
        for (int i = 0; i < size; i++) {
            categoryFoods.set(i, null);
        }
    }

    public void clearCategoryTreesCache() {
        foodCategoryTrees = null;
    }

    /**
     * 清除供應商食材緩存
     */
    public void clearSupplierFoods() {
        int size = supplierFoods.size();
        for (int i = 0; i < size; i++) {
            supplierFoods.set(i, null);
        }
    }

    public void clearSupplierCache() {
        supplierTranCategoryCache = null;
    }

    /**
     * 判斷是否有本地緩存
     *
     * @param isSupplier 是否查供應商
     * @param position   分類下標
     * @return true 有緩存
     */
    public boolean isHasLocationInfo(boolean isSupplier, int position) {
        if (isSupplier) {
            if (position >= supplierFoods.size()) {
                return false;
            }
            return supplierFoods.get(position) != null;
        } else {
            if (position >= categoryFoods.size()) {
                return false;
            }
            return categoryFoods.get(position) != null;
        }
    }

    /**
     * 判斷這個分類的數據是否已經加載到顯示列表中了
     *
     * @param foodCategoryTrees 分類
     * @return 這個分類在列表中的下標
     */
    public int isShowGoods(OrderCategoryBean.FoodCategoryTrees foodCategoryTrees) {
        return showFoods.indexOf(new BuyIngredientsBean(foodCategoryTrees.getId(), foodCategoryTrees.getName(), foodCategoryTrees.getParentId()));
    }

    /**
     * 根據分類的下標獲取在食品列表中的下標
     *
     * @param categoryIndex 分類下標
     * @return 食品列表中的下標
     */
    public int getFoodIndexByCategoryIndex(int categoryIndex) {
        int progress = 0;
        for (int i = 0; i < showFoods.size(); i++) {
            if (i >= categoryIndex) {
                return progress;
            } else {
                progress += showFoods.get(i).purchaseFoodList.size() + 1;
            }
        }
        return progress;
    }

    /**
     * 加載下一個分類的數據。如果已加載，則是後面的未加載的分類下標，如果未加載，就是這個未加載的分類下標
     *
     * @param position          分類下標
     * @param foodCategoryTrees 分類
     */
    public void loadNextCategoryFood(boolean isSupplier, int position, List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        List<BuyIngredientsBean> buyIngredientsBeans = null;
        if (isSupplier) {
            if (supplierFoods.get(position) != null) {
                buyIngredientsBeans = new ArrayList<>();
                buyIngredientsBeans.add(supplierFoods.get(position));
            }
        } else {
            buyIngredientsBeans = categoryFoods.get(position);
        }
        if (CollectionUtils.isNotNullOrEmpty(buyIngredientsBeans)) {
            Log.e("eee", "loadNextCategoryFood不為空");
            //判斷是否已經加載到列表中了，如果已經加載到列表中，那麼就加載下一個
            if (showFoods.contains(buyIngredientsBeans.get(0))) {
                Log.e("eee", "loadNextCategoryFood已加載");
                position++;
                int size;
                if (isSupplier) {
                    size = supplierFoods.size();
                } else {
                    size = categoryFoods.size();
                }
                if (position < size) {
                    Log.e("eee", "下一個");
                    loadNextCategoryFood(isSupplier, position, foodCategoryTrees);
                } else {
                    mRootView.finishLoad(true);
                }
            } else {
                Log.e("eee", "loadNextCategoryFood未加載");
                //加載
//                mRootView.selectFirstCategoryByIndex(position);
                if (isHasLocationInfo(isSupplier, position)) {
                    loadCacheFood(isSupplier, position, false, false);
                } else {
                    if (isSupplier) {
                        getFoodsBySupplier(position, foodCategoryTrees.get(position), false, false);
                    } else {
                        getFoodByCategory(position, foodCategoryTrees.get(position), false, false);
                    }
                }
            }
        } else {
            if (isSupplier) {
                getFoodsBySupplier(position, foodCategoryTrees.get(position), false, false);
            } else {
                Log.e("eee", "loadNextCategoryFood為空");
                getFoodByCategory(position, foodCategoryTrees.get(position), false, false);
            }
        }

    }


    /**
     * 根據分類的下標獲得他的一級分類
     *
     * @param index 分類下標
     */
    public BuyIngredientsBean getFirstCategoryByIndex(int index) {
        if (index >= showFoods.size()) {
            return null;
        }
        BuyIngredientsBean buyIngredientsBean = showFoods.get(index);
        boolean isParent = buyIngredientsBean.parentId == 0;
        for (int i = index; i > -1; i--) {
            BuyIngredientsBean data = showFoods.get(i);
            if (isParent && data.id == buyIngredientsBean.id) {
                //是父分類
                return data;
            } else if (data.id == buyIngredientsBean.parentId) {
                //子分類
                if (data.parentId == 0) {
                    return data;
                } else {
                    return getFirstCategoryByIndex(i);
                }
            }
        }
        return null;
    }

    /**
     * 加載緩存中的商品
     *
     * @param position  分類下標
     * @param addToHead 是否添加到頭部
     */
    public void loadCacheFood(boolean isSupplier, int position, boolean addToHead, boolean isReset) {
        if (isSupplier) {
            BuyIngredientsBean buyIngredientsBean = supplierFoods.get(position);
            if (buyIngredientsBean != null) {
                if (showFoods.contains(buyIngredientsBean)) {
                    //如果列表中已经有这个分类的数据，则加载上一个分类
                    position -= 1;
                    if (position >= 0 && position < categoryFoods.size()) {
                        loadCacheFood(isSupplier, position, addToHead, isReset);
                    } else {
                        mRootView.finishLoad(false);
                    }
                } else {
                    Log.e("eee", "加载供應商缓存");
                    List<BuyIngredientsBean> food = new ArrayList<>();
                    food.add(supplierFoods.get(position));
                    if (addToHead) {
                        showFoods.addAll(0, food);
                    } else {
                        showFoods.addAll(food);
                    }
                    mRootView.loadFood(food, addToHead, isReset);
                }
            } else {
                Log.e("eee", "没有供應商缓存" + position);
                //需要通过接口
                getFoodsBySupplier(position, supplierTranCategoryCache.get(position), addToHead, isReset);
            }
        } else {
            List<BuyIngredientsBean> buyIngredientsBeans = categoryFoods.get(position);
            if (CollectionUtils.isNotNullOrEmpty(buyIngredientsBeans)) {
                if (showFoods.contains(buyIngredientsBeans.get(0))) {
                    //如果列表中已经有这个分类的数据，则加载上一个分类
                    position -= 1;
                    if (position >= 0 && position < categoryFoods.size()) {
                        loadCacheFood(isSupplier, position, addToHead, isReset);
                    } else {
                        mRootView.finishLoad(false);
                    }
                } else {
                    Log.e("eee", "加载分类缓存");
                    if (addToHead) {
                        showFoods.addAll(0, categoryFoods.get(position));
                    } else {
                        showFoods.addAll(categoryFoods.get(position));
                    }
                    mRootView.loadFood(categoryFoods.get(position), addToHead, isReset);
                }
            } else {
                Log.e("eee", "没有分类缓存" + position);
                //需要通过接口
                getFoodByCategory(position, foodCategoryTrees.get(position), addToHead, isReset);
            }
        }
    }


    /**
     * 在所有食材中獲取分類下標
     *
     * @param allShowFood   所以顯示的食材
     * @param categoryTrees 分類
     * @return 下標
     */
    public int getIndexInAllFood(List<BuyIngredientsBean> allShowFood, OrderCategoryBean.FoodCategoryTrees categoryTrees) {
        //從一層中找到當前分類的位置
        int index = allShowFood.indexOf(new BuyIngredientsBean(categoryTrees.getId(), categoryTrees.getName(), categoryTrees.getParentId()));
        int position = index;
        for (int i = 0; i < index; i++) {
            position += allShowFood.get(i).purchaseFoodList.size();
        }
        return position;
    }
}
