package com.gingersoft.supply_chain.mvp.presenter;

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

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.CategoryFoodTreeBean;
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.bean.ShoppingCartBean;
import com.gingersoft.supply_chain.mvp.content.Constant;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.FoodIngredientsContract;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxAsyncTask;
import com.xuexiang.rxutil2.rxjava.task.RxIOTask;
import com.xuexiang.rxutil2.rxjava.task.RxUITask;

import org.jetbrains.annotations.NotNull;

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

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/24/2020 15:28
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class FoodIngredientsPresenter extends BasePresenter<FoodIngredientsContract.Model, FoodIngredientsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    /**
     * key為供應商ID，
     * 集合是對應的食品
     * 如果通過在map中有食品，就不用再次調用接口
     */
    private Map<Integer, List<PurchaseFoodBean>> supplierFoodsMap;
    /**
     * 分類數據，之後通過分類獲取對應下面的食品
     */
    private List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees;
    /**
     * 存儲供應商信息，
     * 只有供應商id和名稱
     * 只有供應商id和名稱
     * 只有供應商id和名稱
     */
    private List<FoodListInfoBean.DataBean> supplierInfo;
    /**
     * 存儲所有分類id和名字，包括下面的所有食材，如果沒有食材，需要調用獲取食材接口然後存放在這個集合裡面
     */
    private List<CategoryFoodTreeBean> categoryFoodTreeBeans;
    /**
     * 供應商列表
     */
    private List<CategoryBean> categoryBeans;

    @Inject
    public FoodIngredientsPresenter(FoodIngredientsContract.Model model, FoodIngredientsContract.View rootView) {
        super(model, rootView);
    }

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

    /**
     * 獲取數據，供應商
     *
     * @param supplierId
     */
    public void loadFoodIngredientsData(int supplierId) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        map.put("restaurantId", RestaurantInfoManager.newInstance().getRestaurantId());
        map.put("brandId", RestaurantInfoManager.newInstance().getBrandId());
        if (supplierId != -1) {
            map.put("supplierId", supplierId);
        }
        mModel.getFoodIngredientsData(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.GET_INFO_LOADING))
                .doAfterTerminate(() -> mRootView.hideLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .observeOn(Schedulers.io())
                .subscribe(new ErrorHandleSubscriber<FoodListInfoBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull FoodListInfoBean info) {
                        if (info.isSuccess() && info.getData() != null) {
                            categoryBeans = new ArrayList<>();
                            if (supplierFoodsMap == null) {
                                supplierFoodsMap = new HashMap<>(5);
                            }
                            if (supplierInfo == null) {
                                supplierInfo = new ArrayList<>();
                            } else {
                                supplierInfo.clear();
                            }
                            supplierInfo.addAll(info.getData());
                            for (FoodListInfoBean.DataBean datum : info.getData()) {
                                //將供應商信息轉為左側用來顯示的數據類型
                                CategoryBean categoryBean = new CategoryBean(datum.getId(), datum.getSupplierName());
                                //將供應商和供應商的食品添加到map中
                                if (datum.getPurchaseFoodListVOS() == null) {
                                    supplierFoodsMap.put(datum.getId(), null);
                                } else {
                                    int totalCount = setFoodCount(datum.getPurchaseFoodListVOS());
                                    categoryBean.setCount(totalCount);
                                    supplierFoodsMap.put(datum.getId(), new ArrayList<>(datum.getPurchaseFoodListVOS()));
                                }
                                categoryBeans.add(categoryBean);
                            }
                            RxJavaUtils.doInUIThread(new RxUITask<Object>(0) {
                                @Override
                                public void doInUIThread(Object o) {
                                    mRootView.loadLeftSupplierInfo(categoryBeans);
                                    if (info.getData().size() > 0) {
                                        mRootView.setCurrentSupplierName(info.getData().get(0).getSupplierName());
                                        mRootView.loadRightFoodIngredients(info.getData().get(0).getPurchaseFoodListVOS());
                                    }
                                }
                            });
                        }
                    }
                });
    }

    public void setCategoryBeans(List<CategoryBean> categoryBeans) {
        this.categoryBeans = categoryBeans;
    }


    public void addToSupplierCacheInfo(int id, String supplierName) {
        if (supplierInfo == null) {
            supplierInfo = new ArrayList<>();
        }
        FoodListInfoBean.DataBean foodBean = new FoodListInfoBean.DataBean();
        foodBean.setId(id);
        foodBean.setSupplierName(supplierName);
        supplierInfo.add(foodBean);
    }

    /**
     * 將購物車中的食品數量填充到列表數據中
     *
     * @param purchaseFoodListVOS
     */
    private int setFoodCount(List<PurchaseFoodBean> purchaseFoodListVOS) {
        //統計當前食品集合中有多少個被選中
        int totalCount = 0;
        for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
            //將購物車中的食品數量同步到當前數據中
            for (PurchaseFoodBean purchaseFoodListVO : purchaseFoodListVOS) {
                if (cartFood.getId().equals(purchaseFoodListVO.getId())) {
                    //購物車裡的食品id和當前的食品id一樣，則將購物車中的食品數量賦值給當前食品
                    purchaseFoodListVO.setFoodQuantity(cartFood.getFoodQuantity());
                    totalCount += cartFood.getFoodQuantity();
                }
            }
        }
        return totalCount;
    }

    /**
     * 獲取數據，供應商
     *
     * @param supplierId
     */
    public void loadFoodsBySupplierId(int supplierId) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        map.put("restaurantId", RestaurantInfoManager.newInstance().getRestaurantId());
        map.put("brandId", RestaurantInfoManager.newInstance().getBrandId());
        if (supplierId != -1) {
            map.put("supplierId", supplierId);
        }
        mModel.getFoodBySupplierId(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取中..."))
                .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);
                            if (purchaseFoodListVOS == null) {
                                supplierFoodsMap.put(supplierId, new ArrayList<>());
                            } else {
                                setFoodCount(purchaseFoodListVOS);
                                supplierFoodsMap.put(supplierId, new ArrayList<>(purchaseFoodListVOS));
                            }
                            mRootView.loadRightFoodIngredients(purchaseFoodListVOS);
                        }
                    }
                });
    }

    /**
     * 根據供應商ID獲取食品
     *
     * @param supplierId
     */
    public void getFoodsBySupplierId(int supplierId) {
        if (supplierFoodsMap == null) {
            supplierFoodsMap = new HashMap<>(5);
        }
        List<PurchaseFoodBean> purchaseFoodBeans = supplierFoodsMap.get(supplierId);
        if (purchaseFoodBeans != null && purchaseFoodBeans.size() > 0) {
            mRootView.loadRightFoodIngredients(new ArrayList<>(purchaseFoodBeans));
        } else {
            loadFoodsBySupplierId(supplierId);
        }
        mRootView.loadLeftSupplierInfo(categoryBeans);
    }

    /**
     * 清除指定供應商的緩存
     *
     * @param supplierName
     * @return
     */
    public int removeSupplierCache(String supplierName) {
        int supplierId = -1;
        if (supplierInfo != null && supplierFoodsMap != null) {
            for (FoodListInfoBean.DataBean dataBean : supplierInfo) {
                if (supplierName.equals(dataBean.getSupplierName())) {
                    supplierId = dataBean.getId();
                    break;
                }
            }
            supplierFoodsMap.remove(supplierId);
        }
        return supplierId;
    }

    /**
     * 清除指定供應商的緩存
     * @return
     */
    public void removeSupplierCacheById(int supplierId) {
        if (supplierFoodsMap != null) {
            List<PurchaseFoodBean> purchaseFoodBeans = supplierFoodsMap.get(supplierId);
            supplierFoodsMap.put(supplierId, null);
        }
    }

    /**
     * 獲取選中的食品，存入購物車
     *
     * @param integerMap 存放食品id和數量的map
     */
    public void getSelectFood(Map<Integer, PurchaseFoodBean> integerMap) {
        for (PurchaseFoodBean purchaseFoodBean : integerMap.values()) {
            if (purchaseFoodBean.getFoodQuantity() <= 0) {
                integerMap.remove(purchaseFoodBean);
            }
        }
        //把購物車的食品清空
        SupplyShoppingCart.getInstance().clear();
        //將本次選擇的添加進去
        SupplyShoppingCart.getInstance().addAllFood(integerMap.values());
    }

    /**
     * 刪除食品
     *
     * @param position
     */
    public void deleteFood(int foodId, int supplierId, int categoryId, int position) {
        mModel.deleteFood(foodId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("刪除中..."))
                .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()) {
                            //需要在供應商和分類的緩存中這個食品移除
                            if (supplierFoodsMap != null) {
                                List<PurchaseFoodBean> purchaseFoodBeans = supplierFoodsMap.get(supplierId);
                                if (purchaseFoodBeans != null && position < purchaseFoodBeans.size()) {
                                    purchaseFoodBeans.remove(position);
                                }
                            }
                            //移除在分類中的緩存
                            removeCacheByCategoryId(categoryId);
                            //移除在購物車中的緩存
                            SupplyShoppingCart.getInstance().removeFoodsByFoodId(foodId);
                            mRootView.onDeleteFoodSuccess(position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage("刪除失敗");
                        }
                    }
                });
    }

    /**
     * 獲取分類的結構：所有分類和分類的子分類都有
     */
    public void getCategoryTrees() {
        if (foodCategoryTrees != null) {
            mRootView.loadCategory(foodCategoryTrees);
            return;
        }
        Map<String, Object> map = new HashMap<>(2);
        Constant.addBrandId(map);
        Constant.addRestaurantId(map);
        mModel.getCategoryTrees(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))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<OrderCategoryBean>(mErrorHandler) {
                    @Override
                    public void onNext(OrderCategoryBean orderCategoryBean) {
                        if (orderCategoryBean.isSuccess()) {
                            if (categoryFoodTreeBeans == null) {
                                categoryFoodTreeBeans = new ArrayList<>();
                            }
                            List<OrderCategoryBean.FoodCategoryTrees> data = orderCategoryBean.getData();
                            if (data != null) {
                                RxJavaUtils.doInIOThread(new RxIOTask<Object>(0) {
                                    @Override
                                    public Void doInIOThread(Object o) {
                                        conversionCategoryTree(data);
                                        return null;
                                    }
                                });
                            }
                            foodCategoryTrees = new ArrayList<>();
                            foodCategoryTrees.addAll(orderCategoryBean.getData());
                            mRootView.loadCategory(orderCategoryBean.getData());
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(orderCategoryBean.getErrMsg())) {
                            mRootView.showMessage(orderCategoryBean.getErrMsg());
                        } else {
                            mRootView.showMessage(Constant.GET_INFO_ERROR);
                        }
                    }

                    /**
                     * 將分類轉換為categoryFoodTreeBeans
                     */
                    private void conversionCategoryTree(List<OrderCategoryBean.FoodCategoryTrees> data) {
                        for (OrderCategoryBean.FoodCategoryTrees category : data) {
                            CategoryFoodTreeBean categoryFoodTreeBean = new CategoryFoodTreeBean();
                            List<Integer> categoryId = new ArrayList<>();
                            List<String> categoryName = new ArrayList<>();
                            categoryId.add(category.getId());
                            categoryName.add(category.getName());
                            if (category.getFoodCategoryTrees() != null) {
                                for (OrderCategoryBean.FoodCategoryTrees secondCategory : category.getFoodCategoryTrees()) {
                                    categoryId.add(secondCategory.getId());
                                    categoryName.add(secondCategory.getName());
                                    if (secondCategory.getFoodCategoryTrees() != null) {
                                        for (OrderCategoryBean.FoodCategoryTrees thirdCategory : secondCategory.getFoodCategoryTrees()) {
                                            categoryId.add(thirdCategory.getId());
                                            categoryName.add(thirdCategory.getName());
                                        }
                                    }
                                }
                            }
                            categoryFoodTreeBean.setCategoryIds(categoryId);
                            categoryFoodTreeBean.setCategoryNames(categoryName);
                            categoryFoodTreeBeans.add(categoryFoodTreeBean);
                        }
                    }
                });
    }

//    private void getCategoryById(){
//        foodCategoryTrees
//    }

    /**
     * 根據分類id移除緩存
     *
     * @param categoryId
     */
    public void removeCacheByCategoryId(int categoryId) {
        if (categoryFoodTreeBeans != null) {
            for (CategoryFoodTreeBean categoryFoodTreeBean : categoryFoodTreeBeans) {
                if (categoryFoodTreeBean.getCategoryIds().contains(categoryId)) {
                    //清空這個分類下所有的食材
                    categoryFoodTreeBean.setFoodInfo(null);
                    break;
                }
            }
        }
    }

    /**
     * 根據分類名字移除緩存
     *
     * @param categoryName 分類名字
     */
    public void removeCacheByCategoryName(String categoryName) {
        RxJavaUtils.doInIOThread(new RxIOTask<String>(categoryName) {
            @Override
            public Void doInIOThread(String name) {
                for (CategoryFoodTreeBean categoryFoodTreeBean : categoryFoodTreeBeans) {
                    if (categoryFoodTreeBean.getCategoryNames().contains(name)) {
//                        int categoryIndex = categoryFoodTreeBean.getCategoryNames().indexOf(name);
                        //清空這個分類下所有的食材
                        categoryFoodTreeBean.setFoodInfo(null);
//                        //重新從接口獲取
//                        if (categoryIndex != -1) {
//                            getFoodByCategory(categoryFoodTreeBean.getCategoryIds().get(categoryIndex));
//                        }
                        break;
                    }
                }
                return null;
            }
        });
    }

    /**
     * 根據分類Id移除緩存
     *
     * @param categoryId 分類名字
     */
    public void removeCacheByCategoryId(Integer categoryId) {
        RxJavaUtils.doInIOThread(new RxIOTask<Integer>(categoryId) {
            @Override
            public Void doInIOThread(Integer categoryId) {
                if (categoryId == null) {
                    return null;
                }
                for (CategoryFoodTreeBean categoryFoodTreeBean : categoryFoodTreeBeans) {
                    if (categoryFoodTreeBean.getCategoryIds().contains(categoryId)) {
//                        int categoryIndex = categoryFoodTreeBean.getCategoryNames().indexOf(name);
                        //清空這個分類下所有的食材
                        categoryFoodTreeBean.setFoodInfo(null);
//                        //重新從接口獲取
//                        if (categoryIndex != -1) {
//                            getFoodByCategory(categoryFoodTreeBean.getCategoryIds().get(categoryIndex));
//                        }
                        break;
                    }
                }
                return null;
            }
        });
    }

    /**
     * 從本地緩存中獲取該分類下得食品，如果沒有，則調用接口獲取
     *
     * @param categoryId 分類id
     */
    public void getFoodCacheByCategory(int categoryId) {
        RxJavaUtils.executeAsyncTask(new RxAsyncTask<Integer, List<PurchaseFoodBean>>(categoryId) {
            @Override
            public List<PurchaseFoodBean> doInIOThread(Integer id) {
                for (CategoryFoodTreeBean categoryFoodTreeBean : categoryFoodTreeBeans) {
                    if (categoryFoodTreeBean.getCategoryIds().contains(id)) {
                        //拿到這個分類的父分類下所有的食材
                        List<PurchaseFoodBean> foodInfo = categoryFoodTreeBean.getFoodInfo();
                        //分類下沒有食材
                        if (foodInfo == null) {
                            //獲取該分類父類下的所有食材
                            getFoodByCategory(categoryFoodTreeBean.getCategoryIds().get(0), categoryId);
                            return null;
                        } else {
                            return filterThisCategoryFood(id, foodInfo);
                        }
                    }
                }
                return null;
            }

            @Override
            public void doInUIThread(List<PurchaseFoodBean> foodBeans) {
                if (foodBeans != null) {
                    //加載這個分類下的數據
                    mRootView.loadRightFoodIngredients(foodBeans);
                }
            }
        });

    }

    /**
     * 篩選出這個分類下的食材
     *
     * @param id       分類id
     * @param foodInfo 所有食材
     * @return 當前分類下的食材
     */
    @NotNull
    private List<PurchaseFoodBean> filterThisCategoryFood(Integer id, List<PurchaseFoodBean> foodInfo) {
        //從所有食材中篩選出自己分類下的食材
        List<PurchaseFoodBean> foods = new ArrayList<>();
        //用於提前終止循環，如果已經拿到過這個分類下的數據，後面沒有這個分類下的數據了，就終止循環
        boolean hasFood = false;
        for (PurchaseFoodBean purchaseFoodBean : foodInfo) {
            if (id.equals(purchaseFoodBean.getFoodCategoryId())) {
                hasFood = true;
                foods.add(purchaseFoodBean);
            } else if (hasFood) {
                break;
            }
        }
        return foods;
    }

    /**
     * 根據分類ID獲取食品
     *
     * @param parentCategoryId
     */
    public void getFoodByCategory(int parentCategoryId, int categoryId) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        Constant.addBrandId(map);
        Constant.addRestaurantId(map);
        map.put("parentId", parentCategoryId);
        mModel.getFoodByCategory(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取中..."))
                .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()) {
                            RxJavaUtils.doInIOThread(new RxIOTask<FoodByCategoryResultBean>(info) {
                                @Override
                                public Void doInIOThread(FoodByCategoryResultBean info) {
                                    //將本次獲取到的食品存入到緩存中
                                    for (CategoryFoodTreeBean categoryFoodTreeBean : categoryFoodTreeBeans) {
                                        if (categoryFoodTreeBean.getCategoryIds().contains(parentCategoryId)) {
                                            categoryFoodTreeBean.setFoodInfo(info.getData());
                                            break;
                                        }
                                    }
                                    return null;
                                }
                            });
                            mRootView.loadRightFoodIngredients(filterThisCategoryFood(categoryId, info.getData()));
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                            mRootView.loadFail();
                        } else {
                            mRootView.loadFail();
                        }
                    }
                });
    }

    /**
     * 刷新頁面數據
     *
     * @param purchaseFoodBeans 當前頁面顯示的食材信息
     * @param integerMap        上次選中的食材
     */
    public void refreshPageData(List<PurchaseFoodBean> purchaseFoodBeans, Map<Integer, PurchaseFoodBean> integerMap) {
        if (purchaseFoodBeans != null) {
            RxJavaUtils.executeAsyncTask2(integer -> {
                        //將顯示的食材和購物車的食材對比，數量
                        for (PurchaseFoodBean purchaseFoodBean : purchaseFoodBeans) {
                            if (purchaseFoodBean.getFoodQuantity() > 0) {
                                boolean hasThisFood = false;
                                for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
                                    if (purchaseFoodBean.getId().equals(cartFood.getId())) {
                                        hasThisFood = true;
                                        purchaseFoodBean.setFoodQuantity(cartFood.getFoodQuantity());
                                        if (integerMap != null) {
                                            PurchaseFoodBean selectFood = integerMap.get(purchaseFoodBean.getId());
                                            if (selectFood != null) {
                                                selectFood.setFoodQuantity(cartFood.getFoodQuantity());
                                            }
                                        }
                                        break;
                                    }
                                }
                                if (!hasThisFood) {
                                    purchaseFoodBean.setFoodQuantity(0);
                                    if (integerMap != null) {
                                        PurchaseFoodBean selectFood = integerMap.get(purchaseFoodBean.getId());
                                        if (selectFood != null) {
                                            selectFood.setFoodQuantity(0);
                                        }
                                    }
                                }
                            }
                        }
                        return "";
                    }
            ).doOnSubscribe(disposable -> mRootView.showLoading("加载中..."))
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .doAfterTerminate(() -> mRootView.hideLoading())
                    .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                    .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                        @Override
                        public void onNext(String value) {
                            mRootView.loadRightFoodIngredients(purchaseFoodBeans);
                        }
                    });
        }
        //刷新供應商下的食材信息
        RxJavaUtils.doInIOThread(new RxIOTask<Integer>(1) {
            @Override
            public Void doInIOThread(Integer id) {
                //將食材和購物車的食材對比，修改數量
                Iterator<Map.Entry<Integer, PurchaseFoodBean>> it = integerMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<Integer, PurchaseFoodBean> next = it.next();
                    boolean hasThisFood = false;
                    for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
                        if (cartFood.getId() == next.getKey()) {
                            if (next.getValue().getFoodQuantity() != cartFood.getFoodQuantity()) {
                                next.getValue().setFoodQuantity(cartFood.getFoodQuantity());
                            }
                            hasThisFood = true;
                            break;
                        }
                    }
                    if (!hasThisFood) {
                        next.getValue().setFoodQuantity(0);
                        it.remove();
                    }
                }
//                for (Map.Entry<Integer, PurchaseFoodBean> entry : integerMap.entrySet()) {
//                    //將上次選中的和購物車中的食材進行對比，修改
//                    boolean hasThisFood = false;
//                    for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
//                        if (cartFood.getId() == entry.getKey()) {
//                            if (entry.getValue().getFoodQuantity() != cartFood.getFoodQuantity()) {
//                                entry.getValue().setFoodQuantity(cartFood.getFoodQuantity());
//                            }
//                            hasThisFood = true;
//                            break;
//                        }
//                    }
//                    if (!hasThisFood) {
//                        entry.getValue().setFoodQuantity(0);
//                        integerMap.remove(entry.getKey());
//                    }
//                }
//                for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
//                    //拿到對應供應商下所有食材
//                    List<PurchaseFoodBean> supplierFoods = supplierFoodsMap.get(cartFood.getSupplierId());
//                    if (supplierFoods != null) {
//                        for (PurchaseFoodBean supplierFood : supplierFoods) {
//                            if (cartFood.getId() == supplierFood.getId()) {
//                                supplierFood.setFoodQuantity(cartFood.getFoodQuantity());
//                                break;
//                            }
//                        }
//                    }
//
//                    //刷新分類下的食材信息
//                    List<PurchaseFoodBean> categoryFoodInfo = null;
//                    for (CategoryFoodTreeBean categoryFoodTreeBean : categoryFoodTreeBeans) {
//                        if (categoryFoodTreeBean.getCategoryIds().contains(cartFood.getFoodCategoryId())) {
//                            categoryFoodInfo = categoryFoodTreeBean.getFoodInfo();
//                            break;
//                        }
//                    }
//                    if (categoryFoodInfo != null) {
//                        for (PurchaseFoodBean categoryFood : categoryFoodInfo) {
//                            if (cartFood.getId() == categoryFood.getId()) {
//                                categoryFood.setFoodQuantity(cartFood.getFoodQuantity());
//                                break;
//                            }
//                        }
//                    }
//                }
                return null;
            }
        });
    }
}
