package com.gingersoft.gsa.cloud.table.mvp.action.order;

import android.text.TextUtils;
import android.util.Log;
import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.patterns.Strategy;
import com.gingersoft.gsa.cloud.common.utils.AppDevices;
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.order.bean.response.OrderDiscountResponse;
import com.gingersoft.gsa.cloud.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.order.billItem.BillOrderMoney;
import com.gingersoft.gsa.cloud.order.cart.ShoppingCart;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.pay.bean.PayMethod;
import com.gingersoft.gsa.cloud.print.bean.PrintContent;
import com.gingersoft.gsa.cloud.print.bean.adapter.PrintContentAdapter;
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.ui.bean.view.SectionTextItem3;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.mvp.IView;

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

/**
 * @作者: bin
 * @創建時間: 2021-01-15 15:19
 * @更新時間: 2021-01-15 15:19
 * @描述:打印账单
 */
public class PrintOrderAction implements Strategy<OrderManagerResponse> {

    private final  String TAG = "PrintOrderAction";
    private BaseFragmentActivity mActivity;
    private IView mRootView;

    public PrintOrderAction(BaseFragmentActivity fragmentActivity, IView rootView){
        this.mActivity  = fragmentActivity;
        this.mRootView = rootView;
    }

    @Override
    public void action(OrderManagerResponse orderItem) {
        List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(orderItem.getOrderDetails()));
        startPrintOrder(orderItem, orderDetailList);
    }

    @Override
    public void destroy() {
        mActivity = null;
        mRootView = null;
    }

    private void startPrintOrder(OrderManagerResponse orderDetailItem, List<OrderDetail> orderDetailList) {

        DoshokuOrder doshokuOrder = DoshokuOrder.getInstance();
        ShoppingCart shoppingCart = doshokuOrder.getShoppingCart();

        double wholeAmount = getWholeAmount(orderDetailList);

        doshokuOrder.setOrderId(orderDetailItem.getId());
        doshokuOrder.setOrderNo(orderDetailItem.getOrderNo());
        doshokuOrder.setNewFoodList(orderDetailList);
        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());
        dataBean.setPerson(orderDetailItem.getPerson());
        if (!TextUtils.isEmpty(orderDetailItem.getCreateTime())) {
            dataBean.setCreateTime(TimeUtils.getStringByFormat(new Date(orderDetailItem.getCreateTime()), TimeUtils.DEFAULT_DATE_FORMAT_YMDHM));
        }
        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);
        }

        if (orderDetailItem.withHywebPay() && AppDevices.isHywebPos()) {
            printPosStub(orderDetailItem,doshokuOrder,dataBean);
        }else {
            printBill(orderDetailItem,doshokuOrder, dataBean,false);
        }
    }

    private void printPosStub(OrderManagerResponse orderDetailItem, DoshokuOrder doshokuOrder, TableBean.DataBean dataBean) {
//        PosPay.printStub(mActivity, mRootView, orderDetailItem.getPayTxnId(), new OnPosActionListener() {
//            @Override
//            public void onPosSuccess(HywebPosResponse response) {
//                if(printlListener != null){
//                    printlListener.printPosStubResult(true);
//                }
//                printBill(orderDetailItem,doshokuOrder, dataBean,true);
//            }
//
//            @Override
//            public void onPosException(HywebPosResponse response, Exception e) {
//                if(printlListener != null){
//                    printlListener.printPosStubResult(false);
//                }
//                printBill(orderDetailItem,doshokuOrder, dataBean,true);
//            }
//
//            @Override
//            public void onPosInvalid(String e) {
//                printBill(orderDetailItem,doshokuOrder, dataBean,true);
//            }
//
//            @Override
//            public void onUpdateStatusSuccess(HywebPosResponse response) {
//            }
//
//            @Override
//            public void onUpdateStatusError(Throwable e) {
//            }
//        });
    }

    private void printBill(OrderManagerResponse orderDetailItem,DoshokuOrder doshokuOrder, TableBean.DataBean dataBean,boolean printStub) {
        PrintContent printContent = new PrintContentAdapter().adaptationBillContent(doshokuOrder, dataBean);
        CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                .setActionName("printActivity")
                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_BILL)
                .addParam(PrintConstans.PRINT_CONTENT, printContent)
                .addParam(PrintConstans.PRINT_ORDER_NO,doshokuOrder.getOrderNo())
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    Log.e("error", "是否成功打印：" + result.isSuccess());
                    if (printStub) {
                        printPosStub(orderDetailItem,doshokuOrder,dataBean);
                    }
                    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;
    }

    private PrintOrderAction.OnPrintlListener printlListener;
    public void setPrintlListener(OnPrintlListener printlListener) {
        this.printlListener = printlListener;
    }
    public interface OnPrintlListener{
        void printPosStubResult(boolean success);
    }
}
