package com.qmai.zqtoolkit.base

import android.annotation.SuppressLint
import android.content.Context
import android_serialport_api.SerialPortFinder
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.qmai.zqtoolkit.ConnectState
import com.qmai.zqtoolkit.LivingWeight
import com.qmai.zqtoolkit.ScaleInfo
import com.qmai.zqtoolkit.base.scale.ScaleBaseKit
import com.qmai.zqtoolkit.config.QmScaleBrand
import tp.xmaihh.serialport.SerialHelper
import tp.xmaihh.serialport.bean.ComBean

/**
 *@desc
 *
 *@auth gaoyingxiang
 *@time 2024/8/21 17:25
 */
object SllchKit : ScaleBaseKit() {
    override val TAG: String
        get() = "SllchKit"
    override val SCALE_TYPE: QmScaleBrand
        get() = QmScaleBrand.SLLCH
    override val STABLE_COUNT: Int
        get() = 6
    override val CONECT_CHECK_COUNT: Int
        get() = 4

    //归 0
    private val cmdZero = byteArrayOf(0x3C, 0x5A, 0x4F, 0x00, 0x00, 0x00, 0x3E)

    //去皮
    val cmd = byteArrayOf(0x3C, 0x54, 0x4B, 0x00, 0x00, 0x00, 0x3E)

    private val serialPortFinder by lazy { SerialPortFinder() }
    private var serialHelper: SerialHelper? = null

    //自己记录皮重
    private var tare = "0.00"

    //最后一次重量
    private var lastWeight = "0.00"

    /**
     * 是否稳定
     */
    fun isStable(comBean: ComBean): Boolean {
        return balanceState(
            String(comBean.bRec, charset("UTF-8"))
        ) == "S"
    }

    /**
     * 状态
     */
    fun balanceState(strGlo: String): String {
        return if (strGlo.isNotEmpty()) {
            try {
                strGlo.substring(2, 3)
            } catch (e: Exception) {
                "S"
            }
        } else {
            "S"
        }
    }

    @SuppressLint("DefaultLocale")
    fun weightKg(comBean: ComBean): String {
        val strGlo = String(comBean.bRec, charset("UTF-8"))
        return if (strGlo.isNotEmpty()) {
            try {
                String.format("%.3f", strGlo.substring(4, 10).toFloat())
            } catch (e: Exception) {
                "0.000"
            }
        } else {
            "0.000"
        }
    }

    override fun connect(cxt: Context?, scale: ScaleInfo) {
        super.connect(cxt, scale)
        if (serialHelper == null) {
            serialHelper = object : SerialHelper("/dev/ttyS9", 9600) {
                override fun onDataReceived(comBean: ComBean) {
                    updateScaleInfo(
                        "${AclasScaleKit.TAG} :onRcvData " + TimeUtils.getNowString() + " data: " + GsonUtils.toJson(
                            comBean
                        )
                    )
                    val it = LivingWeight(
                        isStable = isStable(comBean),
                        weight = weightKg(comBean),
                        unit = "kg",
                        tare = "0",
                        isReadErr = false
                    )
                    updateWeight(it)
                    //LogUtils.e(TAG, GsonUtils.toJson(it))
                }
            }
        }
        serialHelper?.close()
        serialHelper?.open()
        updateState(ConnectState(true, "打开成功"))
    }

    override fun readData() {
//        try {
//            updateState(ConnectState(true, "打开成功"))
//        } catch (e: Exception) {
//            updateState(ConnectState(false, "打开失败"))
//        }
    }

    override fun stopReadData() {
        //serialHelper?.close()
    }

    override fun setZero() {
        serialHelper?.send(cmdZero)
    }

    //去皮
    override fun setNetWeight() {
//        this.tare = lastWeight
        serialHelper?.send(cmd)
    }

    //去皮
    override fun setNetWeightByElec(tare: Double) {
//        this.tare = lastWeight
        serialHelper?.send(cmd)
    }

    //清除去皮
    override fun clearTare() {
//        this.tare = "0.00"
        serialHelper?.send(cmdZero)
    }

    //电子秤获取配置
    override fun getParameter(): Array<String> {
        return serialPortFinder.allDevicesPath
    }
}