package com.gingersoft.supply_chain.mvp.presenter;

import android.annotation.SuppressLint;
import android.app.Application;
import android.widget.CheckBox;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
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.NewPurchaseOrderBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.ShoppingCatContract;
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.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
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/03/2020 17:16
 * <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 ShoppingCatPresenter extends BasePresenter<ShoppingCatContract.Model, ShoppingCatContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private List<List<PurchaseFoodBean>> supplierFoods;

    @Inject
    public ShoppingCatPresenter(ShoppingCatContract.Model model, ShoppingCatContract.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, List<PurchaseFoodBean>> listMap = new HashMap<>(4);
        double totalPrice = 0;
        int totalTypeNumber = 0;
        for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
            //計算總價
            if (cartFood.isChecked()) {
                totalPrice = MoneyUtil.sum(totalPrice, MoneyUtil.priceCalculation(cartFood.getUnitPrice(), cartFood.getFoodQuantity()));
                totalTypeNumber++;
            }
            List<PurchaseFoodBean> foodListVosBeans = listMap.get(cartFood.getSupplierId());
            if (foodListVosBeans == null) {
                foodListVosBeans = new ArrayList<>();
                foodListVosBeans.add(cartFood);
                listMap.put(cartFood.getSupplierId(), foodListVosBeans);
            } else {
                foodListVosBeans.add(cartFood);
            }
        }
        supplierFoods = new ArrayList<>();
        supplierFoods.addAll(listMap.values());
        mRootView.loadAdapter(supplierFoods);
        mRootView.setTotalInfo(totalTypeNumber, totalPrice);
    }

    /**
     * 計算出已選中食品的總價
     */
    public void calculateTotalPrice(CheckBox cbAllSelect) {
        double totalAmount = 0;
        int totalTypeFood = 0;
        for (PurchaseFoodBean purchaseFoodBean : SupplyShoppingCart.getInstance().getCartFoods()) {
            if (purchaseFoodBean.isChecked()) {
                totalTypeFood++;
                totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
            }
        }
        mRootView.setTotalInfo(totalTypeFood, totalAmount);
        cbAllSelect.setChecked(totalTypeFood == SupplyShoppingCart.getInstance().getCartFoods().size());
    }

    @SuppressLint("CheckResult")
    public void addNewPurchaseOrder(List<PurchaseFoodBean> purchaseFoodBeans, String remarks) {
        NewPurchaseOrderBean newPurchaseOrderBean = new NewPurchaseOrderBean();
        newPurchaseOrderBean.setBrandId(RestaurantInfoManager.newInstance().getBrandId());
        newPurchaseOrderBean.setRestaurantId(RestaurantInfoManager.newInstance().getRestaurantId());
        double totalAmount = 0;
        for (PurchaseFoodBean purchaseFoodBean : purchaseFoodBeans) {
            totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
        }
        newPurchaseOrderBean.setTotalAmount(totalAmount);
        newPurchaseOrderBean.setRemarks(remarks);

        ArrayList<NewPurchaseOrderBean.PurchaseOrderDetailsBean> purchaseOrderDetailsBeans = new ArrayList<>();
        Observable.fromIterable(purchaseFoodBeans)
                .map(purchaseFoodListVosBean -> {
                    NewPurchaseOrderBean.PurchaseOrderDetailsBean orderDetailsBean = new NewPurchaseOrderBean.PurchaseOrderDetailsBean();
                    orderDetailsBean.setFoodId(purchaseFoodListVosBean.getId());
                    orderDetailsBean.setFoodPrice(purchaseFoodListVosBean.getUnitPrice());
                    orderDetailsBean.setFoodQuantity(purchaseFoodListVosBean.getFoodQuantity());
                    orderDetailsBean.setSupplierId(purchaseFoodListVosBean.getSupplierId());
                    return orderDetailsBean;
                }).subscribe(new Observer<NewPurchaseOrderBean.PurchaseOrderDetailsBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NewPurchaseOrderBean.PurchaseOrderDetailsBean purchaseOrderDetailsBean) {
                purchaseOrderDetailsBeans.add(purchaseOrderDetailsBean);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                newPurchaseOrderBean.setPurchaseOrderDetailsVOS(purchaseOrderDetailsBeans);
            }
        });

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(newPurchaseOrderBean));
        mModel.addNewPurchaseOrder(requestBody)
                .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) {

                    }
                });
    }


    public List<ConfirmOrderBean> getOrganizeShopCartData() {
        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));
                    confirmOrderBean.setMinimumAmount(cartFood.getMinimumAmount());
                    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));
                }
            }
        }
        ArrayList<ConfirmOrderBean> confirmOrderBeans = new ArrayList<>(listMap.values());
        for (ConfirmOrderBean confirmOrderBean : confirmOrderBeans) {
            if (MoneyUtil.compareTo(confirmOrderBean.getPurchaseOrder().getTotalAmount(), confirmOrderBean.getMinimumAmount()) < 0) {
                //小於最低採購金額
                mRootView.showMessage("不滿足【" + confirmOrderBean.getPurchaseOrder().getSupplierName() + "】的最低採購金額");
                return null;
            }
        }
        return new ArrayList<>(listMap.values());
    }

    public void addPurchaseOrder() {
        List<ConfirmOrderBean> confirmOrderBeans = getOrganizeShopCartData();
        if(confirmOrderBeans == null){
            return;
        }
        mModel.addNewPurchaseOrder(RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(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("創建訂單失敗，請稍後重試");
                        }
                    }
                });


    }

}
