package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;
import android.view.View;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
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.ConsumeReasonBean;
import com.gingersoft.supply_chain.mvp.bean.ConsumeWareHousingBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseConsumeSnBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseWarehousingOrderDetailsVO;
import com.gingersoft.supply_chain.mvp.bean.WarehouseDetailsBean;
import com.gingersoft.supply_chain.mvp.content.PurchaseConstant;
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.WarehouseDetailsContract;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/21/2021 10:15
 * <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 WarehouseDetailsPresenter extends BasePresenter<WarehouseDetailsContract.Model, WarehouseDetailsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;


    @Inject
    public WarehouseDetailsPresenter(WarehouseDetailsContract.Model model, WarehouseDetailsContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    /**
     * 獲取入庫訂單流水
     *
     * @param foodNo 食材編號
     */
    public void getWarehousingOrderDetails(String foodNo) {
        Map<String, Object> map = new HashMap<>(4);
        PurchaseConstant.addBrandId(map);
        PurchaseConstant.addRestaurantId(map);
        map.put("foodNo", foodNo);
        mModel.getWarehousingOrderDetails(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(PurchaseConstant.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 != null && baseResult.isSuccess()) {
                            List<WarehouseDetailsBean> warehouseDetailsBean = GsonUtils.jsonToList(baseResult.getData(), WarehouseDetailsBean.class);
                            mRootView.loadAdapter(warehouseDetailsBean);
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(PurchaseConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 獲取出庫庫訂單流水
     *
     * @param foodNo
     */
    public void getOutStockDetails(String foodNo) {
        Map<String, Object> map = new HashMap<>(4);
        PurchaseConstant.addBrandId(map);
        PurchaseConstant.addRestaurantId(map);
        map.put("foodNo", foodNo);
        mModel.getOutStockDetails(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(PurchaseConstant.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 != null && baseResult.isSuccess()) {
                            List<ConsumeWareHousingBean> consumeWareHousingBeans = GsonUtils.jsonToList(baseResult.getData(), ConsumeWareHousingBean.class);
                            mRootView.loadAdapter(WarehouseDetailsBean.getWarehousingByConsumes(consumeWareHousingBeans));
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(PurchaseConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 獲取庫存消耗原因
     */
    public void getWarehouseInventoryReason() {
        mModel.getWarehouseInventoryReason()
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(PurchaseConstant.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 != null && baseResult.isSuccess()) {
                            List<ConsumeReasonBean> consumeReasonBeans = GsonUtils.jsonToList(baseResult.getData(), ConsumeReasonBean.class);
                            mRootView.loadConsumeReason(consumeReasonBeans);
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(PurchaseConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 庫存消耗
     *
     * @param purchaseWarehousingOrderDetailsVO 食材信息
     * @param consumeQuantity                   消耗數量
     * @param consumeReasonBean                 消耗原因
     * @param remarks                           備註
     */
    public void consumeWareHousing(PurchaseWarehousingOrderDetailsVO purchaseWarehousingOrderDetailsVO, int consumeQuantity, ConsumeReasonBean consumeReasonBean, String remarks, List<String> snCodes, boolean whetherPrint) {
        PurchaseConsumeSnBean purchaseConsumeSnBean = new PurchaseConsumeSnBean();
        purchaseConsumeSnBean.brandId = PurchaseConstant.getBrandId();
        purchaseConsumeSnBean.restaurantId = PurchaseConstant.getRestaurantId();
        purchaseConsumeSnBean.foodNo = purchaseWarehousingOrderDetailsVO.getFoodNo();
        purchaseConsumeSnBean.purchaseConsumeReasonId = consumeReasonBean.getId();
        purchaseConsumeSnBean.remarks = remarks;
        if (CollectionUtils.isNotNullOrEmpty(snCodes)) {
            purchaseConsumeSnBean.encodeFoodNos = snCodes;
            purchaseConsumeSnBean.consumeQuantity = snCodes.size();
        } else {
            purchaseConsumeSnBean.consumeQuantity = consumeQuantity;
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(purchaseConsumeSnBean));
        mModel.consumeWareHousing(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(PurchaseConstant.UPDATE_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 != null && baseResult.isSuccess()) {
                            if (whetherPrint) {
                                mRootView.printConsumeOrder(snCodes, consumeReasonBean.getDescription(), consumeQuantity);
                            } else {
                                //如果需要打印，則是在打印完之後查詢，如果不需要打印，現在就查詢刷新頁面
                                //消耗完之後，刷新列表
                                mRootView.getPageInfo();
                                //重新獲取庫存數量
                                getWarehousingNum(purchaseWarehousingOrderDetailsVO.getFoodNo());
                            }
                            //不需要打印，現在就移除消耗视图，显示流水页面
                            //如果需要打印，則在打印完成後執行
                            mRootView.showList(View.VISIBLE);
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(PurchaseConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 獲取庫存數量
     */
    public void getWarehousingNum(String foodNo) {
        Map<String, Object> map = new HashMap<>(3);
        PurchaseConstant.addBrandId(map);
        PurchaseConstant.addRestaurantId(map);
        map.put("foodNo", foodNo);
        mModel.getWarehousingNum(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(PurchaseConstant.QUERY_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 != null && baseResult.isSuccess()) {
                            try {
                                mRootView.setWarehousingNum((int) Double.parseDouble(GsonUtils.GsonString(baseResult.getData())));
                            } catch (NumberFormatException e) {
                                mRootView.killMyself();
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }
}
