package com.pinwang.ailinkblesdk.modules.smart_cycling_table

import aicare.net.cn.sdk.ailinksdkdemoandroid.modules.smart_cycling_table.SatelliteAllBean
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.L
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.pingwang.bluetoothlib.AILinkBleManager
import com.pingwang.bluetoothlib.bean.BleValueBean
import com.pingwang.bluetoothlib.device.BleDevice
import com.pingwang.bluetoothlib.listener.OnBleOtherDataListener
import com.pingwang.bluetoothlib.listener.OnCallbackBle
import com.pingwang.bluetoothlib.utils.UuidUtils

/**
 * 智能码表视图模型
 * @author xing
 * @date 2025/03/07
 * @constructor 创建[SmartCyclingTableViewModel]
 */
class SmartCyclingTableViewModel : ViewModel(), OnCallbackBle, OnBleOtherDataListener {

    /** ble状态数据
     * true-打开
     * false-关闭
     * */
    val bleStatusData by lazy { MutableLiveData<Boolean>() }

    /** 连接状态数据
     * 1-扫描中
     * 2-连接断开
     * 3-连接成功
     *
     * */
    val connectStatusData by lazy { MutableLiveData<Int>() }

    val mGpsLogLiveData by lazy { MutableLiveData<String>() }
    val mGpsInfoLiveData by lazy { MutableLiveData<MutableMap<String, SatelliteAllBean>>() }


    /** 缓存Map */
    var cacheMap: MutableMap<String, SatelliteAllBean> = mutableMapOf()
    var mRefreshData: Boolean = true
    var mMac: String = ""
    var mBleDevice: BleDevice? = null

    fun init(mac: String, cid: Int, vid: Int, pid: Int) {
        mMac = mac
        AILinkBleManager.getInstance().setOnCallbackBle(this)
        mBleDevice = AILinkBleManager.getInstance().getBleDevice(mac)
        mBleDevice?.let {
            connectStatusData.postValue(3)
            it.setA7Encryption(false)
            it.setOnBleOtherDataListener(this)
        } ?: run {
            connectDevice(mac, cid, vid, pid)
        }
    }


    fun getGpsInfo() {
        mBleDevice?.setNotify(UuidUtils.getUuid("FFE0"), UuidUtils.getUuid("FFE3"))
        refreshDataContinue()
    }

    fun refreshDataPause() {
        mRefreshData = false
        mGpsLogLiveData.value = "暂停刷新"
    }

    fun refreshDataContinue() {
        mRefreshData = true
        mGpsLogLiveData.value = "继续刷新"
    }


    override fun onNotifyOtherData(uuid: String?, data: ByteArray?) {
        super.onNotifyOtherData(uuid, data)
        data?.let {
            if (mRefreshData) {
                parseData(String(data))
            }
        }

    }


    /**
     * 解析数据
     * @param [msg] 味精
     */
    fun parseData(msg: String) {
        if (msg.contains(",")) {
            val split = msg.split(",")
            if (split[0].isEmpty()) {
                return
            }
            val type = split[0].substring(1)
            var message: String
            when (type) {
                "GPGSV" -> {
                    message = "GPS卫星数:"
                }

                "GBGSV" -> {
                    message = "北斗卫星数:"
                }

                "GAGSV" -> {
                    message = "伽利略卫星数:"
                }

                "GLGSV" -> {
                    message = "俄罗斯卫星数:"
                }

                "GIGSV" -> {
                    message = "印度卫星数:"
                }

                "GQGSV" -> {
                    message = "日本卫星数:"
                }

                else -> {
                    return
                }
            }
            L.i("msg:$msg")
            var bean = cacheMap[type]
            if (bean == null) {
                bean = SatelliteAllBean()
            }
            bean.parseStr(split.toTypedArray())
            cacheMap[type] = bean
            if (bean.checkData()) {
                message += "${bean.size}\n"
                val newBean = bean.copy()
                cacheMap.remove(bean.type)
                if (newBean.size > 0) {
                    mGpsLogLiveData.value = message + getSatelliteAllBeanString(newBean)
                }
//                mGpsInfoLiveData.value = mutableMapOf<String, SatelliteAllBean>().also { it.putAll(cacheMap) }
            }
        }
    }


    /**
     * 获取卫星所有豆字符串
     * @param [bean] 豆
     * @return [String]
     */
    private fun getSatelliteAllBeanString(bean: SatelliteAllBean): String {
        var message = ""
        for ((index, satelliteBean) in bean.list.withIndex()) {
            message += "编号:${satelliteBean.id};信号:${satelliteBean.rssi}dB"
            message += if (index % 2 == 1) {
                "\n"
            } else {
                ";  "
            }
        }

        return message
    }


    /**
     * 连接设备
     * @param [mac] mac
     * @param [cid] cid
     * @param [vid] vid
     * @param [pid] pid
     */
    private fun connectDevice(mac: String, cid: Int, vid: Int, pid: Int) {
        AILinkBleManager.getInstance().connectDevice(BleValueBean(mac, cid, vid, pid))
    }

    override fun bleOpen() {
        bleStatusData.postValue(true)
    }

    override fun bleClose() {
        bleStatusData.postValue(false)
    }

    override fun onDisConnected(mac: String?, code: Int) {
        super.onDisConnected(mac, code)
        if (mac == mMac) {
            connectStatusData.postValue(2)
        }
    }

    override fun onServicesDiscovered(mac: String?) {
        super.onServicesDiscovered(mac)
        if (mac == mMac) {
            connectStatusData.postValue(3)
        }
    }

    override fun onStartScan() {
        super.onStartScan()
        connectStatusData.postValue(1)
    }

    override fun onScanning(data: BleValueBean?) {
        super.onScanning(data)
        data?.let {
            if (it.mac == mMac) {
                AILinkBleManager.getInstance().connectDevice(data)
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        mBleDevice?.disconnect()
        AILinkBleManager.getInstance().disconnectAll()
    }
}