package com.gingersoft.gsa.cloud.table.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.common.core.pay.PayMethod;
import com.gingersoft.gsa.cloud.common.core.order.bean.response.OrderDiscountResponse;
import com.gingersoft.gsa.cloud.common.core.order.bean.response.OrderResponse;
import com.gingersoft.gsa.cloud.common.core.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.common.core.order.billItem.BillOrderMoney;
import com.gingersoft.gsa.cloud.common.core.order.cart.ShoppingCart;
import com.gingersoft.gsa.cloud.common.core.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.common.core.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.mvp.contract.AllOrderContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.response.OrderManagerResponse;
import com.gingersoft.gsa.cloud.table.mvp.model.utils.OrderAssemblyUtil;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.orderManager.OrderCenterActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.orderManager.OrderDetailActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderCenterAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.AllOrderFragment;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.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<OrderManagerResponse> mOrderItemList = new ArrayList<>();

    private DoshokuOrder doshokuOrder ;
    private ShoppingCart shoppingCart ;

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

    @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(OrderManagerResponse datasBean, int position) {
                Intent intent = new Intent(IActivity, OrderDetailActivity.class);
                intent.putExtra("orderDetailItem", datasBean);
                mRootView.launchActivity(intent);
            }

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

            @Override
            public void onModifyClick(OrderManagerResponse datasBean, int position) {
                if (datasBean.getRestaurantTable() == null) {
                    mRootView.showMessage("餐檯不存在,無法修改訂單");
                    return;
                }

                //設置為修改訂單操作
                doshokuOrder.setModifyOrder(true);
                /**
                 * 緩存訂單信息
                 */
                OrderResponse orderBean = new OrderResponse();
                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());
                }
                doshokuOrder.setOrderPlaced(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());
                }
                tableBean.setPerson(datasBean.getPerson());
                doshokuOrder.setOpenTableInfo(tableBean);

                List<OrderResponse.OrderDetailsBean> orderDetailsBeans = datasBean.getOrderDetails();
                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(orderDetailsBeans));
                doshokuOrder.getShoppingCart().addCommodityList(orderDetailList);

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

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

            @Override
            public void onCancelClick(OrderManagerResponse 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(OrderManagerResponse orderDetailItem, List<OrderDetail> orderDetailList) {
        double wholeAmount = getWholeAmount(orderDetailList);

        doshokuOrder.setOrderId(orderDetailItem.getId());
        shoppingCart.setOrderCommodityList(orderDetailList);
        shoppingCart.setBillItemList(getOrderMoneyList(orderDetailItem, wholeAmount));
        shoppingCart.setWholeAmount(wholeAmount);
        shoppingCart.setTotalAmount(orderDetailItem.getTotalAmount());

        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));
        }
        dataBean.setPerson(orderDetailItem.getPerson());
        doshokuOrder.setOpenTableInfo(dataBean);

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

    private ArrayList<BillItem> getOrderMoneyList(OrderManagerResponse orderDetailItem, double totalMoney) {
        List<SectionTextItem3> printOrderMoneyList = new ArrayList<>();
        ArrayList<BillItem> 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.setName(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(OrderManagerResponse orderDetailItem) {
        List<SectionTextItem3> sectionTextItem3s = null;
        if (orderDetailItem.getDiscountDetails() != null) {
            sectionTextItem3s = new ArrayList<>();
            //折扣
            for (OrderDiscountResponse discount : orderDetailItem.getDiscountDetails()) {
                sectionTextItem3s.add(discountTransSectionTextItem3(discount));
            }
        }
        return sectionTextItem3s;
    }

    private 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
     */
    private SectionTextItem3 getOrderRoudingSection(OrderManagerResponse orderDetailItem) {
        if (orderDetailItem.getRounding() != null && orderDetailItem.getRounding() != 0) {
            return SectionTextItem3.roundingTransSectionTextItem3(orderDetailItem.getRounding());
        }
        return null;
    }

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

    /**
     * 獲取支付方式
     *
     * @param orderPays
     * @return
     */
    private 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;
    }

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

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

}
