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.ResturantInfoManager;
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.content.Constant;
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.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/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;
    /**
     * Key為一級分類ID，對應的二級數據
     */
    private Map<Integer, List<FoodCategoryResultBean.DataBean.FoodCategoryBean>> primaryCategory;

    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 getFoodCategoryList(String name, int parentId, int hierarchy) {
        Map<String, Object> map = new HashMap<>(6);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        map.put("parentId", parentId);
        map.put("restaurantId", ResturantInfoManager.newInstance().getRestaurantId());
        map.put("brandId", ResturantInfoManager.newInstance().getBrandId());
        if (!TextUtil.isEmptyOrNullOrUndefined(name)) {
            map.put("name", name);
        }
        mModel.getFoodCategoryList(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodCategoryResultBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull FoodCategoryResultBean info) {
                        if (info != null) {
                            if (info.isSuccess()) {
                                if (info.getData() != null) {
                                    List<FoodCategoryResultBean.DataBean.FoodCategoryBean> categoryBeans = info.getData().getList();
                                    if (categoryBeans == null) {
                                        categoryBeans = new ArrayList<>();
                                    }
                                    if (hierarchy == primaryCategoryTag) {
                                        //如果獲取的是一級分類。將一級分類的id保存到map的key中
                                        if (primaryCategory == null) {
                                            primaryCategory = new HashMap<>(5);
                                            for (FoodCategoryResultBean.DataBean.FoodCategoryBean categoryBean : categoryBeans) {
                                                primaryCategory.put(categoryBean.getId(), null);
                                            }
                                        } else {
                                            //第一類，不是空，判斷裡面數據是否為空，不為空的就不覆蓋數據
                                            for (FoodCategoryResultBean.DataBean.FoodCategoryBean categoryBean : categoryBeans) {
                                                if (primaryCategory.get(categoryBean.getId()) != null
                                                        && primaryCategory.get(categoryBean.getId()).size() > 0) {

                                                } else {
                                                    primaryCategory.put(categoryBean.getId(), null);
                                                }
                                            }
                                        }
                                    } else {
                                        //如果獲取到的是二級、三級分類
                                        if (categoryBeans.size() > 0) {
                                            categoryBeans.add(0, new FoodCategoryResultBean.DataBean.FoodCategoryBean());
                                        }
                                        primaryCategory.put(parentId, new ArrayList<>(categoryBeans));
                                    }
                                    mRootView.loadCategoryInfo(categoryBeans, hierarchy);
                                } else {
                                    mRootView.hideLoading();
                                    mRootView.showMessage("獲取" + hierarchy + "級分類失敗");
                                }
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                                mRootView.hideLoading();
                            }
                        } else {
                            mRootView.hideLoading();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("獲取" + hierarchy + "級分類失敗");
                        mRootView.hideLoading();
                    }
                });

    }

    public void getCategoryBeansById(int id, int hierarchy) {
        List<FoodCategoryResultBean.DataBean.FoodCategoryBean> foodCategoryBeans = primaryCategory.get(id);
        if (foodCategoryBeans == null) {
            getFoodCategoryList("", id, hierarchy);
        } else {
            mRootView.loadCategoryInfo(foodCategoryBeans, 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("保存中..."))
                .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()) {
                                getFoodCategoryList("", parentId, hierarchy);
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("保存失敗");
                            }
                        }
                    }
                });
    }

    public FoodCategoryResultBean.DataBean.FoodCategoryBean toFoodCategoryBean(int parentId, String categoryName, int id) {
        FoodCategoryResultBean.DataBean.FoodCategoryBean foodCategoryBean = new FoodCategoryResultBean.DataBean.FoodCategoryBean();
        foodCategoryBean.setBrandId(ResturantInfoManager.newInstance().getBrandId());
        foodCategoryBean.setRestaurantId(ResturantInfoManager.newInstance().getRestaurantId());
        foodCategoryBean.setName(categoryName);
        foodCategoryBean.setParentId(parentId);
        foodCategoryBean.setId(id);
        return foodCategoryBean;
    }

    public void deleteFoodCategory(FoodCategoryResultBean.DataBean.FoodCategoryBean foodCategoryBean, int hierarchy, int position) {
        foodCategoryBean.setDeletes(Constant.DELETE);
        updateFoodCategory(foodCategoryBean, hierarchy, position);
    }

    /**
     * @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("修改中..."))
                .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.refreshInfo(hierarchy, position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                        } else {
                            mRootView.showMessage("修改失敗");
                        }
                    }
                });
    }
}
