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.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
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.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.bean.OrderWareHouseBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodEncodeSn;
import com.gingersoft.supply_chain.mvp.bean.PurchaseOrderDetailsBean;
import com.gingersoft.supply_chain.mvp.bean.WareHousingUnitBean;
import com.gingersoft.supply_chain.mvp.bean.WarehousingOrderDetailsBean;
import com.gingersoft.supply_chain.mvp.content.PurchaseConstant;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.ui.adapter.ConsumptionReasonAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.WareHousingOrderFoodAdapter;
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.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;

import javax.inject.Inject;

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

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/29/2021 15: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 WarehousingOrderDetailsPresenter extends BasePresenter<WarehousingOrderDetailsContract.Model, WarehousingOrderDetailsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private ConsumptionReasonAdapter consumptionReasonAdapter;
    private WareHousingOrderFoodAdapter wareHousingOrderFoodAdapter;

    @Inject
    public WarehousingOrderDetailsPresenter(WarehousingOrderDetailsContract.Model model, WarehousingOrderDetailsContract.View rootView) {
        super(model, rootView);
    }

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

    /**
     * 獲取入庫單詳情
     *
     * @param warehousingOrderId
     */
    public void getWarehousingOrderDetails(int warehousingOrderId) {
        mModel.getWarehousingOrderDetails(warehousingOrderId)
                .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<WarehousingOrderDetailsBean> warehousingOrderDetailsBeans = GsonUtils.jsonToList(baseResult.getData(), WarehousingOrderDetailsBean.class);
                            setAdapter(WarehousingOrderDetailsBean.conversionToPurchaseFoodBean(warehousingOrderDetailsBeans));
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(PurchaseConstant.GET_INFO_ERROR);
                        }
                    }
                });

    }

    /**
     * 獲取入庫類型：原因
     */
    public void getWarehousingReason() {
        Map<String, Object> map = new HashMap<>(2);
        PurchaseConstant.addBrandId(map);
        PurchaseConstant.addRestaurantId(map);
        mModel.getMultipleStorageCauseList(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<ConsumeReasonBean> consumeReasonBeans = GsonUtils.jsonToList(baseResult.getData(), ConsumeReasonBean.class);
                            consumptionReasonAdapter = new ConsumptionReasonAdapter(consumeReasonBeans);
                            mRootView.initReason(consumptionReasonAdapter);
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(PurchaseConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 查詢商品sn碼
     */
    public void querySnCodes(PurchaseFoodBean infoVosBean) {
        mModel.querySnCodes(infoVosBean.getFoodNo(), infoVosBean.getWarehousingOrderNo())
                .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(@NonNull BaseResult info) {
                        if (info.isSuccess()) {
                            List<PurchaseFoodEncodeSn> purchaseFoodEncodeSns = GsonUtils.jsonToList(info.getData(), PurchaseFoodEncodeSn.class);
                            if (purchaseFoodEncodeSns != null) {
                                infoVosBean.setPurchaseFoodEncodeSn(purchaseFoodEncodeSns);
                                mRootView.showSnCodePopup(infoVosBean);
                            }
                        }
                    }
                });
    }


    public void setSelectReason(String warehousingReason) {
        if (consumptionReasonAdapter != null) {
            int reasonSize = consumptionReasonAdapter.getItemCount();
            for (int i = 0; i < reasonSize; i++) {
                ConsumeReasonBean item = consumptionReasonAdapter.getItem(i);
                if (item.getDescription().equals(warehousingReason)) {
                    consumptionReasonAdapter.setSelectIndex(i);
                    return;
                }
            }
        }
    }

    /**
     * 獲取食材
     */
    public void initWarehousingFood() {
        List<PurchaseFoodBean> warehousingFood = SupplyShoppingCart.getInstance().getCartFoods();
        setAdapter(warehousingFood);
    }

    private void setAdapter(List<PurchaseFoodBean> warehousingFood) {
        if (wareHousingOrderFoodAdapter == null) {
            wareHousingOrderFoodAdapter = new WareHousingOrderFoodAdapter(warehousingFood);
            mRootView.initFoodView(wareHousingOrderFoodAdapter);
        } else {
            wareHousingOrderFoodAdapter.setNewInstance(warehousingFood);
        }
        mRootView.setOrderAllInfo();
    }

    public void notifyAdapter(int position) {
        wareHousingOrderFoodAdapter.notifyItemChanged(wareHousingOrderFoodAdapter.getHeaderLayoutCount() + position);
    }

    public List<PurchaseFoodBean> getWarehousingFood() {
        if (wareHousingOrderFoodAdapter == null) {
            return null;
        }
        return wareHousingOrderFoodAdapter.getData();
    }

    /**
     * 獲取食材總種類數
     *
     * @return 種類數
     */
    public int getFoodSpecial() {
        List<PurchaseFoodBean> warehousingFood = getWarehousingFood();
        if (warehousingFood == null) {
            return 0;
        }
        return warehousingFood.size();
    }

    /**
     * 獲取食材總數
     *
     * @return 食材總數
     */
    public int getFoodSize() {
        List<PurchaseFoodBean> warehousingFood = getWarehousingFood();
        if (warehousingFood == null) {
            return 0;
        }
        int foodSize = 0;
        for (PurchaseFoodBean purchaseFoodBean : warehousingFood) {
            foodSize += purchaseFoodBean.getFoodQuantity();
        }
        return foodSize;
    }

    public double getFoodTotalAmount() {
        List<PurchaseFoodBean> warehousingFood = getWarehousingFood();
        if (warehousingFood == null) {
            return 0;
        }
        double totalAmount = 0;
        for (PurchaseFoodBean purchaseFoodBean : warehousingFood) {
            totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getFoodQuantity(), purchaseFoodBean.getUnitPrice()));
        }
        return totalAmount;
    }

    public void createWarehousingOrder(String remarks) {
        List<PurchaseFoodBean> warehousingFood = getWarehousingFood();
        if (CollectionUtils.isNullOrEmpty(warehousingFood)) {
            mRootView.showMessage("請先添加食材");
            return;
        }
        if (consumptionReasonAdapter == null || consumptionReasonAdapter.getItemCount() <= 0) {
            mRootView.showMessage("沒有入庫類型，請檢查網絡");
            return;
        }
        OrderWareHouseBean wareHouseBean = new OrderWareHouseBean();
        double orderTotalAmount = 0;
        List<OrderWareHouseBean.PurchaseWarehousingOrderDetail> orderDetails = new ArrayList<>();
        for (PurchaseFoodBean datum : warehousingFood) {
            //食材轉換為訂單詳情
            OrderWareHouseBean.PurchaseWarehousingOrderDetail orderDetail = new OrderWareHouseBean.PurchaseWarehousingOrderDetail();
            //入庫單位
            WareHousingUnitBean purchaseWarehousingUnit = new WareHousingUnitBean();
//            DeputyUnitBean showUnit = new DeputyUnitBean();
//            DeputyUnitBean showUnit = datum.getShowUnit();
//            if (datum.getShowUnit() == null) {
//                mRootView.showMessage("食材【" + datum.getName() + "】沒有單位，請修改食材信息");
//                return;
//            }
            purchaseWarehousingUnit.setBrandId(PurchaseConstant.getBrandId());
            purchaseWarehousingUnit.setRestaurantId(PurchaseConstant.getRestaurantId());
            purchaseWarehousingUnit.setUnitName(datum.getBasicUnitName());
            purchaseWarehousingUnit.setUnitValue(datum.getFoodQuantity());
            purchaseWarehousingUnit.setUnitPrice(datum.getUnitPrice());
            orderDetail.setPurchaseWarehousingUnit(purchaseWarehousingUnit);

            //如果是SN食材，SN碼集合
            if (datum.getFoodMarkSn() == PurchaseFoodBean.HAS_SN) {
                List<PurchaseFoodEncodeSn> purchaseFoodEncodeSn = datum.getPurchaseFoodEncodeSn();
                if (CollectionUtils.isNullOrEmpty(purchaseFoodEncodeSn)) {
                    mRootView.showMessage("食材【" + datum.getName() + "】SN碼數量不能為0，請掃描SN碼");
                    return;
                }
                if (datum.getFoodQuantity() != purchaseFoodEncodeSn.size()) {
                    mRootView.showMessage("食材【" + datum.getName() + "】SN碼數量不足" + datum.getFoodQuantity() + "個，請掃描SN碼！");
                    return;
                }
                for (PurchaseFoodEncodeSn foodEncodeSn : purchaseFoodEncodeSn) {
                    foodEncodeSn.setEncodeFoodNo(datum.getFoodNo());
                }
                orderDetail.setPurchaseFoodEncodeSn(purchaseFoodEncodeSn);
            }
            orderDetail.setSupplierId(datum.getSupplierId());
            orderDetail.setPurchaseFoodId(datum.getId());
            orderDetail.setBrandId(PurchaseConstant.getBrandId());
            orderDetail.setFoodPrice(datum.getUnitPrice());
            orderDetail.setRestaurantId(PurchaseConstant.getRestaurantId());
            orderDetail.setFoodQuantity(datum.getFoodQuantity());
            double foodTotalAmount = MoneyUtil.priceCalculation(datum.getUnitPrice(), datum.getFoodQuantity());
            orderTotalAmount = MoneyUtil.sum(orderTotalAmount, foodTotalAmount);
            orderDetail.setTotalPrice(foodTotalAmount);
            orderDetails.add(orderDetail);
        }
        wareHouseBean.setPurchaseWarehousingOrderDetailsTOS(orderDetails);
        wareHouseBean.setPurchaseWarehousingOrder(getOrderInfo("", remarks, orderTotalAmount, consumptionReasonAdapter.getItem(consumptionReasonAdapter.getSelectIndex()).getDescription()));
        mModel.addWarehousingOrder(RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(wareHouseBean)))
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(PurchaseConstant.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("入庫成功");
                            mRootView.addOrderSuccess();
                        } else if (baseResult != null && TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(PurchaseConstant.SAVE_FAIL);
                        }
                    }
                });

    }

    /**
     * 獲取訂單對象
     *
     * @param files       文件
     * @param remarks     備註
     * @param totalPrice  訂單總金額
     * @param storageType 入庫原因
     * @return 訂單對象
     */
    private OrderWareHouseBean.PurchaseWarehousingOrder getOrderInfo(String files, String remarks, double totalPrice, String storageType) {
        OrderWareHouseBean.PurchaseWarehousingOrder order = new OrderWareHouseBean.PurchaseWarehousingOrder();
        order.setBrandId(PurchaseConstant.getBrandId());
        order.setRestaurantId(PurchaseConstant.getRestaurantId());
        order.setFiles(files);
        order.setRemarks(remarks);
        order.setTotalPrice(totalPrice);
        order.setStorageType(storageType);
        return order;
    }

}
