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

import android.app.Application;
import android.text.TextUtils;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.common.bean.MemberInfo;
import com.gingersoft.gsa.cloud.base.common.bean.PayMethod;
import com.gingersoft.gsa.cloud.base.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.base.order.bean.OrderPayRequest;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.constans.FoodSummaryConstans;
import com.gingersoft.gsa.cloud.table.BuildConfig;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderPayContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.OrderPayRespose;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderPayActivity;
import com.gingersoft.gsa.cloud.ui.view.OrderPayView;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.List;

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 01/09/2020 19:25
 * <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 OrderPayPresenter extends BaseOrderPresenter<OrderPayContract.Model, OrderPayContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private OrderPayActivity IActivity;

    //    private BillMethodAdapter mBillMethodAdapter;
//    private ArrayList<PayMethod> mBillMethodList = new ArrayList<>();
//
//    private BillMoneyAdapter mBillMoneyAdapter;
    private List<PayMethod> mBillMoneyList;

    /**
     * 0#店內支付
     * 1#貨到付款
     * 2#在線支付
     */
    private final int orderPayType = 0;

    /**
     * 找零
     */
    public static final int LINE_PAY_TYPE_CHANGE = 1;
    /**
     * 貼士
     */
    public static final int LINE_PAY_TYPE_TIPS = 2;


    @Inject
    public OrderPayPresenter(OrderPayContract.Model model, OrderPayContract.View rootView) {
        super(model, rootView);
        this.IActivity = (OrderPayActivity) rootView;
    }

    @Override
    public void createOrder(boolean isPrint, Class afterToActivity) {
    }

    @Override
    public void addOrderFood(boolean isPrint, Class afterToActivity) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void initAdapter() {
        if (mSelectMealAdapter != null) {
            mRootView.setFoodAdapter(mSelectMealAdapter);
        }
        if (mOrderMoneyAdapter != null) {
            mRootView.setOrderDetailAdapter(mOrderMoneyAdapter);
        }
//        if (mBillMethodAdapter == null) {
//            mBillMethodAdapter = new BillMethodAdapter(mBillMethodList);
//            mRootView.setBillMethodAdapter(mBillMethodAdapter);
//        }
//        if (mBillMoneyAdapter == null) {
//            mBillMoneyAdapter = new BillMoneyAdapter(mBillMoneyList);
//            mRootView.setBillMoneyAdapter(mBillMoneyAdapter);
//        }
    }

//    public void initBillListener() {
//        mBillMethodAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//
//                mRootView.recordOperat(true);
//
//                PayMethod method = (PayMethod) adapter.getItem(position);
////                if (!isCashPayMethod(method)) {
////                    PayMethod N5PayMethod = getSelectN5PayMethod();
////                    if (N5PayMethod != null) {
////                        //最多選擇2中支付方式（現金+其他）
////                        mBillMoneyList.remove(N5PayMethod);
////                        mBillMoneyAdapter.notifyDataSetChanged();
////                    }
////                }
//                mBillMoneyList.clear();
////                if (!mBillMoneyList.contains(method)) {
//                double differenceMoney = getDifferenceMoney();
//                if (differenceMoney > -1) {
//                    //補足差額
//                    method.setPayMoney(differenceMoney);
//                }
//                //添加選中支付方式
//                mBillMoneyList.add(method);
//                mBillMoneyAdapter.setSelect_position(mBillMoneyList.size() - 1);
//                mBillMoneyAdapter.notifyDataSetChanged();
//                mRootView.setBillMoneyRvScrollToPosition(mBillMoneyList.size() - 1);
//                //設置差額狀態
//                mRootView.setDifferenceText();
////                }
//            }
//        });
//        mBillMoneyAdapter.setOnItemClickListener(new BillMoneyAdapter.OnItemClickListener() {
//
//            @Override
//            public void onItemClick(PayMethod datasBean, int position) {
//                mRootView.recordOperat(true);
//                mBillMoneyAdapter.setSelect_position(position);
//                mBillMoneyAdapter.notifyDataSetChanged();
//            }
//
//            @Override
//            public void onItemDeleteClick(PayMethod datasBean, int position) {
//                mRootView.recordOperat(true);
//                //刪除當前付款方式
//                mBillMoneyList.remove(position);
//                mBillMoneyAdapter.setSelect_position(mBillMoneyList.size() - 1);
//                mBillMoneyAdapter.notifyDataSetChanged();
//                //設置差額狀態
//                mRootView.setDifferenceText();
//            }
//        });
//    }

    public void getPayMethods() {
        int brandId = GsaCloudApplication.getBrandId();
        int restaurantId = GsaCloudApplication.getRestaurantId();
        mModel.getPayMethods(brandId, restaurantId, FoodSummaryConstans.RESTAURANT_MODE)
                .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(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            List<PayMethod> payMethods = JsonUtils.parseArray(baseResult.getData(), PayMethod.class);
                            for (int i = 0; i < payMethods.size(); i++) {
                                //這裡有對象為null的情況 排除掉
                                if (payMethods.get(i) == null) {
                                    payMethods.remove(i);
                                }
                                if (BuildConfig.DEBUG) {
                                    if (i == 0) {
                                        payMethods.get(i).setPayType(PayMethod.PAY_TYPE_INTEGRAL);
                                        payMethods.get(i).setPayName("測試積分支付");
                                    }
                                }
                            }
                            mRootView.loadPayMethodsSuccess(payMethods);
                        }
                    }
                });
    }

    /**
     * 結賬
     */
    public void toOrderPay(boolean show) {
        if (mDoshokuOrder.isModifyOrder()) {
            //修改訂單
            updateOrderPay();
            return;
        }
        OrderPayView orderPayView = IActivity.getGsaPayView();
        if (orderPayView.getBillMoneyList() == null || orderPayView.getBillMoneyList().size() == 0) {
            return;
        }

        String payRequest = GsonUtils.GsonString(getOrderPayRequest(orderPayView));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), payRequest);
        String json = GsonUtils.GsonString(payRequest);

        mModel.toOrderPay(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (show) {
                        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(BaseResult baseResult) {
                        mRootView.hideLoading();
                        if (baseResult.isSuccess()) {
                            OrderPayRespose orderPayRespose = JsonUtils.parseObject(baseResult.getData(), OrderPayRespose.class);
                            if (orderPayRespose != null) {
                                if (mDoshokuOrder.getMemberInfo() != null) {
                                    mDoshokuOrder.setAddPoints(orderPayRespose.getAddPoints());
                                    mDoshokuOrder.setNowPoints(orderPayRespose.getNowPoints());
                                    mDoshokuOrder.setOldPoints(orderPayRespose.getOldPoints());
                                } else {
                                    if (!TextUtils.isEmpty(orderPayRespose.getVerifyCode())) {
                                        mDoshokuOrder.setIntegralQrcode(orderPayRespose.getVerifyCode());
                                    }
                                }
                            }
                            //結賬成功
                            mRootView.paySuccess();
                        } else {
                            mRootView.showMessage(baseResult.getErrMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.hideLoading();
                    }
                });
    }

    private OrderPayRequest getOrderPayRequest(OrderPayView orderPayView) {

        MemberInfo memberInfo = mDoshokuOrder.getMemberInfo();

        List<PayMethod> payMethodList = orderPayView.getBillMoneyList();

        OrderPayRequest payRequest = new OrderPayRequest();
        payRequest.setOrderId(mDoshokuOrder.getOrderId());
        payRequest.setOrderPayType(orderPayType);
        payRequest.setLinePayType(orderPayView.getLinePayType());
        payRequest.setTableId(mTableInfo.getId());
        payRequest.setTableNumber(mTableInfo.getTableNumber());
        if (memberInfo != null) {
            payRequest.setMemberId(memberInfo.getId());
            payRequest.setCouponId(getCouponDiscountId());
        }
        payRequest.setPointsAdd(getPointsAdd());
        payRequest.setPointsUse(getPointsRedeem());

        int whetherFreeService = 0;
        for (int i = 0; i < payMethodList.size(); i++) {
            PayMethod payMethod = payMethodList.get(i);
            OrderPayRequest.OrderPay orderPay = new OrderPayRequest.OrderPay();
            orderPay.setPayType(payMethod.getPayType());
            if (payMethodList.size() == 2) {
                if (i == 1) {
                    //小费放在第二种支付方式里面
                    orderPay.setTipsPrice(orderPayView.getTipsPrice());
                }
            } else {
                orderPay.setTipsPrice(orderPayView.getTipsPrice());
            }
            if (orderPay.getPayType() == PayMethod.PAY_TYPE_INTEGRAL) {
                double consumptionPoints = orderPayView.getPayForConsumptionPoints(null, memberInfo.getPointRedeemCash());
                orderPay.setConsumptionPoints(consumptionPoints);
//                //減去積分支付所用的積分
//                payRequest.setPointsUse(MoneyUtil.sum(payRequest.getPointsUse(), consumptionPoints));
            }
            whetherFreeService = payMethod.getWhetherFreeService();
            orderPay.setAmount(payMethod.getPayMoney());
            payRequest.getOrderPays().add(orderPay);
        }
        payRequest.setWhetherFreeService(whetherFreeService);

        return payRequest;
    }

    /**
     * 修改訂單更新支付方式
     */
    public void updateOrderPay() {
        OrderPayView orderPayView = IActivity.getGsaPayView();
        if (orderPayView.getBillMoneyList() == null || orderPayView.getBillMoneyList().size() == 0) {
            return;
        }

        String payRequest = GsonUtils.GsonString(getOrderPayRequest(orderPayView));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), payRequest);

        mModel.updateOrderPay(requestBody)
                .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(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            //結賬成功
                            mRootView.paySuccess();
                        }
                    }
                });
    }

    /**
     * 結賬前創建訂單或添加食品
     */
    public void sendOrderBefore() {
//        if (hasNesOrderFoods() || getNesOrderDiscount() != null || hasDeleteFood()) {
//            //有食品或折扣未送單 先送單
//            sendOrder(false);
//        } else {
        //去結賬
        toOrderPay(true);
//        }
    }

    /**
     * 是否修刪除過食品
     *
     * @return
     */
    private boolean hasDeleteFood() {
        for (OrderDetail item : mOrderMealList) {
            if (item.isModify()) {
                return true;
            }
        }
        return false;
    }

    public void setFreeServiceStauts(boolean isUseFreeServicePayMethod) {
        //更新服務費中劃線
        mOrderMoneyAdapter.FreeServiceStauts(isUseFreeServicePayMethod);
        //更新總金額
        updateBillInfo();
        OrderPayView orderPayView = IActivity.getGsaPayView();
        if (orderPayView != null) {
            orderPayView.setTotalAmount(getTotalAmount());
            orderPayView.initOrderDetail();
            orderPayView.setDifferenceText(GsaCloudApplication.getAppContext());
        }
    }

    /**
     * 獲取當前選中的支付方式
     *
     * @return
     */
    public PayMethod getSelectBillMoney() {
//        for (int i = 0; i < mBillMoneyList.size(); i++) {
//            if (i == mBillMoneyAdapter.getSelect_position())
//                return mBillMoneyList.get(i);
//        }
        return null;
    }

    /**
     * 獲取超出的金額為找零還是貼士: linePayType 1 tipsPrice 为找零  2 tipsPrice为贴上
     * 現金，掃碼QR = 找零
     * 信用卡 = 貼士
     *
     * @return 第一階段默認為找零
     */
    public int getLinePayType() {
        return LINE_PAY_TYPE_CHANGE;
    }

    /**
     * 獲取找零或貼士金額
     *
     * @return
     */
    public double getTipsPrice() {
        double tips = 0.0;
        double difference = getDifferenceMoney();
        if (difference < 0) {
            tips = difference;
        }
        return Math.abs(tips);
    }

    /**
     * 獲取支付差額
     *
     * @return
     */
    public double getDifferenceMoney() {
        double differenceMoney = MoneyUtil.sub(getTotalAmount(), getBillMoney());
        return MoneyUtil.get_ItemDecimals_money(differenceMoney);
    }

    /**
     * 獲取支付總額
     *
     * @return
     */
    private double getBillMoney() {
        double totalMoney = 0.0;
//        for (PayMethod method : mBillMoneyList) {
//            totalMoney = MoneyUtil.sum(totalMoney, method.getPayMoney());
//        }
        return totalMoney;
    }

    /**
     * 額外食品加分
     *
     * @return
     */
    public double getPointsAdd() {
        double pointsAdd = 0;
        for (OrderDetail orderDetail : mOrderMealList) {
            if (orderDetail.getType() == OrderDetail.FOOD_TYPE) {
                pointsAdd = MoneyUtil.sum(pointsAdd, MoneyUtil.multiply(orderDetail.getPointsAdd(), orderDetail.getNumber()));
            }
        }
        return pointsAdd;
    }

    /**
     * 換購食品所需積分
     *
     * @return
     */
    public double getPointsRedeem() {
        double pointsRedeem = 0;
        for (OrderDetail orderDetail : mOrderMealList) {
            if (orderDetail.getType() == OrderDetail.FOOD_TYPE) {
                pointsRedeem = MoneyUtil.sum(pointsRedeem, MoneyUtil.multiply(orderDetail.getPointsRedeem(), orderDetail.getNumber()));
            }
        }
        return pointsRedeem;
    }

    /**
     * 是否滿足支付條件
     *
     * @return
     */
    public boolean canPay() {
        double difference = getDifferenceMoney();
        if (difference <= 0) {
            return true;
        }
        return false;
    }

    //
    public List<PayMethod> getBillMoneyList() {
        return mBillMoneyList;
    }

    public void setBillMoneyList(List<PayMethod> mBillMoneyList) {
        this.mBillMoneyList = mBillMoneyList;
    }
}
