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

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.common.bean.PayMethod;
import com.gingersoft.gsa.cloud.base.order.bean.BillOrderMoney;
import com.gingersoft.gsa.cloud.base.order.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.order.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.order.bean.discount.OrderDiscount;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.OpenTableManage;
import com.gingersoft.gsa.cloud.base.table.bean.TableBean;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.bean.R;
import com.gingersoft.gsa.cloud.bean.mvp.contract.AllOrderContract;
import com.gingersoft.gsa.cloud.bean.mvp.model.bean.OrderDetailItem;
import com.gingersoft.gsa.cloud.bean.mvp.model.utils.OrderAssemblyUtil;
import com.gingersoft.gsa.cloud.bean.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.bean.mvp.ui.activity.orderManager.OrderCenterActivity;
import com.gingersoft.gsa.cloud.bean.mvp.ui.activity.orderManager.OrderDetailActivity;
import com.gingersoft.gsa.cloud.bean.mvp.ui.adapter.OrderCenterAdapter;
import com.gingersoft.gsa.cloud.bean.mvp.ui.fragment.AllOrderFragment;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem3;
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.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

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

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/13/2020 16: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>
 * ================================================
 */
@FragmentScope
public class AllOrderPresenter extends BasePresenter<AllOrderContract.Model, AllOrderContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private OrderCenterActivity IActivity;
    private OrderCenterAdapter mOrderCenterAdapter;
    private List<OrderDetailItem> mOrderItemList = new ArrayList<>();


    @Inject
    public AllOrderPresenter(AllOrderContract.Model model, AllOrderContract.View rootView) {
        super(model, rootView);
        AllOrderFragment allOrderFragment = (AllOrderFragment) rootView;
        this.IActivity = (OrderCenterActivity) allOrderFragment.getCurrentActivity();
    }

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

    public void initOrderAdapter(Context context) {
        if (mOrderCenterAdapter == null) {
            mOrderCenterAdapter = new OrderCenterAdapter(context, mOrderItemList);
            mRootView.setAllOrderAdapter(mOrderCenterAdapter);
        }
        mOrderCenterAdapter.setOnItemClickListener(new OrderCenterAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(OrderDetailItem datasBean, int position) {
                Intent intent = new Intent(IActivity, OrderDetailActivity.class);
                intent.putExtra("orderDetailItem", datasBean);
                mRootView.launchActivity(intent);
            }

            @Override
            public void onPrintClick(OrderDetailItem datasBean, int position) {
                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(datasBean.getOrderDetails()));
                startPrintOrder(datasBean, orderDetailList);
            }

            @Override
            public void onModifyClick(OrderDetailItem datasBean, int position) {
                if(datasBean.getRestaurantTable() == null){
                    mRootView.showMessage("餐檯不存在,無法修改訂單");
                    return;
                }
                //設置為修改訂單操作
                MyOrderManage.getInstance().setModifyOrder(true);
                /**
                 * 緩存訂單信息
                 */
                OrderBean orderBean = new OrderBean();
                orderBean.setId(datasBean.getId());
                orderBean.setStatus(datasBean.getStatus());
                orderBean.setOrderNo(datasBean.getOrderNo());
                orderBean.setPerson(datasBean.getPerson());
                orderBean.setCreateTime(datasBean.getCreateTime());
                if (datasBean.getDiscountDetails() != null) {
                    orderBean.setDiscountDetails(datasBean.getDiscountDetails());
                }
                MyOrderManage.getInstance().setOrderBean(orderBean);

                TableBean.DataBean tableBean = new TableBean.DataBean(datasBean.getRestaurantTable());
                if (!TextUtils.isEmpty(tableBean.getTableNumber())) {
                    tableBean.setTableName(tableBean.getTableName() + "-" + tableBean.getTableNumber());
                } else {
                    tableBean.setTableName(tableBean.getTableName());
                }
                OpenTableManage.getDefault().setTableBean(tableBean);
                OpenTableManage.getDefault().setPeopleNumber(datasBean.getPerson());

                List<OrderBean.OrderDetailsBean> orderDetailsBeans = datasBean.getOrderDetails();
                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(orderDetailsBeans));
                MyOrderManage.getInstance().setOrderFoodList(orderDetailList);

                if (datasBean.getMemberInfo() != null) {
                    MyOrderManage.getInstance().setMemberInfo(datasBean.getMemberInfo());
                }

                Intent intent = new Intent(IActivity, MealStandActivity.class);
                IActivity.startActivityForResult(intent, OrderCenterActivity.MODIFY_ORDER_RETURN_CODE);
            }

            @Override
            public void onCancelClick(OrderDetailItem datasBean, int position) {
                showCancelDialog(datasBean.getId());
            }
        });
    }

    private void showCancelDialog(long orderId) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(IActivity);
        dialogBuilder.setTitle("溫馨提示");
        dialogBuilder.setTitleIcon(R.drawable.qmui_icon_dialog_doubt);
        dialogBuilder.setMessage("是否取消訂單?");
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            dialog.dismiss();
            IActivity.cancelOrder(orderId, mRootView.getOrderType());
        });
        dialogBuilder.addAction("取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    private void startPrintOrder(OrderDetailItem orderDetailItem, List<OrderDetail> orderDetailList) {
        double wholeAmount = getWholeAmount(orderDetailList);

        MyOrderManage.getInstance().setOrderFoodList(orderDetailList);
        MyOrderManage.getInstance().setOrderMoneyList(getOrderMoneyList(orderDetailItem, wholeAmount));
        MyOrderManage.getInstance().setOrderId(orderDetailItem.getId());
        MyOrderManage.getInstance().setWholeAmount(wholeAmount);
        MyOrderManage.getInstance().setTotalAmount(orderDetailItem.getTotalAmount());

        OpenTableManage.getDefault().setPeopleNumber(orderDetailItem.getPerson());
        TableBean.DataBean dataBean = new TableBean.DataBean();
        dataBean.setTableName(orderDetailItem.getTableName());
        if(!TextUtils.isEmpty(orderDetailItem.getCreateTime())) {
            dataBean.setCreateTime(TimeUtils.getStringByFormat(new Date(orderDetailItem.getCreateTime()), TimeUtils.DEFAULT_DATE_FORMAT_YMDHM));
        }
        OpenTableManage.getDefault().setTableBean(dataBean);

        if (orderDetailItem.getMemberInfo() != null) {
            MyOrderManage.getInstance().setMemberInfo(orderDetailItem.getMemberInfo());
        } else {
            MyOrderManage.getInstance().setIntegralQrcode(orderDetailItem.getVerifyCode());
        }
        List<PayMethod> payMethodList = getPayMethodList(orderDetailItem.getOrderPays());
        if (payMethodList != null) {
            //設置打印所需支付方式
            MyOrderManage.getInstance().setBillMoney(payMethodList);
        }
        CC.obtainBuilder("Component.Print")
                .setActionName("printActivity")
                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_BILL)
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    Log.e("error", "是否成功打印：" + result.isSuccess());

                    MyOrderManage.getInstance().clear();
                    OpenTableManage.getDefault().setPeopleNumber(0);
                    OpenTableManage.getDefault().setTableBean(null);
                });
    }

    private List<BillOrderMoney> getOrderMoneyList(OrderDetailItem orderDetailItem, double totalMoney) {
        List<SectionTextItem3> printOrderMoneyList = new ArrayList<>();
        List<BillOrderMoney> printBillOrderMoneyList = new ArrayList<>();
        SectionTextItem3 serviceAmountSection = getOrderServiceAmountSection(orderDetailItem);
        if (serviceAmountSection != null) {
            printOrderMoneyList.add(serviceAmountSection);
        }

        List<SectionTextItem3> discountSections = getOrderDiscountSections(orderDetailItem);
        if (discountSections != null) {
            printOrderMoneyList.addAll(discountSections);
        }

        SectionTextItem3 roudingSection = getOrderRoudingSection(orderDetailItem);
        if (roudingSection != null) {
            printOrderMoneyList.add(roudingSection);
        }
        for (SectionTextItem3 item : printOrderMoneyList) {
            BillOrderMoney billOrderMoney = new BillOrderMoney();
            billOrderMoney.setTitle(item.getLeftText());
            billOrderMoney.setMoney(Double.parseDouble(item.getRightText()));
            printBillOrderMoneyList.add(billOrderMoney);
        }
        return printBillOrderMoneyList;
    }

    /**
     * 返回合計金額
     *
     * @return
     */
    private double getWholeAmount(List<OrderDetail> orderDetailList) {
        double otherMoney = 0.0;
        for (OrderDetail item : orderDetailList) {
            otherMoney = MoneyUtil.sum(otherMoney, item.getPrice());
        }
        return otherMoney;
    }


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

    private SectionTextItem3 discountTransSectionTextItem3(OrderDiscount.Respose 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.base.R.style.order_paymethod_text_style);
        sectionTextItem3.setRightTextStyle(com.gingersoft.gsa.cloud.base.R.style.order_paymethod_text_style);
        return sectionTextItem3;
    }

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

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

    /**
     * 獲取支付方式
     *
     * @param orderPays
     * @return
     */
    private List<PayMethod> getPayMethodList(List<OrderDetailItem.OrderPayBean> orderPays) {
        List<PayMethod> payMethodList = new ArrayList<>();
        if (orderPays != null) {
            for (OrderDetailItem.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;
    }

    public void updateOrderData(List<OrderDetailItem> orderItemList) {
        if (orderItemList != null) {
            mOrderItemList.clear();
            mOrderItemList.addAll(orderItemList);
            mOrderCenterAdapter.notifyDataSetChanged();
        }
    }

    public void addOrderItem(List<OrderDetailItem> orderItemList) {
        if (orderItemList != null) {
            mOrderItemList.addAll(orderItemList);
            mOrderCenterAdapter.notifyDataSetChanged();
        }
    }

}
