package com.module.pay.strategy

import com.module.pay.serialport.DataUtils
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.androidbaseframemvvm.common.constant.PayName
import com.quyunshuo.androidbaseframemvvm.common.constant.event.ApiMessageEvent
import com.quyunshuo.androidbaseframemvvm.common.util.AmountMoney
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import org.greenrobot.eventbus.EventBus
import java.io.OutputStream
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * ict rs232 接受和发送数据 策略实现类
 */
class SerialPortICTRS232Strategy:SerialPortStrategy {
    private var nowAmountMoney: Double? = null
    private var createStrategy: PaySendDataStrategy? = null

    init {
        createStrategy = PaySendDataFactory.createStrategy(StrategyType.ICT)
    }

    override fun readData(data: ByteArray, i: Int, size: Int) {
        val readString: String = DataUtils.ByteArrToHex(data, 0, size)
        disposeData(readString.trim())

    }

    private fun disposeData(asciiData: String) {
        when (asciiData) {
            "808F", "26" -> {
                createStrategy?.squeezeMoney()
                createStrategy?.squeezeMoney()
            }
            "8140", "818F40" -> pressing(0)
            "8141", "818F41" -> pressing(1)
            "8142", "818F42" -> pressing(2)
            "8143", "818F43" -> pressing(3)
            "8144", "818F44" -> pressing(4)
            "8145", "818F45" -> pressing(5)
            "8146", "818F46" -> pressing(6)
            "8147", "818F47" -> pressing(7)
            "8148", "818F48" -> pressing(8)
            "10" -> {
                //收钱成功
                Heartbeat.acceptBill = Heartbeat.acceptBill.add(BigDecimal(nowAmountMoney.toString() + ""))
                    .setScale(2, RoundingMode.HALF_UP)
                //通知前台页面更新
                EventBus.getDefault().post(ApiMessageEvent(PayName.ACCEPT_BILL, Heartbeat.acceptBill))

            }

            "20" -> {}
            "21" -> {}
            "22" -> {}
            "23" -> {}
            "24" -> {}
            "25" -> {}
            "27" -> {}
            "28" -> {}
            else -> {}
        }
    }
    private fun pressing(x: Int) {
        nowAmountMoney = AmountMoney.earth.get(x)
        createStrategy?.squeezeMoney() //收钱
    }

    override fun sendData(data: String, outputStream: OutputStream?) {
        XLogUtil.d("sendData:$data")
        try {
            if (outputStream != null) {
                val sendData: ByteArray = DataUtils.HexToByteArr(data)
                outputStream.write(sendData)
                outputStream.flush()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}