package com.gingersoft.supply_chain.mvp.presenter;

import android.annotation.SuppressLint;
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.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.gsa.cloud.common.utils.time.TimeUtils;
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.bean.ShoppingCartBean;
import com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean;
import com.gingersoft.supply_chain.mvp.content.Constant;
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 com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxAsyncTask;

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<ShoppingCartBean> shoppingCartBeans;

    @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;
        getFoodsBySupplierGrouping(listMap);
        shoppingCartBeans = new ArrayList<>();
        //創建訂單按鈕是否可點擊，只要有供應商不滿足最低採購，就不能點擊
        boolean createBtnCheckable = true;
        //將裝有不同供應商和供應商食品的map轉換為用於顯示的集合數據
        for (Map.Entry<Integer, List<PurchaseFoodBean>> entry : listMap.entrySet()) {
            ShoppingCartBean shoppingCartBean = new ShoppingCartBean();
            List<PurchaseFoodBean> foods = entry.getValue();
            if (foods != null && foods.size() > 0) {
                //將供應商信息從食材中取出
                PurchaseFoodBean food = foods.get(0);
                //統計當前供應商所選中食品的總金額
                double supplierTotalAmount = 0;
                //統計當前供應商選中食材的種類
                int supplierTotalSpecies = 0;
                shoppingCartBean.setAllSelect(true);
                double shipping = 0;
                for (PurchaseFoodBean purchaseFoodBean : foods) {
                    if (purchaseFoodBean.isChecked()) {
                        supplierTotalAmount = MoneyUtil.sum(supplierTotalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
                        supplierTotalSpecies++;
                        //有選中的食品才顯示運費
                        shipping = purchaseFoodBean.getShipping();
                    } else {
                        shoppingCartBean.setAllSelect(false);
                    }
                }
                //以購物車中的供應商信息為准，如果購物車拿出來的供應商信息為空，就用食材本身的供應商信息
                SupplierInfoBean supplierInfoBean = null;
                if (food.getSupplierId() != null) {
                    supplierInfoBean = SupplyShoppingCart.getInstance().getSupplierById(food.getSupplierId());
                }
                if (supplierInfoBean != null) {
                    shoppingCartBean.setAddress(supplierInfoBean.getAddress());
                    shoppingCartBean.setMinimumAmount(supplierInfoBean.getMinimumAmount());
                    shoppingCartBean.setSupplierId(supplierInfoBean.getId());
                    shoppingCartBean.setSupplierName(supplierInfoBean.getSupplierName());
                    shoppingCartBean.setShipping(supplierInfoBean.getShipping());
                } else {
                    shoppingCartBean.setAddress(food.getAddress());
                    shoppingCartBean.setMinimumAmount(food.getMinimumAmount());
                    if (entry.getKey() != null) {
                        shoppingCartBean.setSupplierId(entry.getKey());
                    }
                    shoppingCartBean.setSupplierName(food.getSupplierName());
                    shoppingCartBean.setShipping(shipping);
                }
                //不滿足最低採購金額，不可點擊創建訂單按鈕
                if (MoneyUtil.compareTo(shoppingCartBean.getMinimumAmount(), supplierTotalAmount) == 1) {
                    createBtnCheckable = false;
                }
                //運費
//                shoppingCartBean.setShipping(shipping);
                shoppingCartBean.setInitialShippingTime(TimeUtils.getNextDay(1));
                shoppingCartBean.setSelectFoodAmount(supplierTotalAmount);
                shoppingCartBean.setSelectSpeciesNum(supplierTotalSpecies);
                //統計所有供應商的選中的食材的總金額，加上運費
                totalPrice = MoneyUtil.sum(MoneyUtil.sum(totalPrice, supplierTotalAmount), shipping);
                //統計所有供應商的選中的食材的種類數量
                totalTypeNumber += supplierTotalSpecies;
                shoppingCartBean.setFoodList(foods);
            }
            shoppingCartBeans.add(shoppingCartBean);
        }
        mRootView.setCreateBtnState(createBtnCheckable);
        mRootView.loadAdapter(shoppingCartBeans);
        mRootView.setTotalInfo(totalTypeNumber, totalPrice);
    }

    /**
     * 獲取根據供應商分組後的食材
     *
     * @param listMap 區分出不同供應商的map
     */
    private void getFoodsBySupplierGrouping(Map<Integer, List<PurchaseFoodBean>> listMap) {
        for (PurchaseFoodBean cartFood : SupplyShoppingCart.getInstance().getCartFoods()) {
            //將食材按供應商分類
            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);
            }
        }
    }

    /**
     * 計算出已選中食品的總價和种类
     *
     * @param checkState        全選狀態
     * @param shoppingCartBeans 食品和供應商信息
     */
    public void calculateTotalPrice(boolean checkState, List<ShoppingCartBean> shoppingCartBeans) {
        RxJavaUtils.executeAsyncTask2(integer -> {
                    double totalAmount = 0;
                    double totalTypeFood = 0;
                    for (ShoppingCartBean shoppingCartBean : shoppingCartBeans) {
                        shoppingCartBean.setAllSelect(checkState);
                        double supplierTotalAmount = 0;
                        for (PurchaseFoodBean purchaseFoodBean : shoppingCartBean.getFoodList()) {
                            purchaseFoodBean.setChecked(checkState);
                            if (checkState) {
                                supplierTotalAmount = MoneyUtil.sum(supplierTotalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
                                totalTypeFood++;
                            }
                        }
                        if (checkState) {
                            shoppingCartBean.setSelectSpeciesNum(shoppingCartBean.getFoodList().size());
                            //總金額要加上運費
                            totalAmount = MoneyUtil.sum(totalAmount, shoppingCartBean.getShipping());
                        } else {
                            shoppingCartBean.setSelectSpeciesNum(0);
                        }
                        shoppingCartBean.setSelectFoodAmount(supplierTotalAmount);
                        totalAmount = MoneyUtil.sum(totalAmount, supplierTotalAmount);
                    }
                    return new Double[]{totalAmount, totalTypeFood};
                }
        ).doOnSubscribe(disposable -> mRootView.showLoading("加载中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<Double[]>(mErrorHandler) {
                    @Override
                    public void onNext(Double[] value) {
                        mRootView.setTotalInfo(value[1].intValue(), value[0]);
                        mRootView.notifyAdapter(-1);
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void addNewPurchaseOrder(List<PurchaseFoodBean> purchaseFoodBeans, String remarks) {
        NewPurchaseOrderBean newPurchaseOrderBean = new NewPurchaseOrderBean();
        newPurchaseOrderBean.setBrandId(Constant.getBrandId());
        newPurchaseOrderBean.setRestaurantId(Constant.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.NewPurchaseOrderDetailsBean> purchaseOrderDetailsBeans = new ArrayList<>();
        Observable.fromIterable(purchaseFoodBeans)
                .map(purchaseFoodListVosBean -> {
                    NewPurchaseOrderBean.NewPurchaseOrderDetailsBean orderDetailsBean = new NewPurchaseOrderBean.NewPurchaseOrderDetailsBean();
                    orderDetailsBean.setFoodId(purchaseFoodListVosBean.getId());
                    orderDetailsBean.setFoodPrice(purchaseFoodListVosBean.getUnitPrice());
                    orderDetailsBean.setFoodQuantity(purchaseFoodListVosBean.getFoodQuantity());
                    orderDetailsBean.setSupplierId(purchaseFoodListVosBean.getSupplierId());
                    return orderDetailsBean;
                }).subscribe(new Observer<NewPurchaseOrderBean.NewPurchaseOrderDetailsBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NewPurchaseOrderBean.NewPurchaseOrderDetailsBean 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 boolean filterData(List<ShoppingCartBean> shoppingCartBeans) {
        //判斷用戶是否擇了至少一個食品
        boolean isHasFood = false;
        if (shoppingCartBeans == null || shoppingCartBeans.size() <= 0) {
            mRootView.showMessage("請添加食材");
            return false;
        }
        for (ShoppingCartBean shoppingCartBean : shoppingCartBeans) {
            if (shoppingCartBean.isAllSelect()) {
                isHasFood = true;
                break;
            }
        }
        //沒有一個供應商的食品是全選的，需要對所有食品進行遍歷
        if (!isHasFood) {
            for (ShoppingCartBean shoppingCartBean : shoppingCartBeans) {
                for (PurchaseFoodBean purchaseFoodBean : shoppingCartBean.getFoodList()) {
                    if (purchaseFoodBean.isChecked()) {
                        isHasFood = true;
                        break;
                    }
                }
                if (isHasFood) {
                    break;
                }
            }
        }
        if (!isHasFood) {
            //沒有食品，不允許提交訂單，提示用戶
            mRootView.showMessage("請選擇採購食品");
            return false;
        }
        return true;
    }

    public void createOrder(List<ShoppingCartBean> shoppingCartBeans) {
        //將供應商和食材信息轉換為提交訂單的數據
        List<ConfirmOrderBean> confirmOrderBeanList = new ArrayList<>();
        for (int i = 0; i < shoppingCartBeans.size(); i++) {
            ShoppingCartBean shoppingCartBean = shoppingCartBeans.get(i);
            if (shoppingCartBean.getSelectSpeciesNum() > 0) {
                //判斷選中了多少個商品，如果這個供應商的食品一個都沒被選中，就不用提交他的數據
                ConfirmOrderBean confirmOrderBean = new ConfirmOrderBean();
                //在這裡再計算一遍總價，避免之前的計算出錯
                double totalAmount = 0;
                for (PurchaseFoodBean purchaseFoodBean : shoppingCartBean.getFoodList()) {
                    if (purchaseFoodBean.isChecked()) {
                        if (confirmOrderBean.getPurchaseOrderDetails() == null) {
                            confirmOrderBean.setPurchaseOrderDetails(new ArrayList<>());
                        }
                        //將食材信息加入訂單信息中
                        confirmOrderBean.getPurchaseOrderDetails().add(ConfirmOrderBean.conversionPurchaseOrderDetails(purchaseFoodBean));
                        totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(purchaseFoodBean.getUnitPrice(), purchaseFoodBean.getFoodQuantity()));
                    }
                }
                //判斷總金額是否滿足最低採購金額
                if (MoneyUtil.compareTo(totalAmount, shoppingCartBean.getMinimumAmount()) == -1) {
                    shoppingCartBean.setFlashing(true);
                    mRootView.notifyAdapter(i);
                    mRootView.showMessage("未達到【" + shoppingCartBean.getSupplierName() + "】最低採購金額");
                    return;
                }
                //配置訂單信息
                confirmOrderBean.setPurchaseOrder(ConfirmOrderBean.conversionPurchaseOrder(shoppingCartBean, totalAmount));
                confirmOrderBean.setMinimumAmount(shoppingCartBean.getMinimumAmount());
                confirmOrderBeanList.add(confirmOrderBean);
            }
        }
        addPurchaseOrder(confirmOrderBeanList);
    }

    private Disposable verificationDisposable;

    /**
     * 驗證最低採購金額是否都已經滿足
     */
    public void verificationMixAmount(List<ShoppingCartBean> shoppingCartBeans) {
        if (verificationDisposable != null) {
            verificationDisposable.dispose();
        }
        verificationDisposable = RxJavaUtils.executeAsyncTask(new RxAsyncTask<Object, Boolean>(1) {
            @Override
            public Boolean doInIOThread(Object o) {
                for (int i = 0; i < shoppingCartBeans.size(); i++) {
                    ShoppingCartBean shoppingCartBean = shoppingCartBeans.get(i);
                    //判斷選中了多少個商品，如果這個供應商的食品一個都沒被選中，就不用管
                    if (shoppingCartBean.getSelectSpeciesNum() > 0) {
                        //判斷總金額是否滿足最低採購金額
                        if (MoneyUtil.compareTo(shoppingCartBean.getSelectFoodAmount(), shoppingCartBean.getMinimumAmount()) == -1) {
                            //不滿足最低採購金額
                            return false;
                        }
                    }
                }
                return true;
            }

            @Override
            public void doInUIThread(Boolean o) {
                mRootView.setCreateBtnState(o);
            }
        });
    }


    public void addPurchaseOrder(List<ConfirmOrderBean> confirmOrderBeans) {
        if (confirmOrderBeans == null) {
            mRootView.showMessage("訂單計算出錯，請退出重試");
            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(GsonUtils.GsonString(baseResult.getData()), 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("創建訂單失敗，請稍後重試");
                        }
                    }
                });
    }
}
