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.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.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseOrderDetailsBean;
import com.gingersoft.supply_chain.mvp.bean.OrderWareHouseBean;
import com.gingersoft.supply_chain.mvp.bean.WareHousingUnitBean;
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.OrderDetailsContract;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.gingersoft.supply_chain.mvp.content.Constant.GET_INFO_ERROR;
import static com.gingersoft.supply_chain.mvp.content.Constant.GET_INFO_LOADING;
import static com.gingersoft.supply_chain.mvp.content.Constant.NULL_INFO_ERROR;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/22/2020 16:57
 * <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 OrderDetailsPresenter extends BasePresenter<OrderDetailsContract.Model, OrderDetailsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private int orderId;

    @Inject
    public OrderDetailsPresenter(OrderDetailsContract.Model model, OrderDetailsContract.View rootView) {
        super(model, rootView);
    }

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

    /**
     * 跟劇訂單ID獲取訂單詳情
     *
     * @param orderId 訂單ID
     */
    public void getOrderDetailsById(int orderId) {
        mModel.getOrderDetails(orderId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(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()) {
                            PurchaseOrderDetailsBean orderDetailsBean = GsonUtils.GsonToBean(GsonUtils.GsonString(baseResult.getData()), PurchaseOrderDetailsBean.class);
                            if (orderDetailsBean != null) {
                                OrderDetailsPresenter.this.orderId = orderId;
                                transformationWareHouse(orderDetailsBean);
                                mRootView.loadOrderDetails(orderDetailsBean);
                            } else {
                                mRootView.showMessage(GET_INFO_ERROR);
                            }
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(GET_INFO_ERROR);
                        }
                    }

                    /**
                     * 將單價和
                     */
                    private void transformationWareHouse(PurchaseOrderDetailsBean orderDetailsBean) {
                        List<PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean> purchaseOrderDetailsInfoVos = orderDetailsBean.getPurchaseOrderDetailsInfoVOS();
                        if (purchaseOrderDetailsInfoVos != null) {
                            //遍歷訂單商品
                            for (PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean purchaseOrderDetailsInfoVO : purchaseOrderDetailsInfoVos) {
                                purchaseOrderDetailsInfoVO.setOrderNo(orderDetailsBean.getOrderNo());

                                List<DeputyUnitBean> deputyUnitBeans = new ArrayList<>();
                                deputyUnitBeans.add(new DeputyUnitBean("單價(HKD)", purchaseOrderDetailsInfoVO.getFoodPrice()));
                                deputyUnitBeans.add(new DeputyUnitBean(purchaseOrderDetailsInfoVO.getBasicUnitName(), purchaseOrderDetailsInfoVO.getFoodQuantity()));
                                //入庫金額和總金額
                                purchaseOrderDetailsInfoVO.setWarehousingAmount(MoneyUtil.priceCalculation(purchaseOrderDetailsInfoVO.getFoodPrice(), purchaseOrderDetailsInfoVO.getFoodQuantity()));
                                purchaseOrderDetailsInfoVO.setTotalAmount(MoneyUtil.priceCalculation(purchaseOrderDetailsInfoVO.getFoodPrice(), purchaseOrderDetailsInfoVO.getFoodQuantity()));

                                if (purchaseOrderDetailsInfoVO.getFoodUnits() != null) {
                                    deputyUnitBeans.addAll(purchaseOrderDetailsInfoVO.getFoodUnits());
                                }
                                if (purchaseOrderDetailsInfoVO.getPurchaseWarehousingUnits() != null) {
                                    //入庫單位不為空，將入庫單位轉為副單位，添加到副單位集合裡去，進行顯示
                                    for (WareHousingUnitBean purchaseWarehousingUnit : purchaseOrderDetailsInfoVO.getPurchaseWarehousingUnits()) {
                                        deputyUnitBeans.add(DeputyUnitBean.getDeputyUnitByWareHousingUnit(purchaseWarehousingUnit));
                                    }
                                }
                                purchaseOrderDetailsInfoVO.setFoodUnits(deputyUnitBeans);
                            }
                        }
                    }
                });
    }

    /**
     * 入庫
     *
     * @param state                            入庫單的狀態
     * @param files                            上傳的文件
     * @param remark                           備註
     * @param totalAmount                      總金額
     * @param purchaseOrderDetailsInfoVosBeans 選中的食品
     */
    public void addWarehouse(int state, String files, String remark, double totalAmount, List<PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean> purchaseOrderDetailsInfoVosBeans) {
        List<OrderWareHouseBean.PurchaseWarehousingOrderDetail> purchaseWarehousingOrderDetails = transformWareHoses(purchaseOrderDetailsInfoVosBeans);
        OrderWareHouseBean wareHouseBean = getWareHouseBean(state, files, remark, totalAmount, purchaseWarehousingOrderDetails);
        if (wareHouseBean == null) {
            return;
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(wareHouseBean));
        mModel.addWarehouse(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(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()) {
                            mRootView.showMessage("收貨成功");
                            mRootView.killMyself();
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage(GET_INFO_ERROR);
                        }
                    }
                });
    }

    /**
     * 生成入庫對象
     */
    private OrderWareHouseBean getWareHouseBean(int state, String files, String remark, double totalAmount, List<OrderWareHouseBean.PurchaseWarehousingOrderDetail> purchaseWarehousingOrderDetails) {
        if (purchaseWarehousingOrderDetails == null) {
            return null;
        }
        OrderWareHouseBean orderWareHouseBean = new OrderWareHouseBean();
        orderWareHouseBean.setStatus(state);
        orderWareHouseBean.setOrderId(orderId);

        OrderWareHouseBean.PurchaseWarehousingOrder purchaseWarehousingOrder = new OrderWareHouseBean.PurchaseWarehousingOrder();
        purchaseWarehousingOrder.setRestaurantId(RestaurantInfoManager.newInstance().getRestaurantId());
        purchaseWarehousingOrder.setBrandId(RestaurantInfoManager.newInstance().getBrandId());
        purchaseWarehousingOrder.setFiles(files);
        purchaseWarehousingOrder.setRemarks(remark);
        purchaseWarehousingOrder.setTotalPrice(totalAmount);
        orderWareHouseBean.setPurchaseWarehousingOrder(purchaseWarehousingOrder);
        orderWareHouseBean.setPurchaseWarehousingOrderDetailsTOS(purchaseWarehousingOrderDetails);
        return orderWareHouseBean;
    }

    /**
     * 將訂單轉換為入庫單
     */
    private List<OrderWareHouseBean.PurchaseWarehousingOrderDetail> transformWareHoses(List<PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean> purchaseOrderDetailsInfoVosBeans) {
        if (purchaseOrderDetailsInfoVosBeans == null || purchaseOrderDetailsInfoVosBeans.size() <= 0) {
            mRootView.showMessage(NULL_INFO_ERROR);
            return null;
        }
        List<OrderWareHouseBean.PurchaseWarehousingOrderDetail> purchaseWarehousingOrderDetails = new ArrayList<>();
        for (PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean purchaseOrderDetailsInfoVosBean : purchaseOrderDetailsInfoVosBeans) {
            if (purchaseOrderDetailsInfoVosBean.isChecked()) {
                OrderWareHouseBean.PurchaseWarehousingOrderDetail purchaseWarehousingOrderDetail = new OrderWareHouseBean.PurchaseWarehousingOrderDetail();
                purchaseWarehousingOrderDetail.setOrderDetailsId(purchaseOrderDetailsInfoVosBean.getId());
                purchaseWarehousingOrderDetail.setPurchaseFoodId(purchaseOrderDetailsInfoVosBean.getPurchaseFoodId());
                purchaseWarehousingOrderDetail.setFoodQuantity(purchaseOrderDetailsInfoVosBean.getFoodQuantity());
                purchaseWarehousingOrderDetail.setFoodPrice(purchaseOrderDetailsInfoVosBean.getFoodPrice());
                purchaseWarehousingOrderDetail.setTotalPrice(MoneyUtil.priceCalculation(purchaseOrderDetailsInfoVosBean.getFoodPrice(), purchaseOrderDetailsInfoVosBean.getFoodQuantity()));
                List<DeputyUnitBean> deputyUnitBeans = purchaseOrderDetailsInfoVosBean.getFoodUnits();

                //將副單位轉為入庫用的副單位
                if (deputyUnitBeans != null && deputyUnitBeans.size() > 1) {
                    //主單位名稱
                    purchaseWarehousingOrderDetail.setBasicUnitName(deputyUnitBeans.get(1).getDeputyUnit());
                    //主單位數量
                    purchaseWarehousingOrderDetail.setBasicUnitValue(deputyUnitBeans.get(1).getDeputyValue());
                    //統計副單位
                    List<WareHousingUnitBean> wareHousingUnitBeans = new ArrayList<>();
                    for (int i = 2; i < deputyUnitBeans.size(); i++) {
                        DeputyUnitBean deputyUnitBean = deputyUnitBeans.get(i);
                        WareHousingUnitBean wareHousingUnitBean = new WareHousingUnitBean(purchaseOrderDetailsInfoVosBean.getId(), deputyUnitBean.getDeputyUnit(), deputyUnitBean.getDeputyValue(), deputyUnitBean.getConversionMultiple());
                        wareHousingUnitBean.setBrandId(RestaurantInfoManager.newInstance().getBrandId());
                        wareHousingUnitBean.setRestaurantId(RestaurantInfoManager.newInstance().getRestaurantId());
                        wareHousingUnitBeans.add(wareHousingUnitBean);
                    }
                    purchaseWarehousingOrderDetail.setPurchaseWarehousingUnits(wareHousingUnitBeans);
                }
                purchaseWarehousingOrderDetails.add(purchaseWarehousingOrderDetail);
            }
        }
        if (purchaseWarehousingOrderDetails.size() <= 0) {
            mRootView.showMessage("請選擇需要操作的食品");
            return null;
        }
        return purchaseWarehousingOrderDetails;
    }

}
