package com.gingersoft.gsa.cloud.table.mvp.presenter.orderManager;

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.order.bean.response.OrderDiscountResponse;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.pay.bean.PayMethod;
import com.gingersoft.gsa.cloud.pay.pos.fragment.PosActionStatusExceptionFragment;
import com.gingersoft.gsa.cloud.pay.util.PayMethodUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderDetailContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.response.OrderManagerResponse;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem3;
import com.jess.arms.di.scope.ActivityScope;
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 org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/13/2020 14:29
 * <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>
 * ================================================
 */
@ActivityScope
public class OrderDetailPresenter extends BaseOrderConterPresenter<OrderDetailContract.Model, OrderDetailContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;


    @Inject
    public OrderDetailPresenter(OrderDetailContract.Model model, OrderDetailContract.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 getOrderDetailItem(long orderId) {
        mModel.getOrderDetailItem(orderId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult result) {
                        if (result.isSuccess()) {
                            if (result.getData() != null) {
                                OrderManagerResponse orderDetailItem = JsonUtils.parseObject(JsonUtils.toJson(result.getData()), OrderManagerResponse.class);
                                mRootView.returnOrderDetail(orderDetailItem);
                            } else {
                                mRootView.showMessage("獲取賬單失敗");
                            }
                        } else {
                            mRootView.showMessage("獲取賬單失敗");
                        }
                    }
                });
    }

    public void cancelOrder(long orderId) {
        mModel.cancelOrder(orderId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult result) {
                        if (result.isSuccess()) {
                            if (result.getData() != null) {
                                OrderManagerResponse orderDetailItem = JsonUtils.parseObject(JsonUtils.toJson(result.getData()), OrderManagerResponse.class);
                                mRootView.returnOrderDetail(orderDetailItem);
                                //刷新訂單列表
                                EventBus.getDefault().post(true, PosActionStatusExceptionFragment.REFREAFSH_ORDER_EVENT);
                            } else {
                                mRootView.showMessage("獲取賬單失敗");
                            }
                        } else {
                            mRootView.showMessage("獲取賬單失敗");
                        }
                    }
                });
    }


    public boolean containCardPayment(List<OrderManagerResponse.OrderPayBean> orderPays){
        if (orderPays != null && orderPays.size() > 0) {
            List<PayMethod> payMethods = new ArrayList<>();
            for (OrderManagerResponse.OrderPayBean orderPayBean : orderPays) {
                PayMethod payMethod = new PayMethod();
                payMethod.setPayType(orderPayBean.getPayType());
                payMethod.setPayMoney(orderPayBean.getAmount());
                payMethod.setTipsPrice(orderPayBean.getTipsPrice());
                payMethods.add(payMethod);
            }
            PayMethod payMethod = PayMethodUtils.filterPaymentMethodById(payMethods, PayMethod.HYWEB_POS_TYPE_CC);
            if (payMethod != null) {
                //只有卡片支付才支持補小費
                return true;
            }
        }
        return false;
    }

    public  List<SectionTextItem3> orderPayMethodTransSectionTextItem3(List<PayMethod> payMethodList) {
        List<SectionTextItem3> sectionTextItem3List = new ArrayList<>();
        for (PayMethod payMethod : payMethodList) {
            SectionTextItem3 sectionTextItem3 = new SectionTextItem3();
            sectionTextItem3.setLeftText(payMethod.getPayName());
            sectionTextItem3.setCenterText(String.valueOf(0));
            sectionTextItem3.setRightText(String.valueOf(payMethod.getPayMoney()));
            sectionTextItem3.setLeftTextStyle(R.style.order_paymethod_text_style);
            sectionTextItem3.setRightTextStyle(R.style.order_paymethod_text_style);
            sectionTextItem3List.add(sectionTextItem3);
        }
        return sectionTextItem3List;
    }

    public  List<SectionTextItem3> orderDetailTransSectionTextItem3(List<OrderDetail> orderDetailList) {
        List<SectionTextItem3> sectionTextItem3List = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            SectionTextItem3 sectionTextItem3 = new SectionTextItem3();
            String foodName;
            switch (orderDetail.getItemType()) {
                case 2:
                    foodName = "    " + orderDetail.getProductName();
                    break;
                case 3:
                    foodName = "       " + orderDetail.getProductName();
                    break;
                default:
                    foodName = orderDetail.getProductName();
                    break;
            }
            sectionTextItem3.setLeftText(foodName);
            sectionTextItem3.setCenterText(String.valueOf(orderDetail.getNumber()));
            sectionTextItem3.setRightText(String.valueOf(orderDetail.getPrice()));
            sectionTextItem3List.add(sectionTextItem3);
        }
        return sectionTextItem3List;
    }

    /**
     * 獲取支付方式
     *
     * @param orderPays
     * @return
     */
    public List<PayMethod> getPayMethodList(List<OrderManagerResponse.OrderPayBean> orderPays) {
        List<PayMethod> payMethodList = new ArrayList<>();
        if (orderPays != null) {
            for (OrderManagerResponse.OrderPayBean orderPayBean : orderPays) {
                PayMethod payMethod = new PayMethod();
                payMethod.setPayName(orderPayBean.getPayName());
                payMethod.setPayMoney(orderPayBean.getAmount());
                payMethodList.add(payMethod);
                if (orderPayBean.getTipsPrice() != 0) {
                    //打印添加找零或貼士行
                    String linePayType = orderPayBean.getLinePayType() == 1 ? "找零" : "貼士";
                    PayMethod payMethod2 = new PayMethod();
                    //這裡打印退一格
                    payMethod2.setPayName("     " + linePayType);
                    payMethod2.setPayMoney(orderPayBean.getTipsPrice());
                    payMethodList.add(payMethod2);
                }
            }
        }
        return payMethodList;
    }

    /**
     * 獲取賬單折扣列
     *
     * @param orderDetailItem
     * @return
     */
    public List<SectionTextItem3> getOrderDiscountSections(OrderManagerResponse orderDetailItem) {
        List<SectionTextItem3> sectionTextItem3s = null;
        if (orderDetailItem.getDiscountDetails() != null) {
            sectionTextItem3s = new ArrayList<>();
            //折扣
            for (OrderDiscountResponse discount : orderDetailItem.getDiscountDetails()) {
                sectionTextItem3s.add(discountTransSectionTextItem3(discount));
            }
        }
        return sectionTextItem3s;
    }

    public SectionTextItem3 discountTransSectionTextItem3(OrderDiscountResponse discount) {
        SectionTextItem3 sectionTextItem3 = new SectionTextItem3();
        sectionTextItem3.setLeftText(discount.getRemark());
        sectionTextItem3.setCenterText(String.valueOf(0));
        sectionTextItem3.setRightText(String.valueOf(discount.getDiscountAmount()));
        sectionTextItem3.setLeftTextStyle(com.gingersoft.gsa.cloud.common.R.style.order_paymethod_text_style);
        sectionTextItem3.setRightTextStyle(com.gingersoft.gsa.cloud.common.R.style.order_paymethod_text_style);
        return sectionTextItem3;
    }

    /**
     * 獲取賬單小數列
     *
     * @param orderDetailItem
     * @return
     */
    public SectionTextItem3 getOrderRoudingSection(OrderManagerResponse orderDetailItem) {
        if (orderDetailItem.getRounding() != null && orderDetailItem.getRounding() != 0) {
            return SectionTextItem3.roundingTransSectionTextItem3(orderDetailItem.getRounding());
        }
        return null;
    }

    /**
     * 获取服務費
     *
     * @param orderDetailItem
     * @return
     */
    public SectionTextItem3 getOrderServiceAmountSection(OrderManagerResponse orderDetailItem) {
        if (orderDetailItem.getServiceAmount() != null && orderDetailItem.getServiceAmount() != 0) {
            return SectionTextItem3.serviceAmountTransSectionTextItem3(orderDetailItem.getServiceAmount());
        }
        return null;
    }

    /**
     * 返回合計金額
     *
     * @return
     */
    public double getTotalMoney(List<SectionTextItem3> orderCenterDetailFoodList) {
        double otherMoney = 0.0;
        for (SectionTextItem3 item : orderCenterDetailFoodList) {
            otherMoney = MoneyUtil.sum(otherMoney, Double.parseDouble(item.getRightText()));
        }
        return MoneyUtil.get_ItemDecimals_money(otherMoney);
    }
}
