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.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.order.cart.ShoppingCart;
import com.gingersoft.supply_chain.mvp.bean.CategoryFoodTreeBean;
import com.gingersoft.supply_chain.mvp.bean.FoodCategoryResultBean;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.content.Constant;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.CategoryContract;
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.HashMap;
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.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/28/2020 10:14
 * <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 CategoryPresenter extends BasePresenter<CategoryContract.Model, CategoryContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    public final int primaryCategoryTag = 1;
    public final int secondCategoryTag = 2;
    public final int thirdCategoryTag = 3;

    @Inject
    public CategoryPresenter(CategoryContract.Model model, CategoryContract.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() {
        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()) {
                            mRootView.loadCategoryInfo(orderCategoryBean.getData());
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(orderCategoryBean.getErrMsg())) {
                            mRootView.showMessage(orderCategoryBean.getErrMsg());
                        } else {
                            mRootView.showMessage(Constant.GET_INFO_ERROR);
                        }
                    }

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


    /**
     * 新增分類
     *
     * @param parentId     父類id
     * @param categoryName 分類名字
     * @param hierarchy    級別：是第幾級分類
     */
    public void addCategory(int parentId, String categoryName, int hierarchy) {
        FoodCategoryResultBean.DataBean.FoodCategoryBean foodCategoryBean = toFoodCategoryBean(parentId, categoryName, 0);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(foodCategoryBean));
        mModel.createFoodCategory(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.SAVE_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 != null) {
                            if (info.isSuccess()) {
                                //新增分類成功，本地刷新
                                FoodCategoryResultBean.DataBean.FoodCategoryBean categoryBean = GsonUtils.GsonToBean(info.getData(), FoodCategoryResultBean.DataBean.FoodCategoryBean.class);
                                if (categoryBean != null) {
                                    OrderCategoryBean.FoodCategoryTrees categoryTrees = new OrderCategoryBean.FoodCategoryTrees();
                                    categoryTrees.setId(categoryBean.getId());
                                    categoryTrees.setName(categoryBean.getName());
                                    categoryTrees.setParentId(categoryBean.getParentId());
                                    mRootView.addCategory(categoryTrees, hierarchy);
                                }
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage(Constant.SAVE_FAIL);
                            }
                        }
                    }
                });
    }

    /**
     * 將信息轉為後台需要的數據對象
     *
     * @param parentId     分類的父類id
     * @param categoryName 分類名稱
     * @param id           分類id
     */
    public FoodCategoryResultBean.DataBean.FoodCategoryBean toFoodCategoryBean(int parentId, String categoryName, int id) {
        FoodCategoryResultBean.DataBean.FoodCategoryBean foodCategoryBean = new FoodCategoryResultBean.DataBean.FoodCategoryBean();
        foodCategoryBean.setBrandId(RestaurantInfoManager.newInstance().getBrandId());
        foodCategoryBean.setRestaurantId(RestaurantInfoManager.newInstance().getRestaurantId());
        foodCategoryBean.setName(categoryName);
        foodCategoryBean.setParentId(parentId);
        foodCategoryBean.setId(id);
        return foodCategoryBean;
    }

    /**
     * 刪除分類
     *
     * @param foodCategoryTrees 分類信息
     * @param hierarchy         第幾級分類，用於刪除後刷新
     * @param position          刪除的分類下標
     */
    public void deleteFoodCategory(OrderCategoryBean.FoodCategoryTrees foodCategoryTrees, int hierarchy, int position) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", foodCategoryTrees.getId() + "")
                .add("brandId", RestaurantInfoManager.newInstance().getBrandId() + "")
                .add("restaurantId", RestaurantInfoManager.newInstance().getRestaurantId() + "")
                .build();
        mModel.deleteFoodCategory(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.DELETE_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()) {
                            //需要刪除購物車中被刪除的分類下的食材
                            SupplyShoppingCart.getInstance().removeFoodsByCategoryTress(foodCategoryTrees);
                            mRootView.updateCategory(Constant.DELETE, hierarchy, "", position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                        } else {
                            mRootView.showMessage(Constant.DELETE_FAIL);
                        }
                    }
                });
    }


    /**
     * 修改分類
     *
     * @param foodCategoryBean 分類信息
     * @param hierarchy        修改的是第幾級分類
     * @param position         分類的位置
     */
    public void updateFoodCategory(FoodCategoryResultBean.DataBean.FoodCategoryBean foodCategoryBean, int hierarchy, int position) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(foodCategoryBean));
        mModel.updateFoodCategory(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.UPDATE_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()) {
                            mRootView.updateCategory(Constant.UPDATE, hierarchy, foodCategoryBean.getName(), position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                        } else {
                            mRootView.showMessage(Constant.UPDATE_FAIL);
                        }
                    }
                });
    }
}
