package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
import com.gingersoft.supply_chain.mvp.bean.FoodListInfoBean;
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;


/**
 * ================================================
 * 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<FoodListInfoBean.DataBean.PurchaseFoodListVOSBean>> supplierFoodsMap;

    @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;
    }

    public void loadFoodIngredientsData(int supplierId) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        map.put("restaurantId", GsaCloudApplication.getRestaurantId());
        map.put("brandId", GsaCloudApplication.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<>();
                            }
                            for (FoodListInfoBean.DataBean datum : info.getData()) {
                                categoryBeans.add(new CategoryBean(datum.getId(), datum.getSupplierName()));
                                if (datum.getPurchaseFoodListVOS() == null) {
                                    supplierFoodsMap.put(datum.getId(), null);
                                } else {
                                    supplierFoodsMap.put(datum.getId(), new ArrayList<>(datum.getPurchaseFoodListVOS()));
                                }
                            }
                            mRootView.loadLeftSupplierInfo(categoryBeans);
                            if (info.getData().size() > 0) {
                                mRootView.loadRightFoodIngredients(info.getData().get(0).getPurchaseFoodListVOS());
                            }
                        }
                    }
                });
    }

    public void loadFoodsBySupplierId(int supplierId) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        map.put("restaurantId", GsaCloudApplication.getRestaurantId());
        map.put("brandId", GsaCloudApplication.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<FoodListInfoBean.DataBean.PurchaseFoodListVOSBean> purchaseFoodListVOS = JsonUtils.parseArray(info.getData(), FoodListInfoBean.DataBean.PurchaseFoodListVOSBean.class);
                            if (purchaseFoodListVOS == null) {
                                supplierFoodsMap.put(supplierId, new ArrayList<>());
                            } else {
                                supplierFoodsMap.put(supplierId, new ArrayList<>(purchaseFoodListVOS));
                            }
                            mRootView.loadRightFoodIngredients(purchaseFoodListVOS);
                        }
                    }
                });
    }

    public void getFoodsBySupplierId(int supplierId) {
        if (supplierFoodsMap != null) {
            List<FoodListInfoBean.DataBean.PurchaseFoodListVOSBean> purchaseFoodListVOSBeans = supplierFoodsMap.get(supplierId);
            if (purchaseFoodListVOSBeans != null) {
                mRootView.loadRightFoodIngredients(purchaseFoodListVOSBeans);
            } else {
                loadFoodsBySupplierId(supplierId);
            }
        }
    }

}
