package com.qmai.zqtoolkit.base

import android.content.Context
import android.util.Log
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.Utils
import com.example.scaler.AclasScaler
import com.example.scaler.AclasScaler.AclasScalerListener
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 com.qmai.zqtoolkit.utils.ScaleChecker
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * tongzi
 * 2022/5/25
 */
object AclasScaleKit : ScaleBaseKit() {
    override val TAG: String
        get() = "AclasScaleKit"
    override val STABLE_COUNT: Int
        get() = 4
    override val CONECT_CHECK_COUNT: Int
        get() = 0
    override val SCALE_TYPE: QmScaleBrand
        get() = QmScaleBrand.ACLAS
    private var aclasScaler: AclasScaler? = null
    private var reConnectCount = 1
    private var aclasScalerListener = object : AclasScalerListener {
        override fun onDisConnected() {
            updateScaleInfo("$TAG :onDisConnected " + TimeUtils.getNowString())
            updateState(ConnectState(false, "打开失败"))
        }

        override fun onConnected() {
            updateScaleInfo("$TAG :onConnected " + TimeUtils.getNowString())
            updateState(ConnectState(true, "打开成功"))
        }

        override fun onRcvData(weght: AclasScaler.WeightInfoNew?) {
            updateScaleInfo("$TAG :onRcvData " + TimeUtils.getNowString() + " data: " + GsonUtils.toJson(weght))
            //  getTare()
            updateWeight(
                LivingWeight(
                    weght?.isStable ?: false, weght.toString().replace(weght?.unit ?: "", ""),
                    weght?.unit ?: "", weght?.tareWeight?.toString() ?: "", weght?.netWeight == null
                )
            )
        }

        override fun onError(p0: Int, p1: String?) {
            updateScaleInfo("$TAG :onError " + TimeUtils.getNowString() + " data: p0" + p0 + "  p1" + p1)
            if (p0 == -2 && reConnectCount > 0) {
                reConnectCount = 0
                disconnect()
                lastTryScale?.let { connect(Utils.getApp(), it) }
            }
        }

        override fun onUpdateProcess(p0: Int, p1: Int) {
            updateScaleInfo("$TAG :onUpdateProcess " + TimeUtils.getNowString() + " data: p0" + p0 + "  p1" + p1)
            Log.v(TAG, "onUpdateProcess:$p0$p1")
        }

    }


    override fun connect(cxt: Context?, scale: ScaleInfo) {
        updateScaleInfo("$TAG :action connect " + TimeUtils.getNowString())
        super.connect(cxt, scale)
        if (aclasScaler == null) {
            cxt?.let {
                aclasScaler = AclasScaler(AclasScaler.Type_USB, it, aclasScalerListener)
            }
        }
        val usbConnectIndex = getAclasScaleIndex()
        //val usbConnectIndex = 0
        val aclasConnect = aclasScaler?.AclasConnect(usbConnectIndex)
        updateScaleInfo("$TAG :aclasConnect $aclasConnect " + TimeUtils.getNowString())
    }

    override fun disconnect() {
        updateScaleInfo("$TAG :action disconnect " + TimeUtils.getNowString())
        super.disconnect()
        aclasScaler?.AclasDisconnect()
        aclasScaler = null
    }

    override fun readData() {

    }

    override fun stopReadData() {

    }

    override fun setZero() {
        if (isScaleSuccess()) {
            val aclasZero = aclasScaler?.AclasZero()
            Log.v(TAG, "setZero:$aclasZero")
        }
    }

    private fun getTare() {
        if (isScaleSuccess()) {
            val getTare = aclasScaler?.AclasReadTareValue()
            Log.v(TAG, "getTare:$getTare")
        }
    }

    override fun setNetWeight() {
        if (isScaleSuccess()) {
            val aclasTare = aclasScaler?.AclasTare()
            Log.v(TAG, "setNetWeight:$aclasTare")
        }
    }

    override fun setNetWeightByElec(tare: Double) {
        if (isScaleSuccess()) {
            val aclasSetPreTare = aclasScaler?.AclasSetPreTare((tare * 1000.0f).toInt())
            Log.v(TAG, "setNetWeightByElec:$aclasSetPreTare")
        }
    }

    //去除 除皮一个方法
    override fun clearTare() {
        if (isScaleSuccess()) {
            val clearTare = aclasScaler?.AclasTare()
            Log.v(TAG, "clearTare:$clearTare")
        }
    }

    override fun getParameter(): Array<String> {
        var parameter: Array<String> = arrayOf()
        if (isScaleSuccess()) {
            parameter[0] = aclasScaler?.AclasSDKVersion() ?: ""
            parameter[1] = aclasScaler?.AclasReadVersion() ?: ""
            parameter[2] = aclasScaler?.AclasReadId() ?: ""
        }
        return parameter
    }


    override fun isScaleSuccess(): Boolean {
        return super.isScaleSuccess() && aclasScaler?.AclasIsConnect() == true
    }

    private fun getAclasScaleIndex(): Int {
        var usbIndex = 0
        var aclasPname = ScaleChecker.getAclasPname()
        if (aclasPname.isNotEmpty()) {
            var comList = mutableListOf<String>()
            aclasScaler?.getCommList(comList)
            if (!comList.isNullOrEmpty()) {
                usbIndex = comList.indexOfFirst { name -> name.contains(aclasPname) }
                return usbIndex
            }
        }
        return usbIndex
    }
}