package com.miya.fastcashier.service

import android.text.TextUtils
import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.beans.ViewOrderStatisticsInfo
import com.miya.fastcashier.utils.DateUtils
import com.miya.fastcashier.utils.MiYaPayPlantformPayWayEnum
import com.miya.fastcashier.utils.StringPriceFormat
import com.miya.fastcashier.utils.isEmpty
import com.miya.print.BuildConfig
import com.miya.print.IPrinter
import com.miya.print.PrinterManager
import com.miya.print.utils.Page58MmPrintUtils
import com.miya.print.utils.PrintLogger
import com.sdy.miya.moblie.component.pay.platform.bean.PayServiceResponse
import com.tencent.mmkv.MMKV
import java.lang.Exception
import java.util.*

object PrintService {

    private var payServiceResponse: PayServiceResponse? = null;


    /**
     * 退款
     */
    fun refundPrint(
        selfCashierAccountInfo: SelfCashierAccountInfo,
        payServiceResponse: PayServiceResponse
    ) {
        val printer = PrinterManager.getInstance().printer
        printer.beginPrint()
        //检查打印机状态
        printer.printerStatus
        printer.set58mm()
        refundPrintCashier(printer, payServiceResponse, selfCashierAccountInfo)
        refundPrintCustomer(printer, payServiceResponse, selfCashierAccountInfo)
        printer.feedPaper()
        printer.endPrint()
    }

    /**
     * 打印上一单
     */
    fun printLastOrderInfo() {
        if (payServiceResponse == null) {
            throw java.lang.RuntimeException("暂无上一单信息")
        } else {
            AccountService.getAccountInfo()?.let { payInfoPrint(payServiceResponse!!, it) }
        }
    }

    /**
     * 扣款信息打印
     */
    fun payInfoPrint(
        payServiceResponse: PayServiceResponse,
        selfCashierAccountInfo: SelfCashierAccountInfo
    ) {
        //保存上一单信息
        this.payServiceResponse = payServiceResponse

        //记录流水号，退款要用
        setSerialNoByOrderNo(payServiceResponse.shopTradeNo, getSerialNumber())

        val printer = PrinterManager.getInstance().printer
        printer.beginPrint()
        //检查打印机状态
        printer.printerStatus
        printer.set58mm()
        if (BuildConfig.DEBUG) {
            printCashier(printer, payServiceResponse, selfCashierAccountInfo)
        } else {
            printCashier(printer, payServiceResponse, selfCashierAccountInfo)
            printCustomer(printer, payServiceResponse, selfCashierAccountInfo)
        }
        printer.feedPaper()
        printer.endPrint()
    }

    /**
     * 统计，给两个时间，
     */
    fun printStatisticInfo(
        viewOrderStatisticsInfo: ViewOrderStatisticsInfo,
        selfCashierAccountInfo: SelfCashierAccountInfo,
    ) {
        val printer = PrinterManager.getInstance().printer
        printer.beginPrint()
        //检查打印机状态
        printer.printerStatus
        printer.set58mm()
        doPrintStatisticInfo(printer, viewOrderStatisticsInfo, selfCashierAccountInfo)
        printer.feedPaper()
        printer.endPrint()
    }


    private fun doPrintStatisticInfo(
        printer: IPrinter,
        orderStatisticsInfo: ViewOrderStatisticsInfo,
        accountInfo: SelfCashierAccountInfo
    ) {
        printer.beginPrint()
        //[小票内容优化] 去除'欢迎光临'
        printer.printText(accountInfo.shopInfo?.storeName ?: "")
        //统计时间
        printer.printText(0, 0, "开始时间：" + orderStatisticsInfo.beginDate, true)
        printer.printText(0, 0, "结束时间：" + orderStatisticsInfo.endDate, true)

//            //打印分割线-居左
        printer.printText(0, 0, Page58MmPrintUtils.printDivideLineString(), true)
        //            //打印门店号、收银机号、收银员号在一行打印显示
        if (!TextUtils.isEmpty(
                accountInfo.shopInfo?.operatorId
            )
        ) {
            printer.printText(
                Page58MmPrintUtils.printTwoData(
                    "门店号：" + accountInfo.shopInfo?.storeId
                        .toString() + "  收银机号：" + accountInfo.shopInfo?.posId,
                    "收银员号：" + accountInfo.shopInfo?.operatorId
                )
            )
        } else {
            printer.printText(
                Page58MmPrintUtils.printTwoData(
                    "门店号：" + accountInfo.shopInfo?.storeId,
                    "收银机号：" + accountInfo.shopInfo?.posId
                )
            )
        }
        val totalStatistics: ViewOrderStatisticsInfo.StatisticBean? =
            orderStatisticsInfo.totalStatistic
        if (totalStatistics != null) {
            printer.printText(0, 0, Page58MmPrintUtils.printDivideLineString(), true)
            printer.printText(
                Page58MmPrintUtils.printTwoData(
                    "总交易笔数",
                    "" + totalStatistics.tradeCount
                )
            )
            printer.printText(
                Page58MmPrintUtils.printTwoData(
                    "总交易金额",
                    "" + StringPriceFormat.transStringPriceToDecimalString(totalStatistics.tradeTotalAmount.toString())
                )
            )
        }
        val typedStatisticList: List<ViewOrderStatisticsInfo.StatisticBean> =
            orderStatisticsInfo.typeStatistic
        if (!isEmpty(typedStatisticList)) {
            var statisticBean: ViewOrderStatisticsInfo.StatisticBean
            for (i in typedStatisticList.indices) {
                if (typedStatisticList[i] == null) {
                    continue
                }
                statisticBean = typedStatisticList[i]
                printer.printText(0, 0, Page58MmPrintUtils.printDivideLineString(), true)
                printer.printText(
                    Page58MmPrintUtils.printTwoData(
                        "支付方式",
                        statisticBean.payType
                    )
                )
                printer.printText(
                    Page58MmPrintUtils.printTwoData(
                        "交易笔数",
                        "" + statisticBean.tradeCount
                    )
                )
                printer.printText(
                    Page58MmPrintUtils.printTwoData(
                        "交易金额",
                        "" + StringPriceFormat.transStringPriceToDecimalString(statisticBean.tradeTotalAmount.toString())
                    )
                )
            }
        }
    }


    /**
     * 打印收银员联
     */
    private fun printCashier(
        printer: IPrinter,
        payServiceResponse: PayServiceResponse,
        selfCashierAccountInfo: SelfCashierAccountInfo
    ) {

        val shopInfo = selfCashierAccountInfo.shopInfo
        printer.printText(IPrinter.ALIGN_CENTER, 3, shopInfo.storeName, true)
        printer.setAlign(IPrinter.ALIGN_LEFT)
        printer.printText("商户编号：${shopInfo.saasid}")
        printer.printText("终端编号：${shopInfo.posId}")
        printer.printText("商户名称：converse")
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("交易类型：")
        printer.printText(
            IPrinter.ALIGN_LEFT,
            3,
            "    ${MiYaPayPlantformPayWayEnum.MiyaPayType.find(payServiceResponse.chanelTag).desc}",
            true
        )
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("日期/时间：${DateUtils.format18(Date())}")
        printer.printText("流水号：${getSerialNumber()}")
        printer.printText("商户订单号：")
        printer.printText(payServiceResponse.shopTradeNo)
        printer.printText("支付平台交易号：")
        printer.printText(payServiceResponse.chanelSerialNumber)
        printer.printText("金额:")
        printer.printText(
            IPrinter.ALIGN_LEFT,
            3,
            "    RMB${StringPriceFormat.transStringPriceToDecimalString(payServiceResponse.tradPrice)}",
            true
        )
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("备注：")

        val couponDetail: Array<String> = payServiceResponse.transformCouponMessage
        if (couponDetail.size >= 2 && !TextUtils.isEmpty(couponDetail[1]) && couponDetail[1] != "0" && couponDetail[1] != "0.00") {
            val shopCoupon = couponDetail[1]
            //打印商家优惠
            printer.printText("商家优惠：${StringPriceFormat.transStringPriceToDecimalString(shopCoupon)}元")
        }
        if (couponDetail.size >= 3 && !TextUtils.isEmpty(couponDetail[2]) && couponDetail[2] != "0" && couponDetail[2] != "0.00") {
            //平台优惠
            val platformCoupon = couponDetail[2]
            val channel =
                MiYaPayPlantformPayWayEnum.MiyaPayType.find(payServiceResponse.chanelTag).desc
            printer.printText(
                "$channel 优惠：${
                    StringPriceFormat.transStringPriceToDecimalString(
                        platformCoupon
                    )
                }元"
            )
        }
        if (couponDetail.isNotEmpty() && !TextUtils.isEmpty(couponDetail[0])) {
            val payPrice = couponDetail[0]
            printer.printText("客户支付：${StringPriceFormat.transStringPriceToDecimalString(payPrice)}元")
        }

        printer.printText("持卡人签名：")
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("同意以上支付 ")
        printer.printText("\n\n")
    }

    /**
     * 打印顾客联
     */
    private fun printCustomer(
        printer: IPrinter,
        payServiceResponse: PayServiceResponse,
        selfCashierAccountInfo: SelfCashierAccountInfo
    ) {
        val shopInfo = selfCashierAccountInfo.shopInfo
        printer.printText(IPrinter.ALIGN_CENTER, 3, shopInfo.storeName, true)
        printer.setAlign(IPrinter.ALIGN_LEFT)
        printer.printText("持卡人存根")
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("商户编号：${shopInfo.saasid}")
        printer.printText("终端编号：${shopInfo.posId}")
        printer.printText("商户名称：converse")
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("交易类型：")
        printer.printText(
            IPrinter.ALIGN_LEFT,
            3,
            "    ${MiYaPayPlantformPayWayEnum.MiyaPayType.find(payServiceResponse.chanelTag).desc}",
            true
        )
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("日期/时间：${DateUtils.format18(Date())}")
        printer.printText("流水号：${getSerialNumber()}")
        printer.printText("商户订单号：")
        printer.printText(payServiceResponse.shopTradeNo)
        printer.printText("支付平台交易号：")
        printer.printText(payServiceResponse.chanelSerialNumber)
        printer.printText("金额:")
        printer.printText(
            IPrinter.ALIGN_LEFT,
            3,
            "    RMB${StringPriceFormat.transStringPriceToDecimalString(payServiceResponse.tradPrice)}",
            true
        )
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("备注：")

        val couponDetail: Array<String> = payServiceResponse.transformCouponMessage
        if (couponDetail.size >= 2 && !TextUtils.isEmpty(couponDetail[1]) && couponDetail[1] != "0" && couponDetail[1] != "0.00") {
            val shopCoupon = couponDetail[1]
            //打印商家优惠
            printer.printText("商家优惠：${StringPriceFormat.transStringPriceToDecimalString(shopCoupon)}元")
        }
        if (couponDetail.size >= 3 && !TextUtils.isEmpty(couponDetail[2]) && couponDetail[2] != "0" && couponDetail[2] != "0.00") {
            //平台优惠
            val platformCoupon = couponDetail[2]
            val channel =
                MiYaPayPlantformPayWayEnum.MiyaPayType.find(payServiceResponse.chanelTag).desc
            printer.printText(
                "$channel 优惠：${
                    StringPriceFormat.transStringPriceToDecimalString(
                        platformCoupon
                    )
                }元"
            )
        }
        if (couponDetail.isNotEmpty() && !TextUtils.isEmpty(couponDetail[0])) {
            val payPrice = couponDetail[0]
            printer.printText("客户支付：${StringPriceFormat.transStringPriceToDecimalString(payPrice)}元")
        }
        printer.printText("\n\n")
    }


    /**
     * 打印收银员联 - 退款
     */
    private fun refundPrintCashier(
        printer: IPrinter,
        payServiceResponse: PayServiceResponse,
        selfCashierAccountInfo: SelfCashierAccountInfo
    ) {
        val shopInfo = selfCashierAccountInfo.shopInfo
        printer.printText(IPrinter.ALIGN_CENTER, 3, shopInfo.storeName, true)
        printer.setAlign(IPrinter.ALIGN_LEFT)
        printer.printText("商户编号：${shopInfo.saasid}")
        printer.printText("终端编号：${shopInfo.posId}")
        printer.printText("商户名称：converse")
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("交易类型：")
        printer.printText(
            IPrinter.ALIGN_LEFT,
            3,
            "    退款(${MiYaPayPlantformPayWayEnum.MiyaPayType.find(payServiceResponse.chanelTag).desc})",
            true
        )
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("日期/时间：${DateUtils.format18(Date())}")
        printer.printText("流水号：${getSerialNoByOrderNo(payServiceResponse.shopTradeNo)}")
        printer.printText("商户订单号：")
        printer.printText(payServiceResponse.shopTradeNo)
        printer.printText("支付平台交易号：")
        printer.printText(payServiceResponse.chanelSerialNumber)
        printer.printText("金额:")
        printer.printText(
            IPrinter.ALIGN_LEFT,
            3,
            "    RMB${StringPriceFormat.transStringPriceToDecimalString(payServiceResponse.refundPrice)}",
            true
        )
        printer.printText("原订单号：")
        printer.printText(payServiceResponse.shopTradeNo)
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("备注：")

        val couponDetail: Array<String> = payServiceResponse.transformCouponMessage
        if (couponDetail.size >= 2 && !TextUtils.isEmpty(couponDetail[1]) && couponDetail[1] != "0" && couponDetail[1] != "0.00") {
            val shopCoupon = couponDetail[1]
            //打印商家优惠
            printer.printText("商家优惠：${StringPriceFormat.transStringPriceToDecimalString(shopCoupon)}元")
        }
        if (couponDetail.size >= 3 && !TextUtils.isEmpty(couponDetail[2]) && couponDetail[2] != "0" && couponDetail[2] != "0.00") {
            //平台优惠
            val platformCoupon = couponDetail[2]
            val channel =
                MiYaPayPlantformPayWayEnum.MiyaPayType.find(payServiceResponse.chanelTag).desc
            printer.printText(
                "$channel 优惠：${
                    StringPriceFormat.transStringPriceToDecimalString(
                        platformCoupon
                    )
                }元"
            )
        }
        if (couponDetail.isNotEmpty() && !TextUtils.isEmpty(couponDetail[0])) {
            val payPrice = couponDetail[0]
            printer.printText("客户支付：${StringPriceFormat.transStringPriceToDecimalString(payPrice)}元")
        }

        printer.printText("持卡人签名：")
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("同意以上支付 ")
        printer.printText("\n\n")
    }

    /**
     * 打印顾客联-退款
     */
    private fun refundPrintCustomer(
        printer: IPrinter,
        payServiceResponse: PayServiceResponse,
        selfCashierAccountInfo: SelfCashierAccountInfo
    ) {
        val shopInfo = selfCashierAccountInfo.shopInfo
        printer.printText(IPrinter.ALIGN_CENTER, 3, shopInfo.storeName, true)
        printer.setAlign(IPrinter.ALIGN_LEFT)
        printer.printText("持卡人存根")
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("商户编号：${shopInfo.saasid}")
        printer.printText("终端编号：${shopInfo.posId}")
        printer.printText("商户名称：converse")
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("交易类型：")
        printer.printText(
            IPrinter.ALIGN_LEFT,
            3,
            "    退款(${MiYaPayPlantformPayWayEnum.MiyaPayType.find(payServiceResponse.chanelTag).desc})",
            true
        )
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("日期/时间：${DateUtils.format18(Date())}")
        printer.printText("流水号：${getSerialNoByOrderNo(payServiceResponse.shopTradeNo)}")
        printer.printText("商户订单号：")
        printer.printText(payServiceResponse.refundOrderNo)
        printer.printText("支付平台交易号：")
        printer.printText(payServiceResponse.chanelSerialNumber)
        printer.printText("金额:")
        printer.printText(
            IPrinter.ALIGN_LEFT,
            3,
            "    RMB${StringPriceFormat.transStringPriceToDecimalString(payServiceResponse.refundPrice)}",
            true
        )
        printer.printText("原订单号：")
        printer.printText(payServiceResponse.shopTradeNo)
        printer.printText(Page58MmPrintUtils.printDivideLineString())
        printer.printText("备注：")

        val couponDetail: Array<String> = payServiceResponse.transformCouponMessage
        if (couponDetail.size >= 2 && !TextUtils.isEmpty(couponDetail[1]) && couponDetail[1] != "0" && couponDetail[1] != "0.00") {
            val shopCoupon = couponDetail[1]
            //打印商家优惠
            printer.printText("商家优惠：${StringPriceFormat.transStringPriceToDecimalString(shopCoupon)}元")
        }
        if (couponDetail.size >= 3 && !TextUtils.isEmpty(couponDetail[2]) && couponDetail[2] != "0" && couponDetail[2] != "0.00") {
            //平台优惠
            val platformCoupon = couponDetail[2]
            val channel =
                MiYaPayPlantformPayWayEnum.MiyaPayType.find(payServiceResponse.chanelTag).desc
            printer.printText(
                "$channel 优惠：${
                    StringPriceFormat.transStringPriceToDecimalString(
                        platformCoupon
                    )
                }元"
            )
        }
        if (couponDetail.isNotEmpty() && !TextUtils.isEmpty(couponDetail[0])) {
            val payPrice = couponDetail[0]
            printer.printText("客户支付：${StringPriceFormat.transStringPriceToDecimalString(payPrice)}元")
        }
        printer.printText("\n\n")
    }


    private fun getSerialNumber(): String {
        val today = DateUtils.format8(Date())
        val kv = MMKV.defaultMMKV()
        val no = kv.getInt(today, 0).toString()
        var listNo = no
        for (index in 1..(5 - no.length)) {
            listNo = "0$listNo"
        }
        return listNo;
    }


    /**
     * 根据订单号获取流水号
     * //todo  定期删除机制
     */
    private fun getSerialNoByOrderNo(orderNo: String): String {
        return MMKV.defaultMMKV().getString(orderNo, "00000").toString();
    }

    private fun setSerialNoByOrderNo(orderNo: String, serialNo: String) {
        MMKV.defaultMMKV().putString(orderNo, serialNo);
    }

}