package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

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.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
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.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 java.util.ArrayList;
import java.util.HashMap;
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.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;

    @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("獲取中..."))
                .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<CategoryBean> categoryBeans = new ArrayList<>();
                            if (supplierFoodsMap == null) {
                                supplierFoodsMap = new HashMap<>(5);
                            }
                            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);
                            }
                            mRootView.loadLeftSupplierInfo(categoryBeans);
                            if (info.getData().size() > 0) {
                                mRootView.setCurrentSupplierName(info.getData().get(0).getSupplierName());
                                mRootView.loadRightFoodIngredients(info.getData().get(0).getPurchaseFoodListVOS());
                            }
                        }
                    }
                });
    }

    /**
     * 將購物車中的食品
     *
     * @param purchaseFoodListVOS
     */
    private int setFoodCount(List<PurchaseFoodBean> purchaseFoodListVOS) {
        //統計當前食品集合中有多少個被選中
        int totalCount = 0;
        for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
            //將購物車中的食品數量同步到當前數據中
            for (PurchaseFoodBean purchaseFoodListVO : purchaseFoodListVOS) {
                if (cartFood.getId() == 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);
                        }
                    }
                });
    }

    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(purchaseFoodBeans);
        } else {
            loadFoodsBySupplierId(supplierId);
        }
    }

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

    /**
     * 刪除食品
     *
     * @param purchaseFoodBean
     * @param position
     */
    public void deleteFood(PurchaseFoodBean purchaseFoodBean, int position) {
        purchaseFoodBean.setDeletes(Constant.DELETE);
        purchaseFoodBean.setRestaurantId(RestaurantInfoManager.newInstance().getRestaurantId());
        purchaseFoodBean.setBrandId(RestaurantInfoManager.newInstance().getBrandId());
        mModel.updateFood(RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(purchaseFoodBean)))
                .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(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            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("獲取中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<OrderCategoryBean>(mErrorHandler) {
                    @Override
                    public void onNext(OrderCategoryBean orderCategoryBean) {
                        if (orderCategoryBean.isSuccess()) {
                            foodCategoryTrees = new ArrayList<>();
                            foodCategoryTrees.addAll(orderCategoryBean.getData());
                            mRootView.loadCategory(orderCategoryBean.getData());
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(orderCategoryBean.getErrMsg())) {
                            mRootView.showMessage(orderCategoryBean.getErrMsg());
                        } else {
                            mRootView.showMessage("獲取失敗，請稍候重試");
                        }
                    }
                });
    }

    public void getFoodByCategory(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", categoryId);
        mModel.getFoodByCategory(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodByCategoryResultBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull FoodByCategoryResultBean info) {
                        if (info.isSuccess()) {
                            mRootView.loadRightFoodIngredients(info.getData());
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                            mRootView.loadFail();
                        } else {
                            mRootView.loadFail();
                        }
                    }
                });
    }
}
