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.constans.AppConstant;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.mvp.bean.FoodCategoryResultBean;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.content.PurchaseConstant;
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.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.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);
        AppConstant.addBrandId(map);
        AppConstant.addRestaurantId(map);
        mModel.getCategoryTrees(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.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(AppConstant.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(AppConstant.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(AppConstant.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(AppConstant.getBrandId());
        foodCategoryBean.setRestaurantId(AppConstant.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", AppConstant.getBrandId() + "")
                .add("restaurantId", AppConstant.getRestaurantId() + "")
                .build();
        mModel.deleteFoodCategory(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.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(PurchaseConstant.DELETE, hierarchy, "", position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.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(AppConstant.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(PurchaseConstant.UPDATE, hierarchy, foodCategoryBean.getName(), position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.UPDATE_FAIL);
                        }
                    }
                });
    }

    public int[] getCategoryIndexByName(String name, List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (foodCategoryTrees == null) {
            return new int[]{0, -1, -1};
        }
        for (int i = 0; i < foodCategoryTrees.size(); i++) {
            OrderCategoryBean.FoodCategoryTrees firstCategory = foodCategoryTrees.get(i);
            List<OrderCategoryBean.FoodCategoryTrees> secondCategoryTrees = firstCategory.getFoodCategoryTrees();
            if (name.equals(firstCategory.getName())) {
                //如果分類的名字一樣，說明是這個分類
                return new int[]{i, -1, -1};
            } else if (secondCategoryTrees != null) {
                //如果不是這個分類，遍歷這個分類下的分類
                for (int j = 0; j < secondCategoryTrees.size(); j++) {
                    OrderCategoryBean.FoodCategoryTrees secondCategory = secondCategoryTrees.get(j);
                    List<OrderCategoryBean.FoodCategoryTrees> thirdCategoryTress = secondCategory.getFoodCategoryTrees();
                    if (name.equals(secondCategory.getName())) {
                        //如果分類的名字一樣，說明是這個分類
                        return new int[]{i, j, -1};
                    } else if (thirdCategoryTress != null) {
                        //如果不是這個二級分類並且第三級分類不為空，找第三級分類
                        for (int k = 0; k < thirdCategoryTress.size(); k++) {
                            OrderCategoryBean.FoodCategoryTrees thirdCategory = thirdCategoryTress.get(k);
                            if (name.equals(thirdCategory.getName())) {
                                //如果分類的名字一樣，說明是這個分類
                                return new int[]{i, j, k};
                            }
                            //沒有第四級分類
                        }
                    }
                }
            }
        }
        return new int[]{0, -1, -1};
    }
}
