package com.narutohuo.xindazhou.ble.impl

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.narutohuo.xindazhou.ble.api.BLEService
import com.narutohuo.xindazhou.ble.callback.*
import com.narutohuo.xindazhou.ble.config.BLEConstants
import com.narutohuo.xindazhou.ble.model.BLEDevice
import com.narutohuo.xindazhou.ble.model.BLECommand
import com.narutohuo.xindazhou.ble.model.BLEResponse
import com.narutohuo.xindazhou.ble.model.BLEEncryptedData
import com.narutohuo.xindazhou.ble.util.BLECrypto
import com.narutohuo.xindazhou.ble.util.BLEPacketBuilder
import com.narutohuo.xindazhou.ble.util.BLEPacketParser
import com.narutohuo.xindazhou.ble.util.BLEPacketSplitter
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger

/**
 * BLE服务实现类（单例模式）
 * 
 * 封装新大洲本田蓝牙协议，提供高级API供业务模块调用
 * 
 * 使用单例模式的原因：
 * 1. BLE连接是全局唯一的（一个设备同时只能有一个连接）
 * 2. 多个界面（Activity/Fragment）需要共享同一个连接状态
 * 3. 避免重复连接、资源浪费
 * 
 * 使用方式：
 * ```kotlin
 * // 在任何界面中获取单例
 * val bleService = BLEServiceImpl.getInstance(context)
 * 
 * // 或者通过依赖注入（推荐）
 * ```
 */
class BLEServiceImpl private constructor(
    private val context: Context
) : BLEService {
    
    companion object {
        @Volatile
        private var INSTANCE: BLEServiceImpl? = null
        
        /**
         * 获取BLE服务单例
         * 
         * @param context 上下文（ApplicationContext或ActivityContext），第一次调用时必需，后续可选
         * @return BLEService单例实例
         */
        @JvmStatic
        fun getInstance(context: Context? = null): BLEServiceImpl {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: run {
                    if (context == null) {
                        throw IllegalStateException("Context is required for first initialization. Call getInstance(context) first.")
                    }
                    BLEServiceImpl(context.applicationContext).also { INSTANCE = it }
                }
            }
        }
        
        /**
         * 销毁单例（用于测试或需要重新初始化时）
         */
        @JvmStatic
        fun destroyInstance() {
            INSTANCE?.disconnect()
            INSTANCE = null
        }
    }
    
    private val tag = "BLEService"
    private var bluetoothAdapter: BluetoothAdapter? = null
    private var bluetoothLeScanner: BluetoothLeScanner? = null
    private var currentDevice: BLEDevice? = null
    private var bluetoothGatt: BluetoothGatt? = null
    private var encryptKey: ByteArray? = null
    private var dataReceivedListener: DataCallback? = null
    
    // 连接状态
    private var connectionState = ConnectionState.DISCONNECTED
    
    // 扫描相关
    private var scanCallback: ScanCallback? = null
    private var scanResultCallback: ((BLEDevice) -> Unit)? = null
    
    // 数据发送相关
    private val pendingCommands = ConcurrentHashMap<Int, PendingCommand>()
    private val commandQueue = mutableListOf<Int>() // 命令队列（FIFO），用于匹配响应
    private val commandToBusinessId = ConcurrentHashMap<Int, Int>() // 命令hash -> businessId
    private val businessIdGenerator = AtomicInteger(0x2605d501) // 业务ID生成器
    private val commandIdCounter = AtomicInteger(0) // 命令ID计数器
    private val handler = Handler(Looper.getMainLooper())
    
    // 分包相关
    private val splitPackets = ConcurrentHashMap<Int, MutableMap<Int, ByteArray>>() // businessId -> (packetIndex -> data)
    
    // 特征值
    private var writeCharacteristic: BluetoothGattCharacteristic? = null
    private var notifyCharacteristic: BluetoothGattCharacteristic? = null
    
    private val packetBuilder = BLEPacketBuilder()
    private val packetParser = BLEPacketParser()
    private val packetSplitter = BLEPacketSplitter()
    
    /**
     * 连接状态枚举
     */
    enum class ConnectionState {
        DISCONNECTED,
        CONNECTING,
        CONNECTED,
        DISCONNECTING
    }
    
    /**
     * 待发送命令
     */
    private data class PendingCommand(
        val command: BLECommand,
        val callback: (BLEResponse) -> Unit,
        val timeoutRunnable: Runnable
    )
    
    init {
        val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
        bluetoothAdapter = bluetoothManager?.adapter
        bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner
    }
    
    // ========== 基础连接功能 ==========
    
    override fun startScan(callback: (BLEDevice) -> Unit) {
        Log.d(tag, "startScan: 开始扫描BLE设备")
        
        if (bluetoothAdapter == null || !bluetoothAdapter!!.isEnabled) {
            Log.e(tag, "startScan: 蓝牙未启用")
            return
        }
        
        if (bluetoothLeScanner == null) {
            Log.e(tag, "startScan: 无法获取BluetoothLeScanner")
            return
        }
        
        scanResultCallback = callback
        
        scanCallback = object : ScanCallback() {
            override fun onScanResult(callbackType: Int, result: ScanResult) {
                val device = result.device
                val deviceName = device.name
                
                // 过滤设备名称（SDH-Smart-***）
                if (deviceName != null && deviceName.startsWith("SDH-Smart-", ignoreCase = true)) {
                    Log.d(tag, "startScan: 发现设备 ${deviceName}, address=${device.address}, rssi=${result.rssi}")
                    
                    val bleDevice = BLEDevice(
                        name = deviceName,
                        address = device.address,
                        rssi = result.rssi,
                        services = emptyList()
                    )
                    
                    scanResultCallback?.invoke(bleDevice)
                }
            }
            
            override fun onBatchScanResults(results: MutableList<ScanResult>) {
                results.forEach { result ->
                    onScanResult(0, result) // 使用0作为callbackType
                }
            }
            
            override fun onScanFailed(errorCode: Int) {
                Log.e(tag, "startScan: 扫描失败, errorCode=$errorCode")
                scanResultCallback = null
            }
        }
        
        // 配置扫描设置
        val scanSettings = ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build()
        
        // 开始扫描
        try {
            bluetoothLeScanner!!.startScan(null, scanSettings, scanCallback)
            Log.d(tag, "startScan: 扫描已启动")
        } catch (e: SecurityException) {
            Log.e(tag, "startScan: 权限不足", e)
        } catch (e: Exception) {
            Log.e(tag, "startScan: 扫描启动失败", e)
        }
    }
    
    override fun stopScan() {
        Log.d(tag, "stopScan: 停止扫描")
        
        scanCallback?.let { callback ->
            try {
                bluetoothLeScanner?.stopScan(callback)
                Log.d(tag, "stopScan: 扫描已停止")
            } catch (e: SecurityException) {
                Log.e(tag, "stopScan: 权限不足", e)
            } catch (e: Exception) {
                Log.e(tag, "stopScan: 停止扫描失败", e)
            }
        }
        
        scanCallback = null
        scanResultCallback = null
    }
    
    override fun connect(device: BLEDevice, callback: (BLEResponse) -> Unit) {
        Log.d(tag, "connect: 连接设备 ${device.address}")
        
        if (connectionState == ConnectionState.CONNECTING || connectionState == ConnectionState.CONNECTED) {
            Log.w(tag, "connect: 已有连接在进行中或已连接")
            callback(BLEResponse(success = false, errorMessage = "已有连接在进行中或已连接"))
            return
        }
        
        currentDevice = device
        connectionState = ConnectionState.CONNECTING
        
        // 生成加密密钥
        val macBytes = parseMacAddress(device.address)
        encryptKey = BLECrypto.generateAESKey(macBytes)
        
        // 获取BluetoothDevice对象
        val bluetoothDevice = try {
            bluetoothAdapter?.getRemoteDevice(device.address)
        } catch (e: IllegalArgumentException) {
            Log.e(tag, "connect: 无效的MAC地址 ${device.address}", e)
            connectionState = ConnectionState.DISCONNECTED
            callback(BLEResponse(success = false, errorMessage = "无效的MAC地址"))
            return
        }
        
        if (bluetoothDevice == null) {
            Log.e(tag, "connect: 无法获取BluetoothDevice")
            connectionState = ConnectionState.DISCONNECTED
            callback(BLEResponse(success = false, errorMessage = "无法获取BluetoothDevice"))
            return
        }
        
        // 连接设备
        try {
            bluetoothGatt = bluetoothDevice.connectGatt(
                context,
                false, // autoConnect = false，使用直接连接
                gattCallback
            )
            
            // 设置连接超时（10秒）
            handler.postDelayed({
                if (connectionState == ConnectionState.CONNECTING) {
                    Log.e(tag, "connect: 连接超时")
                    disconnect()
                    callback(BLEResponse(success = false, errorMessage = "连接超时"))
                }
            }, 10000)
            
        } catch (e: SecurityException) {
            Log.e(tag, "connect: 权限不足", e)
            connectionState = ConnectionState.DISCONNECTED
            callback(BLEResponse(success = false, errorMessage = "权限不足: ${e.message}"))
        } catch (e: Exception) {
            Log.e(tag, "connect: 连接失败", e)
            connectionState = ConnectionState.DISCONNECTED
            callback(BLEResponse(success = false, errorMessage = "连接失败: ${e.message}"))
        }
        
        // 注意：连接成功会在gattCallback中回调
        // 这里需要保存callback，在连接成功后调用
        connectionCallback = callback
    }
    
    // 连接回调（临时保存，连接成功后调用）
    private var connectionCallback: ((BLEResponse) -> Unit)? = null
    
    // Gatt回调
    private val gattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            Log.d(tag, "onConnectionStateChange: status=$status, newState=$newState")
            
            when (newState) {
                BluetoothProfile.STATE_CONNECTED -> {
                    Log.d(tag, "onConnectionStateChange: 已连接")
                    connectionState = ConnectionState.CONNECTED
                    
                    // 发现服务
                    try {
                        val discovered = gatt.discoverServices()
                        if (!discovered) {
                            Log.e(tag, "onConnectionStateChange: 服务发现失败")
                            disconnect()
                            connectionCallback?.invoke(BLEResponse(success = false, errorMessage = "服务发现失败"))
                            connectionCallback = null
                        }
                    } catch (e: SecurityException) {
                        Log.e(tag, "onConnectionStateChange: 权限不足", e)
                        disconnect()
                        connectionCallback?.invoke(BLEResponse(success = false, errorMessage = "权限不足: ${e.message}"))
                        connectionCallback = null
                    }
                }
                
                BluetoothProfile.STATE_DISCONNECTED -> {
                    Log.d(tag, "onConnectionStateChange: 已断开连接")
                    connectionState = ConnectionState.DISCONNECTED
                    bluetoothGatt = null
                    writeCharacteristic = null
                    notifyCharacteristic = null
                }
            }
        }
        
        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
            Log.d(tag, "onServicesDiscovered: status=$status")
            
            if (status != BluetoothGatt.GATT_SUCCESS) {
                Log.e(tag, "onServicesDiscovered: 服务发现失败, status=$status")
                disconnect()
                connectionCallback?.invoke(BLEResponse(success = false, errorMessage = "服务发现失败: status=$status"))
                connectionCallback = null
                return
            }
            
            // 查找服务和特征值
            val service = gatt.getService(BLEConstants.SERVICE_UUID)
            if (service == null) {
                Log.e(tag, "onServicesDiscovered: 未找到服务 ${BLEConstants.SERVICE_UUID}")
                disconnect()
                connectionCallback?.invoke(BLEResponse(success = false, errorMessage = "未找到服务"))
                connectionCallback = null
                return
            }
            
            // 获取Write特征值
            writeCharacteristic = service.getCharacteristic(BLEConstants.WRITE_CHARACTERISTIC_UUID)
            if (writeCharacteristic == null) {
                Log.e(tag, "onServicesDiscovered: 未找到Write特征值")
                disconnect()
                connectionCallback?.invoke(BLEResponse(success = false, errorMessage = "未找到Write特征值"))
                connectionCallback = null
                return
            }
            
            // 获取Notify特征值
            notifyCharacteristic = service.getCharacteristic(BLEConstants.NOTIFY_CHARACTERISTIC_UUID)
            if (notifyCharacteristic == null) {
                Log.e(tag, "onServicesDiscovered: 未找到Notify特征值")
                disconnect()
                connectionCallback?.invoke(BLEResponse(success = false, errorMessage = "未找到Notify特征值"))
                connectionCallback = null
                return
            }
            
            // 启用Notify
            try {
                val enabled = gatt.setCharacteristicNotification(notifyCharacteristic, true)
                if (!enabled) {
                    Log.e(tag, "onServicesDiscovered: 启用Notify失败")
                    disconnect()
                    connectionCallback?.invoke(BLEResponse(success = false, errorMessage = "启用Notify失败"))
                    connectionCallback = null
                    return
                }
                
                // 写入Descriptor以启用通知
                val descriptor = notifyCharacteristic!!.getDescriptor(
                    UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
                )
                descriptor?.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                gatt.writeDescriptor(descriptor)
                
                Log.d(tag, "onServicesDiscovered: 服务发现成功，Notify已启用")
                
                // 连接成功
                connectionCallback?.invoke(BLEResponse(success = true))
                connectionCallback = null
                
            } catch (e: SecurityException) {
                Log.e(tag, "onServicesDiscovered: 权限不足", e)
                disconnect()
                connectionCallback?.invoke(BLEResponse(success = false, errorMessage = "权限不足: ${e.message}"))
                connectionCallback = null
            }
        }
        
        override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
            val data = characteristic.value
            Log.d(tag, "onCharacteristicChanged: 接收到数据 ${data.size} bytes")
            
            // 处理数据接收
            handleDataReceived(data)
        }
        
        override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
            Log.d(tag, "onCharacteristicWrite: status=$status")
            
            if (status != BluetoothGatt.GATT_SUCCESS) {
                Log.e(tag, "onCharacteristicWrite: 写入失败, status=$status")
            }
        }
    }
    
    // 兼容旧接口
    @Deprecated("使用 lambda 回调方式", ReplaceWith("connect(device) { response -> ... }"))
    override fun connect(device: BLEDevice, callback: ConnectCallback) {
        connect(device) { response ->
            if (response.success) {
                callback.onConnected()
            } else {
                callback.onFailed(response.errorMessage ?: "连接失败")
            }
        }
    }
    
    override fun disconnect() {
        Log.d(tag, "disconnect: 断开连接")
        
        connectionState = ConnectionState.DISCONNECTING
        
        // 取消所有待发送的命令
        pendingCommands.values.forEach { pending ->
            handler.removeCallbacks(pending.timeoutRunnable)
        }
        pendingCommands.clear()
        synchronized(commandQueue) {
            commandQueue.clear()
        }
        commandToBusinessId.clear()
        splitPackets.clear()
        
        // 关闭Gatt连接
        try {
            bluetoothGatt?.disconnect()
            bluetoothGatt?.close()
        } catch (e: Exception) {
            Log.e(tag, "disconnect: 断开连接失败", e)
        }
        
        bluetoothGatt = null
        currentDevice = null
        encryptKey = null
        writeCharacteristic = null
        notifyCharacteristic = null
        connectionState = ConnectionState.DISCONNECTED
    }
    
    override fun isConnected(): Boolean {
        return connectionState == ConnectionState.CONNECTED && bluetoothGatt != null
    }
    
    // ========== 协议封装功能（高级API） ==========
    
    override fun handshake(userId: ByteArray, userType: Byte, callback: (BLEResponse) -> Unit) {
        Log.d(tag, "handshake: userId=${userId.size}bytes, userType=$userType")
        
        if (encryptKey == null) {
            callback(BLEResponse(success = false, errorMessage = "未连接设备或密钥未生成"))
            return
        }
        
        // 构建握手指令
        val command = BLECommand(
            functionCode = BLEConstants.FUNCTION_CODE_HANDSHAKE,
            instructionType = userType,
            applicationData = userId // 16字节USERID
        )
        
        // 发送指令
        sendCommand(command, callback)
    }
    
    // 兼容旧接口
    @Deprecated("使用 lambda 回调方式", ReplaceWith("handshake(userId, userType) { response -> ... }"))
    override fun handshake(userId: ByteArray, userType: Byte, callback: HandshakeCallback) {
        handshake(userId, userType) { response ->
            if (response.success) {
                callback.onSuccess()
            } else {
                callback.onFailed(response.errorMessage ?: "握手失败")
            }
        }
    }
    
    override fun sendCommand(command: BLECommand, callback: (BLEResponse) -> Unit) {
        Log.d(tag, "sendCommand: functionCode=${command.functionCode}, instructionType=${command.instructionType}")
        
        if (!isConnected()) {
            callback(BLEResponse(success = false, errorMessage = "未连接设备"))
            return
        }
        
        if (encryptKey == null) {
            callback(BLEResponse(success = false, errorMessage = "未连接设备或密钥未生成"))
            return
        }
        
        if (writeCharacteristic == null) {
            callback(BLEResponse(success = false, errorMessage = "Write特征值未初始化"))
            return
        }
        
        // 构建数据包
        val packet = packetBuilder.buildPacket(command, encryptKey!!)
        
        // 获取MTU（默认23，Android BLE最小MTU）
        // 注意：getMtu() 方法在某些Android版本可能不可用，使用默认值
        val mtu = 23 // Android BLE默认MTU
        
        // 检查是否需要分包（MTU - 3字节ATT头）
        val maxDataSize = mtu - 3
        if (packet.size > maxDataSize) {
            // 需要分包
            Log.d(tag, "sendCommand: 数据包大小 ${packet.size} > MTU $maxDataSize，需要分包")
            sendSplitPacket(packet, maxDataSize, callback)
        } else {
            // 直接发送
            sendSinglePacket(packet, callback)
        }
    }
    
    /**
     * 发送单个数据包
     */
    private fun sendSinglePacket(packet: ByteArray, callback: (BLEResponse) -> Unit) {
        // 使用时间戳和计数器生成唯一ID
        val commandId = (System.currentTimeMillis() xor (commandIdCounter.getAndIncrement().toLong())).toInt()
        
        // 创建超时任务
        val timeoutRunnable = Runnable {
            pendingCommands.remove(commandId)
            commandQueue.remove(commandId)
            callback(BLEResponse(success = false, errorMessage = "指令超时"))
        }
        
        // 保存待发送命令
        pendingCommands[commandId] = PendingCommand(
            command = BLECommand(0, 0, byteArrayOf()), // 占位，实际不需要
            callback = callback,
            timeoutRunnable = timeoutRunnable
        )
        
        // 加入队列
        synchronized(commandQueue) {
            commandQueue.add(commandId)
        }
        
        // 设置超时（2秒）
        handler.postDelayed(timeoutRunnable, BLEConstants.DEFAULT_TIMEOUT_MS)
        
        // 发送数据
        try {
            writeCharacteristic!!.value = packet
            val success = bluetoothGatt!!.writeCharacteristic(writeCharacteristic)
            
            if (!success) {
                handler.removeCallbacks(timeoutRunnable)
                pendingCommands.remove(commandId)
                synchronized(commandQueue) {
                    commandQueue.remove(commandId)
                }
                callback(BLEResponse(success = false, errorMessage = "写入特征值失败"))
            }
        } catch (e: SecurityException) {
            handler.removeCallbacks(timeoutRunnable)
            pendingCommands.remove(commandId)
            synchronized(commandQueue) {
                commandQueue.remove(commandId)
            }
            callback(BLEResponse(success = false, errorMessage = "权限不足: ${e.message}"))
        } catch (e: Exception) {
            handler.removeCallbacks(timeoutRunnable)
            pendingCommands.remove(commandId)
            synchronized(commandQueue) {
                commandQueue.remove(commandId)
            }
            callback(BLEResponse(success = false, errorMessage = "发送失败: ${e.message}"))
        }
    }
    
    /**
     * 发送分包数据
     */
    private fun sendSplitPacket(packet: ByteArray, maxDataSize: Int, callback: (BLEResponse) -> Unit) {
        val businessId = generateBusinessId()
        val packetHash = packet.contentHashCode()
        
        // 保存命令和业务ID的映射
        commandToBusinessId[packetHash] = businessId
        
        val splitPackets = packetSplitter.splitPacket(packet, maxDataSize, businessId)
        
        Log.d(tag, "sendSplitPacket: 分包数量=${splitPackets.size}, businessId=$businessId")
        
        // 创建超时任务
        val timeoutRunnable = Runnable {
            this.splitPackets.remove(businessId)
            pendingCommands.remove(businessId)
            commandToBusinessId.remove(packetHash)
            callback(BLEResponse(success = false, errorMessage = "分包发送超时"))
        }
        
        // 保存待发送命令
        pendingCommands[businessId] = PendingCommand(
            command = BLECommand(0, 0, byteArrayOf()),
            callback = callback,
            timeoutRunnable = timeoutRunnable
        )
        
        // 初始化分包存储
        this.splitPackets[businessId] = mutableMapOf()
        
        // 设置超时（分包需要更长时间）
        handler.postDelayed(timeoutRunnable, BLEConstants.DEFAULT_TIMEOUT_MS * splitPackets.size)
        
        // 依次发送分包
        sendSplitPacketRecursive(splitPackets, 0, businessId)
    }
    
    /**
     * 递归发送分包
     */
    private fun sendSplitPacketRecursive(packets: List<ByteArray>, index: Int, businessId: Int) {
        if (index >= packets.size) {
            // 所有分包已发送，等待响应
            return
        }
        
        val packet = packets[index]
        
        try {
            writeCharacteristic!!.value = packet
            val success = bluetoothGatt!!.writeCharacteristic(writeCharacteristic)
            
            if (success) {
                // 发送下一个分包（延迟50ms，避免发送过快）
                handler.postDelayed({
                    sendSplitPacketRecursive(packets, index + 1, businessId)
                }, 50)
            } else {
                // 发送失败
                val pending = pendingCommands[businessId]
                if (pending != null) {
                    handler.removeCallbacks(pending.timeoutRunnable)
                }
                splitPackets.remove(businessId)
                pendingCommands.remove(businessId)?.callback?.invoke(
                    BLEResponse(success = false, errorMessage = "分包发送失败")
                )
            }
        } catch (e: Exception) {
            val pending = pendingCommands[businessId]
            if (pending != null) {
                handler.removeCallbacks(pending.timeoutRunnable)
            }
            splitPackets.remove(businessId)
            pendingCommands.remove(businessId)?.callback?.invoke(
                BLEResponse(success = false, errorMessage = "分包发送异常: ${e.message}")
            )
        }
    }
    
    /**
     * 处理接收到的数据
     */
    private fun handleDataReceived(data: ByteArray) {
        // 判断是否是分包数据（检查包头和业务ID）
        if (data.isNotEmpty() && data[0] == 0x0A.toByte() && data.size >= 5) {
            // 可能是分包数据
            val businessId = (data[1].toInt() and 0xFF) or
                            ((data[2].toInt() and 0xFF) shl 8) or
                            ((data[3].toInt() and 0xFF) shl 16) or
                            ((data[4].toInt() and 0xFF) shl 24)
            
            // 检查是否是分包协议（业务ID最后一位表示业务类型：0x01=请求，0x02=响应）
            if ((businessId and 0xFF) == 0x02) {
                // 这是分包响应，需要组包
                handleSplitPacketResponse(data, businessId)
                return
            }
        }
        
        // 普通数据包，直接解析
        if (encryptKey == null) {
            Log.e(tag, "handleDataReceived: 加密密钥未初始化")
            return
        }
        
        val encryptedData = packetParser.parsePacket(data, encryptKey!!)
        if (encryptedData == null) {
            Log.e(tag, "handleDataReceived: 数据包解析失败")
            return
        }
        
        // 使用FIFO队列匹配响应（假设响应按顺序返回）
        // 注意：这种方法在并发场景下可能不够精确，但对于大多数场景已经足够
        var found = false
        synchronized(commandQueue) {
            if (commandQueue.isNotEmpty()) {
                val commandId = commandQueue.removeAt(0)
                val pending = pendingCommands.remove(commandId)
                
                if (pending != null) {
                    handler.removeCallbacks(pending.timeoutRunnable)
                    
                    val response = BLEResponse(
                        success = true,
                        data = encryptedData.applicationData
                    )
                    pending.callback(response)
                    found = true
                }
            }
        }
        
        if (!found) {
            // 没有对应的回调，可能是主动推送的数据
            Log.d(tag, "handleDataReceived: 接收到主动推送数据")
            dataReceivedListener?.onDataReceived(encryptedData.applicationData)
        }
    }
    
    /**
     * 处理分包响应
     */
    private fun handleSplitPacketResponse(data: ByteArray, businessId: Int) {
        // 解析分包数据
        if (data.size < 11) {
            Log.e(tag, "handleSplitPacketResponse: 分包数据长度不足")
            return
        }
        
        val totalPackets = (data[5].toInt() and 0xFF) or ((data[6].toInt() and 0xFF) shl 8)
        val packetIndex = (data[7].toInt() and 0xFF) or ((data[8].toInt() and 0xFF) shl 8)
        val dataLength = (data[9].toInt() and 0xFF) or ((data[10].toInt() and 0xFF) shl 8)
        
        // 提取数据（跳过包头、业务ID、总包数、包序号、数据长度，共11字节）
        val packetData = data.sliceArray(11 until 11 + dataLength)
        
        // 保存分包数据
        val packets = splitPackets.getOrPut(businessId) { mutableMapOf() }
        packets[packetIndex] = packetData
        
        // 检查是否所有分包都已接收
        if (packets.size == totalPackets) {
            // 组包
            val combinedData = packetSplitter.combinePackets(packets)
            
            // 解析完整数据包
            if (encryptKey != null) {
                val encryptedData = packetParser.parsePacket(combinedData, encryptKey!!)
                if (encryptedData != null) {
                    // 查找对应的回调
                    val pending = pendingCommands.remove(businessId)
                    if (pending != null) {
                        handler.removeCallbacks(pending.timeoutRunnable)
                        val response = BLEResponse(
                            success = true,
                            data = encryptedData.applicationData
                        )
                        pending.callback(response)
                    }
                }
            }
            
            // 清理
            splitPackets.remove(businessId)
        }
    }
    
    
    /**
     * 生成业务ID
     */
    private fun generateBusinessId(): Int {
        // 业务ID格式：0x2605d501 + 最后一位表示业务类型（0x01=请求）
        val id = businessIdGenerator.getAndIncrement()
        // 确保最后一位是0x01（请求）
        return if ((id and 0xFF) != 0x01) {
            val newId = (id and 0xFFFFFF00.toInt()) or 0x01
            businessIdGenerator.set(newId)
            newId
        } else {
            id
        }
    }
    
    // 兼容旧接口
    @Deprecated("使用 lambda 回调方式", ReplaceWith("sendCommand(command) { response -> ... }"))
    override fun sendCommand(command: BLECommand, callback: CommandCallback) {
        sendCommand(command) { response ->
            if (response.success) {
                callback.onResponse(response)
            } else {
                if (response.errorMessage?.contains("超时") == true || response.errorMessage?.contains("timeout") == true) {
                    callback.onTimeout()
                } else {
                    callback.onError(response.errorMessage ?: "指令失败")
                }
            }
        }
    }
    
    override fun sendAppControlCommand(instructionType: Byte, data: ByteArray, callback: (BLEResponse) -> Unit) {
        val command = BLECommand(
            functionCode = BLEConstants.FUNCTION_CODE_APP_CONTROL,
            instructionType = instructionType,
            applicationData = data
        )
        sendCommand(command, callback)
    }
    
    override fun sendSystemControlCommand(instructionType: Byte, data: ByteArray, callback: (BLEResponse) -> Unit) {
        val command = BLECommand(
            functionCode = BLEConstants.FUNCTION_CODE_SYSTEM_CONTROL,
            instructionType = instructionType,
            applicationData = data
        )
        sendCommand(command, callback)
    }
    
    override fun queryVehicleInfo(callback: (BLEResponse) -> Unit) {
        val command = BLECommand(
            functionCode = BLEConstants.FUNCTION_CODE_SYSTEM_QUERY,
            instructionType = 0x01.toByte(), // 查询车辆信息
            applicationData = byteArrayOf(0x01) // 有效查询
        )
        sendCommand(command, callback)
    }
    
    override fun setDataReceivedListener(listener: DataCallback) {
        this.dataReceivedListener = listener
        Log.d(tag, "setDataReceivedListener: 设置数据接收监听器")
    }
    
    override fun writeRawData(data: ByteArray, callback: (BLEResponse) -> Unit) {
        Log.d(tag, "writeRawData: 发送原始数据 ${data.size} bytes")
        
        if (!isConnected()) {
            callback(BLEResponse(success = false, errorMessage = "未连接设备"))
            return
        }
        
        if (writeCharacteristic == null) {
            callback(BLEResponse(success = false, errorMessage = "Write特征值未初始化"))
            return
        }
        
        try {
            writeCharacteristic!!.value = data
            val success = bluetoothGatt!!.writeCharacteristic(writeCharacteristic)
            
            if (success) {
                // 原始数据发送成功（不等待响应）
                callback(BLEResponse(success = true))
            } else {
                callback(BLEResponse(success = false, errorMessage = "写入特征值失败"))
            }
        } catch (e: SecurityException) {
            callback(BLEResponse(success = false, errorMessage = "权限不足: ${e.message}"))
        } catch (e: Exception) {
            callback(BLEResponse(success = false, errorMessage = "发送失败: ${e.message}"))
        }
    }
    
    // 兼容旧接口
    @Deprecated("使用 lambda 回调方式", ReplaceWith("writeRawData(data) { response -> ... }"))
    override fun writeRawData(data: ByteArray, callback: CommandCallback) {
        writeRawData(data) { response ->
            if (response.success) {
                callback.onResponse(response)
            } else {
                if (response.errorMessage?.contains("超时") == true || response.errorMessage?.contains("timeout") == true) {
                    callback.onTimeout()
                } else {
                    callback.onError(response.errorMessage ?: "发送失败")
                }
            }
        }
    }
    
    // ========== 工具方法 ==========
    
    /**
     * 解析MAC地址为字节数组
     */
    private fun parseMacAddress(macAddress: String): ByteArray {
        val parts = macAddress.split(":")
        return ByteArray(6) { i ->
            parts[i].toInt(16).toByte()
        }
    }
}
