package com.abbidot.tracker.util

import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.bean.BleReportDataBean
import com.abbidot.tracker.bean.HistoryDataBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.util.bluetooth.SRBleCmdUtil
import com.abbidot.tracker.vm.SocketSendMessageViewModel
import com.clj.fastble.utils.HexUtil

/**
 *Created  by .yzq on 2025/3/17/017.
 * @link
 * @description:蓝牙上报数据相关处理
 */
class BleReportManage(
    socketSendMessageViewModel: SocketSendMessageViewModel, socketUtilManage: SocketUtilManage
) {

    private var mSocketSendMessageViewModel = socketSendMessageViewModel
    private var mSocketUtilManage = socketUtilManage

    //设备状态上报请求CMD
    private val mTogetherDeviceStateCmdList = mutableListOf<Byte>()

    //5.14 Live定位信息上报
    private val mLiveCmdList = mutableListOf<Byte>()
    private val mSportDataCmdList = mutableListOf<Byte>()
    private val mSleepDataCmdList = mutableListOf<Byte>()

    private var mLatLonUpdateTime = 100L

    /**
     * 处理蓝牙上报的数据
     */
    fun dealBleReportData(mac: String, data: ByteArray?) {
        try {
            data?.let {
                val totalLength = SRBleCmdUtil.instance.byteToInt(data[0])
                val timeStampByteArray = data.sliceArray(2..5)
                mTogetherDeviceStateCmdList.clear()
                mTogetherDeviceStateCmdList.addAll(timeStampByteArray.toMutableList())
                mLiveCmdList.clear()
                mLiveCmdList.addAll(timeStampByteArray.toMutableList())
                mSportDataCmdList.clear()
                mSportDataCmdList.addAll(timeStampByteArray.toMutableList())
                mSleepDataCmdList.clear()
                mSleepDataCmdList.addAll(timeStampByteArray.toMutableList())
                val utcTimeStamp = SRBleCmdUtil.instance.byte4ArrayToLong(timeStampByteArray)
                LogUtil.e("状态更新时间=$utcTimeStamp")
                val bleReportDataBean = BleReportDataBean().apply {
                    updateTime = utcTimeStamp
//                    latLonUpdateTime = utcTimeStamp
                    this.mac = mac
                }
                var length = SRBleCmdUtil.instance.byteToInt(data[6])
                var tempLength = totalLength - length
                //设备状态
                if (SRBleCmdUtil.instance.byteToInt(data[7]) == ConstantInt.Type1) {
                    dealDeviceStateIsLive(data.sliceArray(8..8 + length - 2), bleReportDataBean)
                    //判断后面还有没有其他设备数据
                    if (tempLength > 10) {
                        length = SRBleCmdUtil.instance.byteToInt(data[34])
                        tempLength -= length
                        //定位信息
                        if (SRBleCmdUtil.instance.byteToInt(data[35]) == ConstantInt.Type2) {
                            dealLocationData(
                                data.sliceArray(36..36 + length - 2), bleReportDataBean
                            )
                            //判断后面还有没有其他设备数据
                            if (tempLength > 10) {
                                length = SRBleCmdUtil.instance.byteToInt(data[50])
                                if (SRBleCmdUtil.instance.byteToInt(data[51]) == ConstantInt.Type3) {
                                    //运动睡眠
                                    dealSeepSportData(
                                        data.sliceArray(52..52 + length - 2), bleReportDataBean
                                    )
                                }
                            }
                        } else if (SRBleCmdUtil.instance.byteToInt(data[35]) == ConstantInt.Type3) {
                            //判断是否有定位信息
                            if (!bleReportDataBean.haveLocationData) {
                                val locationData = mutableListOf<Byte>().apply {
                                    //定位方式
                                    add(4)
                                    add(1)
                                    val lon = (LonAndLatUtil.currentUserGPSLon * 1000000).toLong()
                                    val lonByteArray = SRBleCmdUtil.instance.longTo4ByteArray(lon)
                                    addAll(lonByteArray.toMutableList())
                                    val lat = (LonAndLatUtil.currentUserGPSLat * 1000000).toLong()
                                    val latByteArray = SRBleCmdUtil.instance.longTo4ByteArray(lat)
                                    addAll(latByteArray.toMutableList())
                                    addAll(timeStampByteArray.toMutableList())
                                }
                                LogUtil.e("设备没有定位信息，融合手机定位")
                                dealLocationData(locationData.toByteArray(), bleReportDataBean)
                            }
                            //运动睡眠
                            dealSeepSportData(
                                data.sliceArray(36..36 + length - 2), bleReportDataBean
                            )
                        }
                    }

                    XEventBus.post(EventName.BleReportData, bleReportDataBean)
                    //有定位点直播才上报
                    if (bleReportDataBean.liveFlag == ConstantInt.Type1 && mLiveCmdList.size > 30) {
                        mSocketSendMessageViewModel.sendCmd(
                            mSocketUtilManage, mac, 0x0E, mLiveCmdList
                        )
                    }
                    if (mTogetherDeviceStateCmdList.size > 4) {
                        mSocketSendMessageViewModel.sendCmd(
                            mSocketUtilManage, mac, 0x0F, mTogetherDeviceStateCmdList
                        )
                    }
                    if (mSportDataCmdList.size > 4) {
                        mSocketSendMessageViewModel.sendCmd(
                            mSocketUtilManage, mac, 0x0A, mSportDataCmdList
                        )
                    }
                    if (mSleepDataCmdList.size > 4) {
                        mSocketSendMessageViewModel.sendCmd(
                            mSocketUtilManage, mac, 0x0B, mSleepDataCmdList
                        )
                    }
                }
            }
        } catch (e: Exception) {
            LogUtil.e("解析蓝牙上报数据异常：${e.message}")
        }
    }

    /**
     * 处理设备状态数据,返回是否正在直播状态
     */
    private fun dealDeviceStateIsLive(data: ByteArray, bleReportDataBean: BleReportDataBean) {
        val gnssIntervalByteArray = data.sliceArray(4..5)
        val cFencesIdByteArray = data.sliceArray(14..17)
        val wiFiZoneMacByteArray = data.sliceArray(19..24)
        mTogetherDeviceStateCmdList.apply {
            add(data[12])
            add(data[13])
            //数据内容标志
            add(1)
            //是否直播
            add(data[11])
            //red
            add(data[8])
            add(data[9])
            add(data[10])
            //LED灯状态
            add(data[6])
            //LED灯开关状态
            add(data[7])
            //GNSS定位刷新时间
            addAll(gnssIntervalByteArray.toMutableList())
            //当前围栏id
            addAll(cFencesIdByteArray.toMutableList())
            //当前GPS信号强度
            add(data[2])
            //当前电池电量
            add(data[3])
            //设备开关机状态
            add(data[0])
            //当前LTE网络信号
            add(data[1])
            //是否在WiFi zone
            add(data[18])
            //WiFi zone Mac地址
            addAll(wiFiZoneMacByteArray.toMutableList())
        }
        mLiveCmdList.apply {
            //时区
            add(data[25])
            //当前LTE网络信号
            add(data[1])
            //当前GPS信号强度
            add(data[2])
            //当前电池电量
            add(data[3])
            //是否直播
            add(data[11])
        }
        bleReportDataBean.apply {
            haveDeviceStateData = true
            LogUtil.e("设备状态数据=${HexUtil.formatHexString(data, true)}")
            //设备状态
            powerSwitch = SRBleCmdUtil.instance.byteToInt(data[0])
            lteSignal = SRBleCmdUtil.instance.byteToInt(data[1])
            gpsSignal = SRBleCmdUtil.instance.byteToInt(data[2])
            batteryLevel = SRBleCmdUtil.instance.byteToInt(data[3])
            gnssInterval = SRBleCmdUtil.instance.byte2ArrayToInt(gnssIntervalByteArray)
            ledMode = SRBleCmdUtil.instance.byteToInt(data[6])
            ledSwitch = SRBleCmdUtil.instance.byteToInt(data[7])
            ledRedValue = SRBleCmdUtil.instance.byteToInt(data[8])
            ledGreenValue = SRBleCmdUtil.instance.byteToInt(data[9])
            ledBlueValue = SRBleCmdUtil.instance.byteToInt(data[10])
            liveFlag = SRBleCmdUtil.instance.byteToInt(data[11])
            inSafeZone = SRBleCmdUtil.instance.byteToInt(data[12])
            inNoGoZone = SRBleCmdUtil.instance.byteToInt(data[13])
            cFencesId = SRBleCmdUtil.instance.byte4ArrayToLong(cFencesIdByteArray).toString()
            inWifiZone = SRBleCmdUtil.instance.byteToInt(data[18])
            wiFiZoneMac =
                HexUtil.formatHexString(wiFiZoneMacByteArray, true).split(" ", ":").toString()
            timeZone = SRBleCmdUtil.instance.byteToInt(data[25]) - 12
            val msg =
                "设备状态=$powerSwitch,lte=$lteSignal,gps=$gpsSignal,battery=$batteryLevel,gnss=$gnssInterval,ledMode=$ledMode,ledSwitch=$ledSwitch,ledRed=$ledRedValue,ledGreen=$ledGreenValue,ledBlue=$ledBlueValue,liveFlag=$liveFlag,safeZone=$inSafeZone,noGoZone=$inNoGoZone,inWiFiZone=$inWifiZone,wiFiZoneMac=$wiFiZoneMac\n"
            LogUtil.e("解析后：$msg")
        }
    }

    /**
     * 处理定位数据
     */
    private fun dealLocationData(data: ByteArray, bleReportDataBean: BleReportDataBean) {
        LogUtil.e("定位数据=${HexUtil.formatHexString(data, true)}")
        bleReportDataBean.apply {
            //定位方式
            locationMode = SRBleCmdUtil.instance.byteToInt(data[0])
            val locationCount = SRBleCmdUtil.instance.byteToInt(data[1])
            var msg = "定位方式=$locationMode,定位点数=$locationCount,"
            if (locationCount == 0) {
                return@apply
            }
            haveLocationData = true

            mLiveCmdList.apply {
                add(data[0])
                add(data[1])
            }
            val locations = mutableListOf<HistoryDataBean>()
            for (i in 0 until locationCount) {
                val location = HistoryDataBean()
                val lonByteArray = data.sliceArray(2 + i * 12..5 + i * 12)
                val latByteArray = data.sliceArray(6 + i * 12..9 + i * 12)
                val timeStampByteArray = data.sliceArray(10 + i * 12..13 + i * 12)
                location.timeStamp = SRBleCmdUtil.instance.byte4ArrayToLong(timeStampByteArray)
                latLonUpdateTime = location.timeStamp

                if (i == locationCount - 1) {
                    if (mLatLonUpdateTime == latLonUpdateTime) {
                        LogUtil.e("同一个时间戳的经纬度不重复上传,$latLonUpdateTime")
                    } else {
                        mLatLonUpdateTime = latLonUpdateTime
                        mTogetherDeviceStateCmdList[6] = 3
                        mTogetherDeviceStateCmdList.addAll(lonByteArray.toMutableList())
                        mTogetherDeviceStateCmdList.addAll(latByteArray.toMutableList())
                        mTogetherDeviceStateCmdList.add(data[0])
                        mTogetherDeviceStateCmdList.add((timeZone + 12).toByte())
                        //速度
                        mTogetherDeviceStateCmdList.add(0)
                        mTogetherDeviceStateCmdList.add(0)
                    }
                }

                mLiveCmdList.let {
                    it.addAll(timeStampByteArray.toMutableList())
                    it.addAll(lonByteArray.toMutableList())
                    it.addAll(latByteArray.toMutableList())
                    //速度
                    it.add(0)
                    it.add(0)
                    it.add(inSafeZone.toByte())
                    it.add(inNoGoZone.toByte())
                }

                location.longitude =
                    SRBleCmdUtil.instance.byte4ArrayToLong(lonByteArray) / 1000000.0
                location.latitude = SRBleCmdUtil.instance.byte4ArrayToLong(latByteArray) / 1000000.0
                locations.add(location)
                msg += "lon=${location.longitude},lat=${location.latitude},locationTimeStamp=${location.timeStamp},"
            }
            locationList = locations
            LogUtil.e("解析后：$msg")
        }
    }

    /**
     *处理运动睡眠数据
     */
    private fun dealSeepSportData(data: ByteArray, bleReportDataBean: BleReportDataBean) {
        LogUtil.e("运动睡眠数据=${HexUtil.formatHexString(data, true)}")
        val cActiveTimeByteArray = data.sliceArray(13..14)
        val cSleepTimeByteArray = data.sliceArray(15..16)
        mSportDataCmdList.apply {
            addAll(0, data.sliceArray(0..11).toMutableList())
            add((bleReportDataBean.timeZone + 12).toByte())
            add(data[12])
            addAll(cActiveTimeByteArray.toMutableList())
        }
        mSleepDataCmdList.apply {
            addAll(0, cSleepTimeByteArray.toMutableList())
            add(0, data[12])
            addAll(0, data.sliceArray(0..3).toMutableList())
            add((bleReportDataBean.timeZone + 12).toByte())
        }
        bleReportDataBean.apply {
            haveActiveSleepData = true
            year = SRBleCmdUtil.instance.byte2ArrayToInt(data.sliceArray(0..1))
            month = SRBleCmdUtil.instance.byteToInt(data[2])
            day = SRBleCmdUtil.instance.byteToInt(data[3])
            activeTime = SRBleCmdUtil.instance.byte4ArrayToLong(data.sliceArray(4..7))
            steps = SRBleCmdUtil.instance.byte4ArrayToLong(data.sliceArray(8..11))
            //几点的数据
            cTime = SRBleCmdUtil.instance.byteToInt(data[12])
            cActiveTime = SRBleCmdUtil.instance.byte2ArrayToInt(cActiveTimeByteArray)
            cSleepTime = SRBleCmdUtil.instance.byte2ArrayToInt(cSleepTimeByteArray)

            val msg =
                "year=$year,month=$month,day=$day,sportTime=$activeTime,step=$steps,timeZone=$timeZone,whatTime=$cTime,cSportTime=$cActiveTime,cSleepTime=$cSleepTime"
            LogUtil.e("解析后：$msg")
        }
    }
}