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.ResturantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.supply_chain.mvp.bean.NewPurchaseOrderBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodListVosBean;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.OrderContentContract;
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.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 OrderContentPresenter extends BasePresenter<OrderContentContract.Model, OrderContentContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private List<List<PurchaseFoodListVosBean>> supplierFoods;

    @Inject
    public OrderContentPresenter(OrderContentContract.Model model, OrderContentContract.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<PurchaseFoodListVosBean>> listMap = new HashMap<>(4);
        double totalPrice = 0;
        int totalTypeNumber = 0;
        for (PurchaseFoodListVosBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
            //計算總價
            if (cartFood.isChecked()) {
                totalPrice = MoneyUtil.sum(totalPrice, MoneyUtil.priceCalculation(cartFood.getUnitPrice(), cartFood.getFoodCount()));
                totalTypeNumber++;
            }
            List<PurchaseFoodListVosBean> 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 (PurchaseFoodListVosBean purchaseFoodListVosBean : SupplyShoppingCart.getInstance().getCartFoods()) {
            if (purchaseFoodListVosBean.isChecked()) {
                totalTypeFood++;
                totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodListVosBean.getUnitPrice(), purchaseFoodListVosBean.getFoodCount()));
            }
        }
        mRootView.setTotalInfo(totalTypeFood, totalAmount);
        cbAllSelect.setChecked(totalTypeFood == SupplyShoppingCart.getInstance().getCartFoods().size());
    }

    @SuppressLint("CheckResult")
    public void addNewPurchaseOrder(List<PurchaseFoodListVosBean> purchaseFoodListVosBeans, String remarks) {
        NewPurchaseOrderBean newPurchaseOrderBean = new NewPurchaseOrderBean();
        newPurchaseOrderBean.setBrandId(ResturantInfoManager.newInstance().getBrandId());
        newPurchaseOrderBean.setRestaurantId(ResturantInfoManager.newInstance().getRestaurantId());
        double totalAmount = 0;
        for (PurchaseFoodListVosBean purchaseFoodListVosBean : purchaseFoodListVosBeans) {
            totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodListVosBean.getUnitPrice(), purchaseFoodListVosBean.getFoodCount()));
        }
        newPurchaseOrderBean.setTotalAmount(totalAmount);
        newPurchaseOrderBean.setRemarks(remarks);

        ArrayList<NewPurchaseOrderBean.PurchaseOrderDetailsBean> purchaseOrderDetailsBeans = new ArrayList<>();
        Observable.fromIterable(purchaseFoodListVosBeans)
                .map(purchaseFoodListVosBean -> {
                    NewPurchaseOrderBean.PurchaseOrderDetailsBean orderDetailsBean = new NewPurchaseOrderBean.PurchaseOrderDetailsBean();
                    orderDetailsBean.setFoodId(purchaseFoodListVosBean.getId());
                    orderDetailsBean.setFoodPrice(purchaseFoodListVosBean.getUnitPrice());
                    orderDetailsBean.setFoodQuantity(purchaseFoodListVosBean.getFoodCount());
                    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) {

                    }
                });
    }


}
