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.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.InventoryRecordBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseConsumeSnBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodEncodeSn;
import com.gingersoft.supply_chain.mvp.content.Constant;
import com.google.gson.Gson;
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.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

import javax.inject.Inject;

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

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


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

    private List<InventoryRecordBean> inventoryRecordBeanList;

    @Inject
    public WarehousingInventoryPresenter(WarehousingInventoryContract.Model model, WarehousingInventoryContract.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 consumeWareHousing(String foodNo, int consumeQuantity) {
        consumeWareHousing(getPurchaseConsumeSnBean(foodNo, consumeQuantity, null));
    }

    public void consumeWareHousing(String foodNo, int consumeQuantity, List<PurchaseFoodEncodeSn> snCodes) {
        consumeWareHousing(getPurchaseConsumeSnBean(foodNo, consumeQuantity, snCodes));
    }

    public PurchaseConsumeSnBean getPurchaseConsumeSnBean(String foodNo, int consumeQuantity, List<PurchaseFoodEncodeSn> snCodes) {
        PurchaseConsumeSnBean purchaseConsumeSnBean = new PurchaseConsumeSnBean();
        purchaseConsumeSnBean.brandId = Constant.getBrandId();
        purchaseConsumeSnBean.restaurantId = Constant.getRestaurantId();
        purchaseConsumeSnBean.foodNo = foodNo;
        purchaseConsumeSnBean.consumeQuantity = consumeQuantity;
        purchaseConsumeSnBean.purchaseConsumeReasonId = Constant.INVENTORY_CONSUME_ID;
        if (CollectionUtils.isNotNullOrEmpty(snCodes)) {
            purchaseConsumeSnBean.encodeFoodNos = new ArrayList<>();
            for (PurchaseFoodEncodeSn snCode : snCodes) {
                purchaseConsumeSnBean.encodeFoodNos.add(snCode.getEncodeSnNo());
            }
        }
        return purchaseConsumeSnBean;
    }

    /**
     * 庫存消耗——盤點
     */
    public void consumeWareHousing(PurchaseConsumeSnBean purchaseConsumeSnBean) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(purchaseConsumeSnBean));
        mModel.wareHousingInventory(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(BaseResult baseResult) {
                        if (baseResult != null && baseResult.isSuccess()) {
                            //消耗完之後，關閉頁面
                            mRootView.showMessage(Constant.SAVE_SUCCESS);
                            mRootView.updateSuccess(purchaseConsumeSnBean.consumeQuantity);
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(Constant.SAVE_FAIL);
                        }
                    }
                });
    }

    /**
     * 查詢庫存盤點記錄
     */
    public void getWarehousingRecord(String foodNo, int pageIndex) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("foodNo", foodNo);
        Constant.addPageSize(map);
        map.put("pageIndex", pageIndex * Constant.PAGE_SIZE);
        mModel.getWarehousingRecord(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.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()) {
                            List<InventoryRecordBean> inventoryRecordBeans = GsonUtils.jsonToList(baseResult.getData(), InventoryRecordBean.class);
                            if (inventoryRecordBeanList == null) {
                                inventoryRecordBeanList = new ArrayList<>();
                            }
                            if (pageIndex == 0) {
                                inventoryRecordBeanList.clear();
                            }
                            inventoryRecordBeanList.addAll(inventoryRecordBeans);
                            mRootView.loadRecord(inventoryRecordBeanList);
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(Constant.SAVE_FAIL);
                        }
                    }
                });
    }
}
