package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
import com.gingersoft.supply_chain.mvp.bean.CategoryFoodTreeBean;
import com.gingersoft.supply_chain.mvp.bean.FoodByCategoryResultBean;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.content.Constant;
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 lombok.val;
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 com.qmuiteam.qmui.widget.section.QMUISection;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxIOTask;

import org.jetbrains.annotations.NotNull;

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;
    /**
     * 存儲所有分類id和名字，包括下面的所有食材，如果沒有食材，需要調用獲取食材接口然後存放在這個集合裡面
     * 之後點擊一個分類，可以通過這個集合去拿到之前已經通過接口獲取到的食材信息
     * <p>
     * 用於快速獲取某個分類下的食材
     */
    private List<CategoryFoodTreeBean> categoryFoodTreeBeans;

    private Map<Integer, List<QMUISection<CategoryBean, PurchaseFoodBean>>> foodSectionMap = new HashMap<>();

    @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 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();
                            conversionCategoryTree(data);
                            foodCategoryTrees = new ArrayList<>();
                            foodCategoryTrees.addAll(data);
                            mRootView.loadCategory(data);
                        } 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) {
                        if (data == null) {
                            return;
                        }
                        RxJavaUtils.doInIOThread(new RxIOTask<Object>(0) {
                            @Override
                            public Void doInIOThread(Object o) {
                                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);
                                }
                                return null;
                            }
                        });
                    }
                });
    }

    public void getFoodByCategoryId() {
    }

    /**
     * 根據一級分類獲取下面所有包括子分類的食品
     *
     * @param parentCategoryId 父分類id
     */
    public void getFoodByCategoryId(int parentCategoryId) {
        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()) {
                            //保存分類下食品
                            savFoodToCategory(info);
                            //這個接口是一級分類才調用，所以直接顯示所有食材，讓用戶可以滾動列表
                            //將食品和分類整合到一起,List<QMUISection<CategoryBean, PurchaseFoodBean>>
                            val sections = foodToList(info.getData());
                            foodSectionMap.put(parentCategoryId, sections);
                            mRootView.loadFood(sections);
//                            mRootView.loadRightFoodIngredients(filterThisCategoryFood(categoryId, info.getData()));
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                            mRootView.loadFail();
                        } else {
                            mRootView.loadFail();
                        }
                    }

                    /**
                     *  保存食品信息到分類數據中
                     * @param info
                     */
                    private void savFoodToCategory(@NonNull FoodByCategoryResultBean info) {
                        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;
                            }
                        });
                    }
                });
    }

    /**
     * 將食品列表轉為帶分類用於顯示的列表
     *
     * @return
     */
    public List<QMUISection<CategoryBean, PurchaseFoodBean>> foodToList(List<PurchaseFoodBean> data) {
        if (data == null) {
            return null;
        }
        List<QMUISection<CategoryBean, PurchaseFoodBean>> sections = new ArrayList<>();
        CategoryBean categoryBean = new CategoryBean();
        List<PurchaseFoodBean> purchaseFoodBeans = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            PurchaseFoodBean purchaseFoodBean = data.get(i);
            if (categoryBean.getId() == null) {
                categoryBean.setId(purchaseFoodBean.getFoodCategoryId());
            } else {
                if (!categoryBean.getId().equals(purchaseFoodBean.getFoodCategoryId())) {
                    sections.add(new QMUISection<>(categoryBean, purchaseFoodBeans));
                    categoryBean = new CategoryBean();
                    categoryBean.setId(purchaseFoodBean.getFoodCategoryId());
                    purchaseFoodBeans = new ArrayList<>();
                }
            }
            purchaseFoodBeans.add(purchaseFoodBean);
            if (i == data.size() - 1) {
                //最後一個食品
                sections.add(new QMUISection<>(categoryBean, purchaseFoodBeans));
            }
        }
        //由於食的數據中沒有分類名稱，需要去分類的緩存中取出對應的分類名
        for (QMUISection<CategoryBean, PurchaseFoodBean> section : sections) {
            CategoryBean header = section.getHeader();
            for (CategoryFoodTreeBean categoryFoodTreeBean : categoryFoodTreeBeans) {
                if (categoryFoodTreeBean.getCategoryIds().contains(header.getId())) {
                    header.setCategoryName(categoryFoodTreeBean.getCategoryNames().get(categoryFoodTreeBean.getCategoryIds().indexOf(header.getId())));
                }
            }
        }
        return sections;
    }


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