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.JsonUtils;
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.ConfirmOrderBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.ConfirmOrderContract;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

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

import javax.inject.Inject;

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;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/17/2020 10:24
 * <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 ConfirmOrderPresenter extends BasePresenter<ConfirmOrderContract.Model, ConfirmOrderContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private List<ConfirmOrderBean> confirmOrderBeans;

    @Inject
    public ConfirmOrderPresenter(ConfirmOrderContract.Model model, ConfirmOrderContract.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 organizeShopCartData() {
        Map<Integer, ConfirmOrderBean> listMap = new HashMap<>(4);

        for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
            //計算總價
            if (cartFood.isChecked()) {
                ConfirmOrderBean confirmOrderBean = listMap.get(cartFood.getSupplierId());
                if (confirmOrderBean == null) {
                    confirmOrderBean = new ConfirmOrderBean();
//                    confirmOrderBean.setPurchaseOrder(ConfirmOrderBean.conversionPurchaseOrder(cartFood));

                    List<ConfirmOrderBean.PurchaseOrderDetails> purchaseOrderDetails = new ArrayList<>();
                    purchaseOrderDetails.add(ConfirmOrderBean.conversionPurchaseOrderDetails(cartFood));
                    confirmOrderBean.setPurchaseOrderDetails(purchaseOrderDetails);
                    listMap.put(cartFood.getSupplierId(), confirmOrderBean);
                } else {
                    ConfirmOrderBean.PurchaseOrder purchaseOrder = confirmOrderBean.getPurchaseOrder();
                    //重新計算總價
                    purchaseOrder.setTotalAmount(MoneyUtil.sum(purchaseOrder.getTotalAmount(), MoneyUtil.priceCalculation(cartFood.getUnitPrice(), cartFood.getFoodQuantity())));
                    //計算加上運費之後的實際應付金額
                    purchaseOrder.setActualPayment(MoneyUtil.sum(purchaseOrder.getTotalAmount(), purchaseOrder.getShipping()));

                    //食品列表添加當前食品
                    List<ConfirmOrderBean.PurchaseOrderDetails> purchaseOrderDetails = confirmOrderBean.getPurchaseOrderDetails();
                    purchaseOrderDetails.add(ConfirmOrderBean.conversionPurchaseOrderDetails(cartFood));
                }
            }
        }
        confirmOrderBeans = new ArrayList<>();
        confirmOrderBeans.addAll(listMap.values());
        mRootView.loadInfo(confirmOrderBeans);
    }


    public void addPurchaseOrder() {
        mModel.addPurchaseOrder(RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(confirmOrderBeans)))
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("訂單創建中..."))
                .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()) {
                            List<ConfirmOrderBean> confirmOrderBeanList = GsonUtils.jsonToList(baseResult.getData().toString(), ConfirmOrderBean.class);
                            List<ConfirmOrderBean.PurchaseOrder> purchaseOrders = new ArrayList<>();
                            for (ConfirmOrderBean confirmOrderBean : confirmOrderBeanList) {
                                for (ConfirmOrderBean confirmOrderBean1 : confirmOrderBeans) {
                                    if (confirmOrderBean.getPurchaseOrder().getSupplierId() == confirmOrderBean1.getPurchaseOrder().getSupplierId()) {
                                        confirmOrderBean.getPurchaseOrder().setSupplierName(confirmOrderBean1.getPurchaseOrder().getSupplierName());
                                        break;
                                    }
                                }
                                purchaseOrders.add(confirmOrderBean.getPurchaseOrder());
                            }
                            //訂單添加成功，將購物車中這些食品移除
                            Iterator<PurchaseFoodBean> iterator = SupplyShoppingCart.getInstance().getCartFoods().iterator();
                            while (iterator.hasNext()) {
                                if (iterator.next().isChecked()) {
                                    iterator.remove();
                                }
                            }
                            mRootView.addOrderSuccess(purchaseOrders);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(baseResult.getErrMsg())) {
                            mRootView.showMessage(baseResult.getErrMsg());
                        } else {
                            mRootView.showMessage("創建訂單失敗，請稍後重試");
                        }
                    }
                });


    }


}
