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.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 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;
    private int orderDetailsId;

    @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;
    }

    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;
                                orderDetailsId = orderDetailsBean.getId();
                                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);
                        }
                    }
                    /**
                     * 將可編輯的商品單價和單位轉換成wareHouse實體類集合，方便之後取值
                     */
                    private void transformationWareHouse(PurchaseOrderDetailsBean orderDetailsBean) {
                        List<PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean> purchaseOrderDetailsInfoVos = orderDetailsBean.getPurchaseOrderDetailsInfoVOS();
                        if (purchaseOrderDetailsInfoVos != null) {
                            //遍歷訂單商品
                            for (PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean purchaseOrderDetailsInfoVO : purchaseOrderDetailsInfoVos) {
                                //可編輯的商品單價和單位轉換成wareHouse實體類，方便之後取值
                                List<PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean.WareHouseBean> wareHouseBeans = new ArrayList<>();
                                wareHouseBeans.add(new PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean.WareHouseBean("單價(HKD)", purchaseOrderDetailsInfoVO.getFoodPrice() + ""));
                                wareHouseBeans.add(new PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean.WareHouseBean(purchaseOrderDetailsInfoVO.getBasicUnitName(), "1"));
                                if (purchaseOrderDetailsInfoVO.getFoodUnits() != null) {
                                    List<DeputyUnitBean> foodUnits = purchaseOrderDetailsInfoVO.getFoodUnits();
                                    for (DeputyUnitBean foodUnit : foodUnits) {
                                        wareHouseBeans.add(new PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean.WareHouseBean(foodUnit.getDeputyUnit(), MoneyUtil.priceCalculation(Double.parseDouble(foodUnit.getConversionMultiple()), purchaseOrderDetailsInfoVO.getFoodQuantity()) + ""));
                                    }
                                }
                                purchaseOrderDetailsInfoVO.setWareHouseBeans(wareHouseBeans);
                            }
                        }
                    }
                });
    }

    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.setPurchaseWarehousingOrderDetails(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(orderDetailsId);
                purchaseWarehousingOrderDetail.setPurchaseFoodId(purchaseOrderDetailsInfoVosBean.getId());
                purchaseWarehousingOrderDetail.setFoodQuantity(purchaseOrderDetailsInfoVosBean.getFoodQuantity());
                purchaseWarehousingOrderDetail.setFoodPrice(purchaseOrderDetailsInfoVosBean.getFoodPrice());
                purchaseWarehousingOrderDetail.setTotalPrice(MoneyUtil.priceCalculation(purchaseOrderDetailsInfoVosBean.getFoodPrice(), purchaseOrderDetailsInfoVosBean.getFoodQuantity()));
                purchaseWarehousingOrderDetail.setType(1);
                purchaseWarehousingOrderDetail.setUnitContent(purchaseOrderDetailsInfoVosBean.getUnit_content() +"");
                purchaseWarehousingOrderDetails.add(purchaseWarehousingOrderDetail);
            }
        }
        if (purchaseWarehousingOrderDetails.size() <= 0) {
            mRootView.showMessage("請選擇需要操作的食品");
            return null;
        }
        return purchaseWarehousingOrderDetails;
    }

}
