package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;
import android.os.Bundle;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.AppConstant;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
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.BasicUnitBean;
import com.gingersoft.supply_chain.mvp.bean.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.content.PurchaseConstant;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.FoodUnitPageFragment;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import javax.inject.Inject;

import com.gingersoft.supply_chain.mvp.contract.FoodUnitPageContract;
import com.jess.arms.utils.RxLifecycleUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/28/2020 16:05
 * <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 FoodUnitPagePresenter extends BasePresenter<FoodUnitPageContract.Model, FoodUnitPageContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    /**
     * 操作的副單位
     */
    private List<DeputyUnitBean> deputyUnitBeans;
    /**
     * 食品已有的副單位
     */
    private List<DeputyUnitBean> afterDeputyUnits;
    /**
     * 是修改還是新增
     * true：修改
     * false：新增
     */
    private boolean isUpdate = false;
    /**
     * 基本單位名稱
     */
    private String basicUnitName;
    private int foodId;

    @Inject
    public FoodUnitPagePresenter(FoodUnitPageContract.Model model, FoodUnitPageContract.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 initData(Bundle arguments) {
        if (arguments != null) {
            basicUnitName = arguments.getString(FoodUnitPageFragment.BASIC_UNIT_KEY);
            afterDeputyUnits = (List<DeputyUnitBean>) arguments.getSerializable(FoodUnitPageFragment.DEPUTY_UNIT_KEY);
            deputyUnitBeans = CollectionUtils.deepCopy(afterDeputyUnits);
            foodId = arguments.getInt(FoodUnitPageFragment.FOOD_ID_KEY);
            isUpdate = arguments.getBoolean(FoodUnitPageFragment.UPDATE_UNIT_KEY);
            mRootView.setMainUnit(basicUnitName);
            if (isUpdate) {
                mRootView.initTopBar("編輯商品單位");
            } else {
                mRootView.initTopBar("填寫商品單位");
            }
            if (deputyUnitBeans == null) {
                deputyUnitBeans = new ArrayList<>();
            }
            getDeputyUnitList();
            mRootView.loadDeputyUnitAdapter(deputyUnitBeans);
        }
    }

    /**
     * 獲取副單位 快捷輸入列表數據集合
     */
    public void getDeputyUnitList() {
        mModel.getDeputyUnitList(AppConstant.getBrandId(), AppConstant.getRestaurantId())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))
                .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() && baseResult.getData() != null) {
                            List<BasicUnitBean> basicUnitBeans = GsonUtils.jsonToList(GsonUtils.GsonString(baseResult.getData()), BasicUnitBean.class);
                            basicUnitBeans.add(new BasicUnitBean("+新增"));
                            mRootView.loadBasicUnitAdapter(basicUnitBeans);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 新增基本單位
     * @param data
     */
    public void addDeputyUnit(List<DeputyUnitBean> data) {
        //新增為false，修改為true
        if (isUpdate) {
            if (data == null) {
                mRootView.callBackDeputyUnit(null);
            } else {
                batchUpdateDeputyUnit(data);
            }
        } else {
            //如果是新增食材，那麼單位返回到新增食材頁面就好，不用做其他處理
            if (data != null) {
                Iterator<DeputyUnitBean> iterator = data.iterator();
                while (iterator.hasNext()) {
                    if (TextUtil.isEmptyOrNullOrUndefined(iterator.next().getDeputyUnit())) {
                        //單位為空，移除掉
                        iterator.remove();
                    }
                }
            }
            mRootView.callBackDeputyUnit(data);
        }
    }

    /**
     * 刪除副單位
     */
    public void deleteDeputyUnit(DeputyUnitBean deputyUnitBean, int position) {
        if (!isUpdate) {
            mRootView.deleteDeputyUnit(position);
            return;
        }
        deputyUnitBean.setDeletes(PurchaseConstant.DELETE);
        mModel.updateDeputyUnit(RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(deputyUnitBean)))
                .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(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            mRootView.deleteDeputyUnit(position);
                            afterDeputyUnits.remove(position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.DELETE_FAIL);
                        }
                    }
                });
    }

    /**
     * 批量修改，新增副單位
     */
    public void batchUpdateDeputyUnit(List<DeputyUnitBean> data) {
        mModel.updateDeputyUnitList(RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(data)))
                .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(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            mRootView.callBackDeputyUnit(data);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }


    /**
     * 添加副單位
     */
    public void addDeputyUnit() {
        if (deputyUnitBeans.size() > 0) {
            DeputyUnitBean basicUnitBean = deputyUnitBeans.get(deputyUnitBeans.size() - 1);
            if (TextUtil.isEmptyOrNullOrUndefined(basicUnitBean.getDeputyUnit())) {
                mRootView.showMessage("請輸入副單位");
                mRootView.loadDeputyUnitAdapter(deputyUnitBeans);
                return;
            }
        }
        DeputyUnitBean unitBean = new DeputyUnitBean();
        unitBean.setBrandId(AppConstant.getBrandId());
        unitBean.setRestaurantId(AppConstant.getRestaurantId());
        unitBean.setPurchaseFoodId(foodId);
        deputyUnitBeans.add(unitBean);
        mRootView.loadDeputyUnitAdapter(deputyUnitBeans);
    }

    /**
     * 添加基本單位-快捷輸入
     *
     * @param content        新增的基本單位
     * @param basicUnitBeans 已有的基本單位——需要判斷是否已經存在了
     */
    public void addBasicUnit(String content, List<BasicUnitBean> basicUnitBeans) {
        for (BasicUnitBean basicUnitBean : basicUnitBeans) {
            if (basicUnitBean.getContent().equals(content)) {
                mRootView.showMessage("此單位已存在，不能重複添加");
                return;
            }
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("content", content);
            jsonObject.put("brandId", AppConstant.getBrandId() + "");
            jsonObject.put("restaurantId", AppConstant.getRestaurantId() + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mModel.addBasicUnit(RequestBody.create(MediaType.parse("application/json"), jsonObject.toString()))
                .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(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            BasicUnitBean basicUnitBean = GsonUtils.GsonToBean(baseResult.getData(), BasicUnitBean.class);
                            mRootView.addBasicUnit(basicUnitBean);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 刪除基本單位快捷輸入的
     * @param id 單位id
     * @param position 單位下標，刪除成功後本地刷新
     */
    public void deleteUnitKey(int id, int position){
        mModel.deleteUnitKey(id)
                .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(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            mRootView.deleteUnitKey(position);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }
}
