package com.example.cmake_project_test

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
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.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat
import java.util.UUID

/**
 * 蓝牙管理器 - 轻迅协议V1.0.1实现
 * 负责蓝牙设备连接、数据接收和状态管理
 */
class BluetoothManager(private val context: Context) {
    
    companion object {
        private const val TAG = "BluetoothManager"
        
        // 轻迅协议相关常量
        object Protocol {
            // 协议版本
            const val VERSION = "1.0.1"
            
            // 数据包格式
            const val PACKET_HEADER_SIZE = 4  // 功能码(2字节) + 数据长度(2字节)
            const val CRC_SIZE = 2            // CRC16校验(2字节)
            const val MIN_PACKET_SIZE = PACKET_HEADER_SIZE + CRC_SIZE
            
            // 功能码定义
            const val FUNC_QUERY_DEVICE_INFO = 0x0000    // 查询设备信息
            const val FUNC_START_COLLECTION = 0x0001     // 采集使能开关（带时间戳）
            const val FUNC_QUERY_BATTERY = 0x0002       // 电量查询
            const val FUNC_STIM_SWITCH = 0x0003         // 电刺激开关
            const val FUNC_POWER_LINE_FILTER = 0x000A  // 工频滤波开关
            const val FUNC_SYNC_TIMESTAMP = 0x0080      // 同步时间戳（64bit毫秒）
            const val FUNC_DATA_STREAM = 0x8000        // 数据上传
            const val FUNC_ALARM_DATA = 0x8001         // 设备状态上报
            const val FUNC_STATUS_REPORT = 0x8002     // 电量上报
            
            // 数据包类型
            const val PACKET_TYPE_COMMAND = 0x00       // 命令包
            const val PACKET_TYPE_RESPONSE = 0x01      // 响应包
            const val PACKET_TYPE_DATA = 0x02          // 数据包
            const val PACKET_TYPE_ALARM = 0x03         // 报警包
            
            // 采集开关
            const val COLLECTION_OFF = 0x00           // 关闭采集
            const val COLLECTION_ON = 0x01            // 开启采集
            
            // 工频滤波
            const val POWER_LINE_FILTER_OFF = 0x00    // 关闭工频滤波
            const val POWER_LINE_FILTER_ON = 0x01     // 开启工频滤波
            
            // 已移除：采样率、增益、导联设置常量（按PDF协议未定义）
            
            // 响应状态码
            const val RESPONSE_SUCCESS = 0x00         // 成功
            const val RESPONSE_FAILED = 0x01          // 失败
            const val RESPONSE_INVALID_PARAM = 0x02   // 参数无效
            const val RESPONSE_NOT_SUPPORTED = 0x03   // 不支持
            const val RESPONSE_BUSY = 0x04            // 设备忙
            const val RESPONSE_TIMEOUT = 0x05         // 超时
        }
        
        // 常见的ECG设备UUID列表（已更新包含ESP32S3 SPP服务）
        private val SERVICE_UUIDS = listOf(
            UUID.fromString("0000abf0-0000-1000-8000-00805f9b34fb"), // // ESP32S3 SPP Service UUID - 0xABF0
            UUID.fromString("6e400001-b5a3-f393-e0a9-68716563686f"), // Nordic UART Service (NUS) - 轻迅设备
            UUID.fromString("1BD790EC-E8B9-7580-0A46-44D30102EDA6"), // 新设备服务UUID
        )
        
        private val CHARACTERISTIC_UUIDS = listOf(
            UUID.fromString("0000abf1-0000-1000-8000-00805f9b34fb"), // ESP32S3 SPP Data Receive - 0xABF1 (TX)
            UUID.fromString("0000abf3-0000-1000-8000-00805f9b34fb"), // ESP32S3 SPP Command Receive - 0xABF3 (TX)
            UUID.fromString("6e400002-b5a3-f393-e0a9-68716563686f"), // Nordic UART TX Characteristic - 轻迅设备发送
            UUID.fromString("1BD790EC-E8B9-7580-0A46-44D30202EDA6"), // 新设备写入特征值
        )
        
        // Notify特征UUID列表（已更新包含ESP32S3 SPP服务）
        private val NOTIFY_CHARACTERISTIC_UUIDS = listOf(
            UUID.fromString("0000abf2-0000-1000-8000-00805f9b34fb"), // ESP32S3 SPP Data Notify - 0xABF2 (RX)
            UUID.fromString("0000abf4-0000-1000-8000-00805f9b34fb"), // ESP32S3 SPP Command Notify - 0xABF4 (RX)
            UUID.fromString("6e400003-b5a3-f393-e0a9-68716563686f"), // Nordic UART RX Characteristic - 轻迅设备接收
            UUID.fromString("1BD790EC-E8B9-7580-0A46-44D30302EDA6"), // 新设备读取特征值
        )
        
        // 设备名称前缀 (根据你的设备调整)
        private const val DEVICE_NAME_PREFIX = "ESP_SPP_SERVER"
        
        // 设备类型枚举
        enum class DeviceType {
            ESP32S3_DEVICE, // ESP32S3 SPP设备
            QINGXUN,        // 轻迅设备
            NEW_DEVICE      // 新设备
        }
    }
    
    private var bluetoothManagerService: android.bluetooth.BluetoothManager? = null
    private var bluetoothAdapter: BluetoothAdapter? = null
    private var bluetoothGatt: BluetoothGatt? = null
    private var bluetoothLeScanner: BluetoothLeScanner? = null
    
    // 连接状态
    private var isConnected = false
    private var isConnecting = false
    private var isClassicScanReceiverRegistered = false
    
    // Handler和延迟任务
    private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
    private var bleScanStopRunnable: Runnable? = null
    
    // 清理状态标志
    private var isCleaningUp = false
    
    // 设备列表
    private val discoveredDevices = mutableListOf<BluetoothDevice>()
    
    // 当前连接的服务和特征
    private var currentService: BluetoothGattService? = null
    private var currentCharacteristic: BluetoothGattCharacteristic? = null
    private var currentNotifyCharacteristic: BluetoothGattCharacteristic? = null
    
    // 当前设备类型
    private var currentDeviceType: DeviceType? = null
    
    // 协议状态
    private var deviceInfo: DeviceInfo? = null
    private var isCollecting = false
    // 已移除：采样率、增益、导联状态变量（按PDF协议未定义）
    private var powerLineFilterEnabled = false
    
    // 数据统计
    private var totalPacketsReceived = 0L
    private var totalBytesReceived = 0L
    private var totalPacketsSent = 0L
    private var totalBytesSent = 0L
    
    // 回调接口
    interface BluetoothCallback {
        fun onDeviceFound(device: BluetoothDevice)
        fun onConnected(device: BluetoothDevice)
        fun onDisconnected()
        fun onDataReceived(data: ByteArray)
        fun onError(message: String)
        fun onStatusChanged(status: String)
        fun onScanComplete(devices: List<BluetoothDevice>)
        fun onCommandSent(success: Boolean, message: String)
        fun onProtocolDataReceived(functionCode: Int, data: ByteArray)
        fun onDeviceInfoReceived(deviceInfo: DeviceInfo)
        fun onBatteryLevelReceived(level: Int)
        fun onCollectionStatusChanged(isCollecting: Boolean)
    }
    
    // 设备信息数据类
    data class DeviceInfo(
        val deviceId: String,
        val firmwareVersion: String,
        val hardwareVersion: String,
        val serialNumber: String,
        val manufacturer: String,
        val model: String,
        val capabilities: List<String>
    )
    
    private var callback: BluetoothCallback? = null
    
    init {
        initializeBluetooth()
    }
    
    /**
     * 初始化蓝牙
     */
    private fun initializeBluetooth() {
        try {
            bluetoothManagerService = context.getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager
            bluetoothAdapter = bluetoothManagerService?.adapter
            
            if (bluetoothAdapter == null) {
                Log.e(TAG, "设备不支持蓝牙")
                callback?.onError("设备不支持蓝牙")
                return
            }
            
            if (!bluetoothAdapter!!.isEnabled) {
                Log.w(TAG, "蓝牙未启用")
                callback?.onStatusChanged("蓝牙未启用，请先启用蓝牙")
                return
            }
            
            // 初始化BLE扫描器
            bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner
            
            if (bluetoothLeScanner == null) {
                Log.w(TAG, "设备不支持BLE")
                callback?.onStatusChanged("设备不支持BLE，将使用传统蓝牙扫描")
            }
            
            Log.d(TAG, "蓝牙初始化成功")
            callback?.onStatusChanged("蓝牙已就绪")
            
        } catch (e: Exception) {
            Log.e(TAG, "蓝牙初始化失败: ${e.message}")
            callback?.onError("蓝牙初始化失败: ${e.message}")
        }
    }
    
    /**
     * 设置回调
     */
    fun setCallback(callback: BluetoothCallback) {
        this.callback = callback
    }
    
    /**
     * 获取当前设备类型
     */
    fun getCurrentDeviceType(): DeviceType? {
        return currentDeviceType
    }
    
    /**
     * 扫描蓝牙设备
     */
    fun startScan() {
        if (bluetoothAdapter == null) {
            callback?.onError("❌ 蓝牙未初始化")
            callback?.onStatusChanged("💡 请检查设备是否支持蓝牙")
            return
        }
        
        if (!bluetoothAdapter!!.isEnabled) {
            callback?.onError("❌ 蓝牙未启用")
            callback?.onStatusChanged("💡 请在系统设置中开启蓝牙")
            return
        }
        
        try {
            // 清空之前的设备列表
            discoveredDevices.clear()
            callback?.onStatusChanged("🔍 开始扫描蓝牙设备...")
            callback?.onStatusChanged("⏱️ 扫描时间: 15秒")
            callback?.onStatusChanged("💡 请确保目标设备:")
            callback?.onStatusChanged("   • 蓝牙已开启")
            callback?.onStatusChanged("   • 设置为可发现模式")
            callback?.onStatusChanged("   • 在10米范围内")
            callback?.onStatusChanged("   • 未与其他设备连接")
            
            // 检查所有必要权限
            val missingPermissions = mutableListOf<String>()
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("BLUETOOTH_SCAN")
            }
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("BLUETOOTH_CONNECT")
            }
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("ACCESS_FINE_LOCATION")
            }
            
            if (missingPermissions.isNotEmpty()) {
                callback?.onError("❌ 缺少权限: ${missingPermissions.joinToString(", ")}")
                callback?.onStatusChanged("💡 请在应用设置中授予蓝牙和位置权限")
                return
            }
            
            callback?.onStatusChanged("✅ 权限检查通过，开始扫描...")
            
            // 改进的兼容性扫描策略
            when {
                // Android 8/8.1: 使用混合扫描模式以获得最佳兼容性
                android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O || 
                android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1 -> {
                    Log.d(TAG, "📱 Android 8/8.1检测：使用混合扫描模式（BLE + 传统蓝牙）")
                    callback?.onStatusChanged("📱 Android 8系统优化：混合扫描模式")
                    callback?.onStatusChanged("🔍 策略：BLE扫描 + 传统蓝牙扫描")
                    startEnhancedScanning()
                }
                // Android 6-11: 优先BLE，失败时回退到传统蓝牙
                android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M &&
                android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S -> {
                    if (bluetoothLeScanner != null) {
                        Log.d(TAG, "📱 Android ${android.os.Build.VERSION.RELEASE}：优先BLE扫描")
                        callback?.onStatusChanged("📡 使用BLE扫描模式")
                        callback?.onStatusChanged("🔍 开始BLE扫描...")
                        startBleScan()
                    } else {
                        Log.w(TAG, "⚠️ BLE不可用，使用传统蓝牙扫描")
                        callback?.onStatusChanged("📡 BLE不可用，使用传统蓝牙扫描")
                        callback?.onStatusChanged("🔍 开始传统蓝牙扫描...")
                        startClassicScan()
                    }
                }
                // Android 12+: 完整的BLE扫描支持
                else -> {
                    if (bluetoothLeScanner != null) {
                        Log.d(TAG, "✅ Android ${android.os.Build.VERSION.RELEASE}：完整的BLE支持")
                        callback?.onStatusChanged("📡 完整BLE扫描模式")
                        callback?.onStatusChanged("🔍 开始BLE扫描...")
                        startBleScan()
                    } else {
                        Log.w(TAG, "⚠️ 意外情况：BLE不可用，使用传统蓝牙")
                        callback?.onStatusChanged("📡 BLE不可用，使用传统蓝牙扫描")
                        callback?.onStatusChanged("🔍 开始传统蓝牙扫描...")
                        startClassicScan()
                    }
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "扫描失败: ${e.message}")
            callback?.onError("❌ 扫描失败: ${e.message}")
            callback?.onStatusChanged("💡 请尝试重启蓝牙或重启设备")
        }
    }
    
    /**
     * 开始BLE扫描
     */
    private fun startBleScan() {
        try {
            val scanSettings = ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .setReportDelay(0) // 立即报告结果
                .build()
            
            // 不使用过滤器，扫描所有BLE设备，确保不会遗漏新设备
            Log.d(TAG, "🚀 开始BLE扫描，无过滤器")
            bluetoothLeScanner?.startScan(null, scanSettings, bleScanCallback)
            Log.d(TAG, "✅ BLE扫描已启动成功")
            
            callback?.onStatusChanged("📡 BLE扫描已启动")
            callback?.onStatusChanged("🔍 扫描模式：所有BLE设备")
            callback?.onStatusChanged("⏱️ 扫描时长：15秒")
            callback?.onStatusChanged("💡 发现设备实时显示")
            callback?.onStatusChanged("🎯 目标服务UUID:")
            for (serviceUuid in SERVICE_UUIDS) {
                callback?.onStatusChanged("   • $serviceUuid")
            }
            
            // 取消之前的延迟任务（如果存在）
            bleScanStopRunnable?.let { mainHandler.removeCallbacks(it) }
            
            // 15秒后停止扫描
            bleScanStopRunnable = Runnable {
                try {
                    // 检查是否正在清理
                    if (isCleaningUp) {
                        Log.d(TAG, "正在清理中，跳过延迟BLE扫描停止")
                        return@Runnable
                    }
                    stopBleScan()
                } catch (e: Exception) {
                    Log.e(TAG, "延迟停止BLE扫描失败: ${e.message}")
                    // 如果是FragmentManager相关错误，记录但不抛出异常
                    if (e.message?.contains("FragmentManager") == true) {
                        Log.w(TAG, "FragmentManager已销毁，延迟BLE扫描停止操作被忽略")
                    }
                }
            }
            mainHandler.postDelayed(bleScanStopRunnable!!, 15000)
            
        } catch (e: Exception) {
            Log.e(TAG, "BLE扫描失败: ${e.message}")
            callback?.onError("❌ BLE扫描失败: ${e.message}")
            callback?.onStatusChanged("💡 尝试使用传统蓝牙扫描...")
            
            // 延迟1秒后启动传统蓝牙扫描，避免同时启动太多扫描
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                try {
                    startClassicScan()
                } catch (fallbackE: Exception) {
                    callback?.onError("❌ 传统蓝牙扫描也失败: ${fallbackE.message}")
                }
            }, 1000)
        }
    }
    
    /**
     * 开始传统蓝牙扫描
     */
    private fun startClassicScan() {
        try {
            Log.d(TAG, "🚀 开始传统蓝牙扫描")
            callback?.onStatusChanged("📡 开始传统蓝牙扫描...")
            
            // Android 8.1特殊状态检查
            if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1) {
                Log.d(TAG, "📱 Android 8.1状态检查:")
                callback?.onStatusChanged("📱 Android 8.1系统检测...")
                
                // 检查蓝牙适配器状态
                val adapterState = bluetoothAdapter?.state ?: BluetoothAdapter.STATE_OFF
                Log.d(TAG, "📱 蓝牙适配器状态: ${adapterState}")
                callback?.onStatusChanged("📱 蓝牙适配器状态: ${when(adapterState) {
                    BluetoothAdapter.STATE_ON -> "已开启"
                    BluetoothAdapter.STATE_OFF -> "已关闭"
                    BluetoothAdapter.STATE_TURNING_ON -> "正在开启"
                    BluetoothAdapter.STATE_TURNING_OFF -> "正在关闭"
                    else -> "未知($adapterState)"
                }}")
                
                // 检查是否正在探索
                val isDiscovering = bluetoothAdapter?.isDiscovering ?: false
                Log.d(TAG, "📱 当前探索状态: $isDiscovering")
                callback?.onStatusChanged("📱 当前探索状态: ${if(isDiscovering) "正在探索" else "未在探索"}")
                
                if (isDiscovering) {
                    Log.d(TAG, "📱 停止当前探索并重新开始")
                    bluetoothAdapter?.cancelDiscovery()
                    Thread.sleep(500) // 等待500ms
                }
            }
            
            registerClassicScanReceiver()
            val discoveryStarted = bluetoothAdapter?.startDiscovery() ?: false
            
            if (discoveryStarted) {
                Log.d(TAG, "✅ 传统蓝牙扫描启动成功")
                callback?.onStatusChanged("✅ 传统蓝牙扫描已启动")
                callback?.onStatusChanged("🔍 扫描时长：25秒")
                callback?.onStatusChanged("💡 请确保目标设备设置为可发现模式")
                callback?.onStatusChanged("🎯 搜索经典蓝牙和音频设备")
                
                // Android 8.1额外提示
                if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1) {
                    callback?.onStatusChanged("📱 Android 8.1提示：扫描传统蓝牙设备")
                    callback?.onStatusChanged("💡 如果找不到设备，请检查设备的配对模式")
                }
            } else {
                Log.w(TAG, "⚠️ 传统蓝牙扫描启动失败")
                callback?.onStatusChanged("❌ 传统蓝牙扫描启动失败")
                
                if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1) {
                    callback?.onStatusChanged("💡 Android 8.1排除步骤：")
                    callback?.onStatusChanged("   • 检查蓝牙是否已开启")
                    callback?.onStatusChanged("   • 尝试重启蓝牙")
                    callback?.onStatusChanged("   • 检查是否有其他应用在扫描")
                }
            }
            
            // 25秒后停止扫描（增强扫描模式使用更长的时间）
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                Log.d(TAG, "⏰ 传统蓝牙扫描超时，自动停止")
                stopClassicScan()
            }, 25000)
            
        } catch (e: Exception) {
            Log.e(TAG, "传统蓝牙扫描异常: ${e.message}", e)
            callback?.onError("❌ 传统蓝牙扫描失败: ${e.message}")
            callback?.onStatusChanged("💡 建议：")
            callback?.onStatusChanged("   • 检查蓝牙是否开启")
            callback?.onStatusChanged("   • 尝试重启蓝牙服务")
            callback?.onStatusChanged("   • 重启设备")
        }
    }
    
    /**
     * 增强扫描模式：同时使用BLE和传统蓝牙扫描（适用于Android 8）
     */
    private fun startEnhancedScanning() {
        try {
            Log.d(TAG, "🚀 开始增强扫描模式")
            callback?.onStatusChanged("🚀 启动混合扫描模式...")
            callback?.onStatusChanged("💡 同时使用BLE和传统音频蓝牙扫描")
            
            // 并行启动两种扫描
            var startedCount = 0
            val errors = mutableListOf<String>()
            
            // 启动BLE扫描
            try {
                bluetoothLeScanner?.let {
                    Log.d(TAG, "📡 启动BLE扫描...")
                    callback?.onStatusChanged("📡 启动BLE扫描...")
                    startedCount++
                    startBleScan()
                } ?: run {
                    errors.add("BLE扫描器不可用")
                }
            } catch (e: Exception) {
                errors.add("BLE扫描启动失败: ${e.message}")
                Log.w(TAG, "BLE扫描启动失败，继续使用传统蓝牙: ${e.message}")
            }
            
            // 启动传统蓝牙扫描
            try {
                Log.d(TAG, "🔗 启动传统蓝牙扫描...")
                callback?.onStatusChanged("🔗 启动传统蓝牙扫描...")
                startedCount++
                startClassicScan()
            } catch (e: Exception) {
                errors.add("传统蓝牙扫描启动失败: ${e.message}")
                Log.w(TAG, "传统蓝牙扫描启动失败: ${e.message}")
            }
            
            // 报告结果
            if (startedCount > 0) {
                Log.d(TAG, "✅ 增强扫描模式启动成功：$startedCount 个扫描器")
                callback?.onStatusChanged("✅ 混合扫描启动成功")
                callback?.onStatusChanged("📊 活跃扫描器：$startedCount 个")
                callback?.onStatusChanged("⏱️ 扫描时长：25秒")
                callback?.onStatusChanged("💡 正在搜索所有类型的蓝牙设备...")
                
                if (errors.isNotEmpty()) {
                    callback?.onStatusChanged("⚠️ 部分扫描器启动失败:")
                    errors.forEach { error ->
                        callback?.onStatusChanged("   • $error")
                    }
                }
            } else {
                callback?.onStatusChanged("❌ 增强扫描模式启动失败")
                errors.forEach { error ->
                    callback?.onStatusChanged("   • $error")
                }
                throw Exception("所有扫描器启动失败")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "增强扫描模式失败: ${e.message}", e)
            callback?.onError("❌ 混合扫描失败: ${e.message}")
            callback?.onStatusChanged("💡 尝试单独启动扫描...")
            
            // 回退到传统蓝牙扫描
            try {
                startClassicScan()
                callback?.onStatusChanged("✅ 已回退到传统蓝牙扫描")
            } catch (fallbackE: Exception) {
                callback?.onError("❌ 回退扫描也失败了: ${fallbackE.message}")
            }
        }
    }

    /**
     * 停止扫描
     */
    fun stopScan() {
        try {
            Log.d(TAG, "🛑 开始停止所有扫描")
            stopBleScan()
            stopClassicScan()
            callback?.onStatusChanged("扫描已停止")
            Log.d(TAG, "✅ 所有扫描已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止扫描失败: ${e.message}")
        }
    }
    
    /**
     * 停止BLE扫描
     */
    private fun stopBleScan() {
        // 如果正在清理，直接返回
        if (isCleaningUp) {
            Log.d(TAG, "正在清理中，跳过BLE扫描停止")
            return
        }
        
        try {
            // 取消延迟任务
            bleScanStopRunnable?.let { 
                mainHandler.removeCallbacks(it)
                bleScanStopRunnable = null
            }
            
            bluetoothLeScanner?.stopScan(bleScanCallback)
            Log.d(TAG, "BLE扫描已停止")
            
            // 扫描完成后触发回调（仅在非混合模式）
            val isMixedScan = android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O || 
                             android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1
            
            callback?.onStatusChanged("🔍 BLE扫描完成")
            val bleDeviceCount = discoveredDevices.count { it.type == BluetoothDevice.DEVICE_TYPE_LE }
            callback?.onStatusChanged("📊 BLE扫描结果：找到 $bleDeviceCount 个BLE设备")
            
            if (bleDeviceCount == 0) {
                callback?.onStatusChanged("⚠️ 未发现BLE设备")
                if (!isMixedScan) {
                    callback?.onStatusChanged("💡 建议：")
                    callback?.onStatusChanged("   • 检查目标设备是否开启蓝牙")
                    callback?.onStatusChanged("   • 确保设备在可见范围内")
                    callback?.onStatusChanged("   • 尝试重启蓝牙服务")
                }
            } else {
                callback?.onStatusChanged("✅ BLE扫描成功")
            }
            
            // 仅在非混合模式下触发完成回调
            if (!isMixedScan) {
                callback?.onScanComplete(discoveredDevices.toList())
            } else {
                callback?.onStatusChanged("⏳ BLE扫描完成，传统蓝牙扫描继续进行...")
            }
        } catch (e: Exception) {
            Log.e(TAG, "停止BLE扫描失败: ${e.message}")
            // 如果是FragmentManager相关错误，记录但不抛出异常
            if (e.message?.contains("FragmentManager") == true) {
                Log.w(TAG, "FragmentManager已销毁，BLE扫描停止操作被忽略")
            }
        }
    }
    
    /**
     * 停止传统蓝牙扫描
     */
    private fun stopClassicScan() {
        try {
            bluetoothAdapter?.cancelDiscovery()
            unregisterClassicScanReceiver()
            Log.d(TAG, "传统蓝牙扫描已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止传统蓝牙扫描失败: ${e.message}")
        }
    }
    
    /**
     * 连接设备
     */
    fun connectToDevice(device: BluetoothDevice) {
        if (isConnecting || isConnected) {
            callback?.onError("正在连接或已连接")
            return
        }
        
        try {
            isConnecting = true
            callback?.onStatusChanged("正在连接设备: ${device.name}")
            
            // 检查权限
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                callback?.onError("缺少蓝牙连接权限")
                isConnecting = false
                return
            }
            
            // 连接设备
            bluetoothGatt = device.connectGatt(context, false, gattCallback)
            
        } catch (e: Exception) {
            Log.e(TAG, "连接失败: ${e.message}")
            callback?.onError("连接失败: ${e.message}")
            isConnecting = false
        }
    }
    
    /**
     * 断开连接
     */
    fun disconnect() {
        try {
            bluetoothGatt?.disconnect()
            bluetoothGatt?.close()
            bluetoothGatt = null
            currentService = null
            currentCharacteristic = null
            isConnected = false
            isConnecting = false
            callback?.onStatusChanged("已断开连接")
        } catch (e: Exception) {
            Log.e(TAG, "断开连接失败: ${e.message}")
        }
    }
    
    /**
     * 发送指令到设备
     */
    fun sendCommand(command: ByteArray) {
        if (!isConnected) {
            callback?.onCommandSent(false, "设备未连接")
            return
        }
        
        if (currentCharacteristic == null) {
            callback?.onCommandSent(false, "特征未找到，无法发送指令")
            return
        }
        
        try {
            // 检查权限
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                callback?.onCommandSent(false, "缺少蓝牙连接权限")
                return
            }
            
            // 设置特征值
            currentCharacteristic!!.value = command
            
            // 发送数据
            val success = bluetoothGatt?.writeCharacteristic(currentCharacteristic!!) ?: false
            
            if (success) {
                totalPacketsSent++
                totalBytesSent += command.size
                Log.d(TAG, "指令发送成功: ${command.joinToString(", ") { "0x%02X".format(it) }}")
                callback?.onCommandSent(true, "指令发送成功")
                callback?.onStatusChanged("已发送指令: ${command.joinToString(", ") { "0x%02X".format(it) }}")
            } else {
                Log.e(TAG, "指令发送失败")
                callback?.onCommandSent(false, "指令发送失败")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "发送指令异常: ${e.message}")
            callback?.onCommandSent(false, "发送指令异常: ${e.message}")
        }
    }
    
    /**
     * 构建轻迅协议数据包
     * 格式: [功能码(2字节)] [数据长度(2字节)] [数据内容] [CRC16(2字节)]
     */
    private fun buildProtocolPacket(functionCode: Int, data: ByteArray = ByteArray(0)): ByteArray {
        val dataLength = data.size
        val packetSize = Protocol.PACKET_HEADER_SIZE + dataLength + Protocol.CRC_SIZE
        val packet = ByteArray(packetSize)
        
        var index = 0
        
        // 功能码 (小端格式)
        packet[index++] = (functionCode and 0xFF).toByte()
        packet[index++] = ((functionCode shr 8) and 0xFF).toByte()
        
        // 数据长度 (小端格式)
        packet[index++] = (dataLength and 0xFF).toByte()
        packet[index++] = ((dataLength shr 8) and 0xFF).toByte()
        
        // 数据内容
        if (data.isNotEmpty()) {
            System.arraycopy(data, 0, packet, index, dataLength)
            index += dataLength
        }
        
        // CRC16校验
        val crc = calculateCRC16(packet, 0, Protocol.PACKET_HEADER_SIZE + dataLength)
        packet[index++] = (crc and 0xFF).toByte()
        packet[index++] = ((crc shr 8) and 0xFF).toByte()
        
        return packet
    }
    
    
    
    /**
     * 处理原始数据（非标准协议格式）
     */
    private fun handleRawData(data: ByteArray) {
        try {
            Log.d(TAG, "处理原始数据: ${data.size} 字节")
            
            // 检查是否是数据流（功能码0x8000）
            if (data.size >= 2) {
                val functionCode = (data[1].toInt() and 0xFF shl 8) or (data[0].toInt() and 0xFF)
                
                if (functionCode == Protocol.FUNC_DATA_STREAM) {
                    Log.d(TAG, "检测到数据流功能码: 0x${functionCode.toString(16).uppercase()}")
                    
                    // 提取数据内容（跳过功能码）
                    val dataContent = if (data.size > 2) {
                        ByteArray(data.size - 2)
                    } else {
                        ByteArray(0)
                    }
                    
                    if (dataContent.isNotEmpty()) {
                        System.arraycopy(data, 2, dataContent, 0, dataContent.size)
                    }
                    
                    // 处理数据流
                    handleDataStream(dataContent)
                    return
                }
            }
            
            // 如果不是已知格式，直接传递给回调
            Log.d(TAG, "未知数据格式，直接传递给回调")
            callback?.onDataReceived(data)
            callback?.onProtocolDataReceived(0xFFFF, data) // 使用特殊功能码表示原始数据
            
        } catch (e: Exception) {
            Log.e(TAG, "处理原始数据异常: ${e.message}")
            // 异常情况下仍然传递给回调
            callback?.onDataReceived(data)
        }
    }
    
    /**
     * 处理设备信息响应
     */
    private fun handleDeviceInfoResponse(data: ByteArray) {
        try {
            if (data.size < 20) {
                Log.e(TAG, "设备信息数据长度不足: ${data.size}")
                return
            }
            
            var index = 0
            
            // 设备ID (8字节)
            val deviceId = String(data, index, 8).trim { it <= ' ' }
            index += 8
            
            // 固件版本 (4字节)
            val firmwareVersion = String(data, index, 4).trim { it <= ' ' }
            index += 4
            
            // 硬件版本 (4字节)
            val hardwareVersion = String(data, index, 4).trim { it <= ' ' }
            index += 4
            
            // 序列号 (4字节)
            val serialNumber = String(data, index, 4).trim { it <= ' ' }
            index += 4
            
            // 制造商和型号 (剩余字节)
            val remainingData = String(data, index, data.size - index).trim { it <= ' ' }
            val parts = remainingData.split("|")
            val manufacturer = if (parts.isNotEmpty()) parts[0] else ""
            val model = if (parts.size > 1) parts[1] else ""
            
            deviceInfo = DeviceInfo(
                deviceId = deviceId,
                firmwareVersion = firmwareVersion,
                hardwareVersion = hardwareVersion,
                serialNumber = serialNumber,
                manufacturer = manufacturer,
                model = model,
                capabilities = listOf("ECG", "BLE", "轻迅协议V${Protocol.VERSION}")
            )
            
            Log.d(TAG, "设备信息: $deviceInfo")
            callback?.onDeviceInfoReceived(deviceInfo!!)
            callback?.onStatusChanged("设备信息已接收: $manufacturer $model")
            
        } catch (e: Exception) {
            Log.e(TAG, "处理设备信息响应异常: ${e.message}")
        }
    }
    
    /**
     * 处理电量响应
     */
    private fun handleBatteryResponse(data: ByteArray) {
        try {
            if (data.isNotEmpty()) {
                val batteryLevel = data[0].toInt() and 0xFF
                Log.d(TAG, "电量: $batteryLevel%")
                callback?.onBatteryLevelReceived(batteryLevel)
                callback?.onStatusChanged("电量: $batteryLevel%")
            }
        } catch (e: Exception) {
            Log.e(TAG, "处理电量响应异常: ${e.message}")
        }
    }
    
    /**
     * 处理采集响应
     */
    private fun handleCollectionResponse(data: ByteArray) {
        try {
            if (data.isNotEmpty()) {
                val status = data[0].toInt() and 0xFF
                isCollecting = status == Protocol.COLLECTION_ON
                Log.d(TAG, "采集状态: ${if (isCollecting) "开启" else "关闭"}")
                callback?.onCollectionStatusChanged(isCollecting)
                callback?.onStatusChanged("采集状态: ${if (isCollecting) "开启" else "关闭"}")
            }
        } catch (e: Exception) {
            Log.e(TAG, "处理采集响应异常: ${e.message}")
        }
    }
    
    /**
     * 处理数据流
     */
    private fun handleDataStream(data: ByteArray) {
        try {
            Log.d(TAG, "收到数据流: ${data.size} 字节")
            callback?.onDataReceived(data)
            callback?.onProtocolDataReceived(Protocol.FUNC_DATA_STREAM, data)
        } catch (e: Exception) {
            Log.e(TAG, "处理数据流异常: ${e.message}")
        }
    }
    
    /**
     * 处理报警数据
     */
    private fun handleAlarmData(data: ByteArray) {
        try {
            Log.d(TAG, "收到报警数据: ${data.size} 字节")
            callback?.onProtocolDataReceived(Protocol.FUNC_ALARM_DATA, data)
            callback?.onStatusChanged("收到报警数据")
        } catch (e: Exception) {
            Log.e(TAG, "处理报警数据异常: ${e.message}")
        }
    }
    
    /**
     * 处理状态报告
     */
    private fun handleStatusReport(data: ByteArray) {
        try {
            Log.d(TAG, "收到状态报告: ${data.size} 字节")
            callback?.onProtocolDataReceived(Protocol.FUNC_STATUS_REPORT, data)
            callback?.onStatusChanged("收到状态报告")
        } catch (e: Exception) {
            Log.e(TAG, "处理状态报告异常: ${e.message}")
        }
    }
    
    /**
     * 发送字符串指令（自动转换为字节数组）
     */
    fun sendStringCommand(command: String) {
        val commandBytes = command.toByteArray()
        sendCommand(commandBytes)
    }
    
    /**
     * 发送十六进制指令
     */
    fun sendHexCommand(hexString: String) {
        try {
            val command = hexString.replace(" ", "").replace("0x", "").replace(",", "")
            val bytes = ByteArray(command.length / 2)
            for (i in bytes.indices) {
                val index = i * 2
                bytes[i] = command.substring(index, index + 2).toInt(16).toByte()
            }
            sendCommand(bytes)
        } catch (e: Exception) {
            Log.e(TAG, "十六进制指令格式错误: ${e.message}")
            callback?.onCommandSent(false, "十六进制指令格式错误: ${e.message}")
        }
    }
    
    /**
     * 开启采集
     * 功能码: 0x0001
     * 数据格式: [采集开关(1字节)] [时间戳(8字节)]
     */
    fun startCollection(timestamp: Long = 0L) {
        try {
            val data = ByteArray(9)
            var index = 0
            
            // 采集开关: 0x01 (开启)
            data[index++] = Protocol.COLLECTION_ON.toByte()
            
            // 时间戳: 8字节 (小端格式)
            for (i in 0..7) {
                data[index++] = ((timestamp shr (i * 8)) and 0xFF).toByte()
            }
            
            val packet = buildProtocolPacket(Protocol.FUNC_START_COLLECTION, data)
            Log.d(TAG, "发送开启采集指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
        } catch (e: Exception) {
            Log.e(TAG, "构建开启采集指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建开启采集指令失败: ${e.message}")
        }
    }
    
    /**
     * 停止采集
     * 功能码: 0x0001
     * 数据格式: [采集开关(1字节)] [时间戳(8字节)]
     */
    fun stopCollection(timestamp: Long = 0L) {
        try {
            val data = ByteArray(9)
            var index = 0
            
            // 采集开关: 0x00 (关闭)
            data[index++] = Protocol.COLLECTION_OFF.toByte()
            
            // 时间戳: 8字节 (小端格式)
            for (i in 0..7) {
                data[index++] = ((timestamp shr (i * 8)) and 0xFF).toByte()
            }
            
            val packet = buildProtocolPacket(Protocol.FUNC_START_COLLECTION, data)
            Log.d(TAG, "发送停止采集指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
        } catch (e: Exception) {
            Log.e(TAG, "构建停止采集指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建停止采集指令失败: ${e.message}")
        }
    }
    
    /**
     * 高级电刺激控制
     * 功能码: 0x0003
     * 数据格式: [开关及类型(1字节)] + [强度(1字节)] + [频率(2字节)] + [总持续时间(2字节)] + [休息时间(2字节)] + [静默时间(2字节)] + [缓进时间(1字节)] + [保持时间(1字节)] + [缓出时间(1字节)]
     * 数据长度：15字节
     */
    fun stimSwitch(
        enable: Boolean,           // 开关状态：true=开启，false=关闭
        stimType: Int = 0,        // 电刺激类型：0x00=关闭，0x10~0x1F=开启+类型
        intensity: Int = 50,       // 强度值：1-100
        frequency: Int = 100,      // 频率值：Hz
        totalDuration: Int = 5000, // 总持续时间：毫秒
        restTime: Int = 1000,     // 休息时间：毫秒
        silenceTime: Int = 500,   // 静默时间：毫秒
        fadeInTime: Int = 1,      // 缓进时间：秒
        holdTime: Int = 3,        // 保持时间：秒
        fadeOutTime: Int = 1      // 缓出时间：秒
    ) {
        try {
            // 根据表格：总包19字节 = 功能码(2) + 数据长度(2) + 数据内容(13) + CRC16(2)
            val packet = ByteArray(19)
            var index = 0
            
            // 1. 功能码 (2字节) - 小端格式
            packet[index++] = (Protocol.FUNC_STIM_SWITCH and 0xFF).toByte()
            packet[index++] = ((Protocol.FUNC_STIM_SWITCH shr 8) and 0xFF).toByte()
            
            // 2. 数据长度 (2字节) - 小端格式，数据内容13字节
            packet[index++] = 13.toByte()  // 数据长度低字节
            packet[index++] = 0.toByte()   // 数据长度高字节
            
            // 3. 开关状态以及电刺激类型 (1字节)
            val switchAndType = if (enable) {
                val typeBits = stimType and 0x0F  // 低4位：类型
                (0x10 or typeBits).toByte()       // 0x10表示开启
            } else {
                0x00.toByte()                     // 0x00表示关闭
            }
            packet[index++] = switchAndType
            
            // 4. 强度 (1字节) - 限制在0-100范围内
            packet[index++] = (intensity.coerceIn(0, 100)).toByte()
            
            // 5. 频率 (2字节) - 小端格式
            packet[index++] = (frequency and 0xFF).toByte()
            packet[index++] = ((frequency shr 8) and 0xFF).toByte()
            
            // 6. 总持续时间 (2字节) - 小端格式
            packet[index++] = (totalDuration and 0xFF).toByte()
            packet[index++] = ((totalDuration shr 8) and 0xFF).toByte()
            
            // 7. 休息时间 (2字节) - 小端格式
            packet[index++] = (restTime and 0xFF).toByte()
            packet[index++] = ((restTime shr 8) and 0xFF).toByte()
            
            // 8. 静默时间 (2字节) - 小端格式
            packet[index++] = (silenceTime and 0xFF).toByte()
            packet[index++] = ((silenceTime shr 8) and 0xFF).toByte()
            
            // 9. 缓进时间 (1字节)
            packet[index++] = (fadeInTime.coerceIn(0, 255)).toByte()
            
            // 10. 保持时间 (1字节)
            packet[index++] = (holdTime.coerceIn(0, 255)).toByte()
            
            // 11. 缓出时间 (1字节)
            packet[index++] = (fadeOutTime.coerceIn(0, 255)).toByte()
            
            // 12. CRC16校验 (2字节) - 计算前面17字节的CRC
            val crc = calculateCRC16(packet, 0, 17)
            packet[index++] = (crc and 0xFF).toByte()
            packet[index++] = ((crc shr 8) and 0xFF).toByte()
            
            // 详细日志记录
            Log.d(TAG, "发送高级电刺激控制指令 (19字节):")
            Log.d(TAG, "  开关状态: ${if (enable) "开启" else "关闭"}")
            Log.d(TAG, "  刺激类型: $stimType")
            Log.d(TAG, "  强度: $intensity")
            Log.d(TAG, "  频率: ${frequency}Hz")
            Log.d(TAG, "  总持续时间: ${totalDuration}ms")
            Log.d(TAG, "  休息时间: ${restTime}ms")
            Log.d(TAG, "  静默时间: ${silenceTime}ms")
            Log.d(TAG, "  缓进时间: ${fadeInTime}s")
            Log.d(TAG, "  保持时间: ${holdTime}s")
            Log.d(TAG, "  缓出时间: ${fadeOutTime}s")
            Log.d(TAG, "数据包结构: 功能码(2) + 数据长度(2) + 数据内容(13) + CRC16(2) = 19字节")
            Log.d(TAG, "数据包: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            
            sendCommand(packet)
            
        } catch (e: Exception) {
            Log.e(TAG, "构建高级电刺激控制指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建高级电刺激控制指令失败: ${e.message}")
        }
    }
    
    /**
     * 简化版电刺激开关（为了保持向后兼容）
     */
    fun stimSwitchSimple(stimType: Int, enable: Boolean) {
        stimSwitch(
            enable = enable,
            stimType = stimType,
            intensity = if (enable) 50 else 0,
            frequency = if (enable) 100 else 0,
            totalDuration = if (enable) 5000 else 0,
            restTime = 1000,
            silenceTime = 500,
            fadeInTime = 1,
            holdTime = 3,
            fadeOutTime = 1
        )
    }

    /**
     * 电刺激预设：高强度短期刺激
     */
    fun stimHighIntensityShort(
        stimType: Int = 1,
        durationSeconds: Int = 30,
        intensity: Int = 80
    ) {
        stimSwitch(
            enable = true,
            stimType = stimType,
            intensity = intensity,
            frequency = 150,
            totalDuration = durationSeconds * 1000,
            restTime = 200,
            silenceTime = 100,
            fadeInTime = 2,
            holdTime = durationSeconds - 4,
            fadeOutTime = 2
        )
    }
    
    /**
     * 电刺激预设：低强度长期刺激
     */
    fun stimLowIntensityLong(
        stimType: Int = 1,
        durationMinutes: Int = 15,
        intensity: Int = 30
    ) {
        stimSwitch(
            enable = true,
            stimType = stimType,
            intensity = intensity,
            frequency = 80,
            totalDuration = durationMinutes * 60 * 1000,
            restTime = 1000,
            silenceTime = 500,
            fadeInTime = 5,
            holdTime = (durationMinutes * 60) - 10,
            fadeOutTime = 5
        )
    }
    
    /**
     * 电刺激预设：康复训练模式
     */
    fun stimRehabilitationMode(
        stimType: Int = 2,
        intensity: Int = 60
    ) {
        stimSwitch(
            enable = true,
            stimType = stimType,
            intensity = intensity,
            frequency = 120,
            totalDuration = 300000, // 5分钟
            restTime = 2000,        // 2秒休息
            silenceTime = 1000,     // 1秒静默
            fadeInTime = 3,
            holdTime = 300,         // 5分钟保持
            fadeOutTime = 3
        )
    }
    
    /**
     * 同步时间戳
     * 功能码: 0x0080
     * 数据格式: [时间戳(8字节, 小端, 毫秒)]
     */
    fun syncTimestamp(timestampMs: Long) {
        try {
            val data = ByteArray(8)
            for (i in 0..7) {
                data[i] = ((timestampMs shr (i * 8)) and 0xFF).toByte()
            }
            val packet = buildProtocolPacket(Protocol.FUNC_SYNC_TIMESTAMP, data)
            Log.d(TAG, "发送同步时间戳指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
        } catch (e: Exception) {
            Log.e(TAG, "构建同步时间戳指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建同步时间戳指令失败: ${e.message}")
        }
    }

    /**
     * 设置采样率
     * 功能码: 0x0003
     * 数据格式: [采样率(2字节)]
     */
    // 已移除：设置采样率（按PDF未列出）
    
    /**
     * 设置增益
     * 功能码: 0x0004
     * 数据格式: [增益(1字节)]
     */
    // 已移除：设置增益（按PDF未列出）
    
    /**
     * 设置导联
     * 功能码: 0x0006
     * 数据格式: [导联(1字节)]
     */
    // 已移除：设置导联（按PDF未列出）
    
    /**
     * 工频滤波开关
     * 功能码: 0x000A
     * 数据格式: [开关状态(1字节)]
     */
    fun togglePowerLineFilter(enable: Boolean) {
        try {
            val data = ByteArray(1)
            data[0] = if (enable) Protocol.POWER_LINE_FILTER_ON.toByte() else Protocol.POWER_LINE_FILTER_OFF.toByte()
            
            val packet = buildProtocolPacket(Protocol.FUNC_POWER_LINE_FILTER, data)
            Log.d(TAG, "发送工频滤波${if (enable) "开启" else "关闭"}指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
            powerLineFilterEnabled = enable
            
        } catch (e: Exception) {
            Log.e(TAG, "构建工频滤波指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建工频滤波指令失败: ${e.message}")
        }
    }
    
    /**
     * 查询状态
     * 功能码: 0x000B
     */
    // 已移除：查询状态（按PDF未列出）
    
    /**
     * 设备复位
     * 功能码: 0x000C
     */
    // 已移除：设备复位（按PDF未列出）
    
    /**
     * 获取协议统计信息
     */
    fun getProtocolStats(): Map<String, Any?> {
        return mapOf(
            "totalPacketsSent" to totalPacketsSent,
            "totalBytesSent" to totalBytesSent,
            "totalPacketsReceived" to totalPacketsReceived,
            "totalBytesReceived" to totalBytesReceived,
            "isCollecting" to isCollecting,
            // 已移除：采样率、增益、导联状态（按PDF协议未定义）
            "powerLineFilterEnabled" to powerLineFilterEnabled,
            "deviceInfo" to deviceInfo
        )
    }
    
    /**
     * 直接连接到指定MAC地址的设备
     */
    fun connectToMacAddress(macAddress: String) {
        if (isConnecting || isConnected) {
            callback?.onError("正在连接或已连接")
            return
        }
        
        try {
            // 检查权限
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                callback?.onError("缺少蓝牙连接权限")
                return
            }
            
            // 检查蓝牙适配器
            if (bluetoothAdapter == null) {
                callback?.onError("蓝牙适配器未初始化")
                return
            }
            
            
            // 尝试获取设备
            val device = bluetoothAdapter!!.getRemoteDevice(macAddress)
            if (device == null) {
                callback?.onError("无法获取设备: $macAddress")
                return
            }
            
            Log.d(TAG, "尝试直接连接到设备: $macAddress")
            callback?.onStatusChanged("正在连接设备: $macAddress")
            callback?.onStatusChanged("⏱️ 连接超时时间: 30秒")
            callback?.onStatusChanged("💡 请确保目标设备:")
            callback?.onStatusChanged("   • 蓝牙已开启")
            callback?.onStatusChanged("   • 设置为可发现模式")
            callback?.onStatusChanged("   • 在10米范围内")
            callback?.onStatusChanged("   • 未与其他设备连接")
            
            isConnecting = true
            
            // 连接设备 - 使用autoConnect=false以获得更快的连接
            bluetoothGatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE)
            
            // 设置连接超时
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                if (isConnecting && !isConnected) {
                    Log.w(TAG, "连接超时，尝试断开并重新连接")
                    callback?.onStatusChanged("⏰ 连接超时，正在重试...")
                    
                    // 断开当前连接
                    bluetoothGatt?.disconnect()
                    bluetoothGatt?.close()
                    bluetoothGatt = null
                    
                    // 重置状态
                    isConnecting = false
                    
                    // 尝试使用传统蓝牙连接
                    callback?.onStatusChanged("🔄 尝试使用传统蓝牙连接...")
                    bluetoothGatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_AUTO)
                    isConnecting = true
                    
                    // 再次设置超时
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        if (isConnecting && !isConnected) {
                            Log.e(TAG, "连接最终失败")
                            callback?.onError("❌ 连接失败: 设备无响应")
                            callback?.onStatusChanged("💡 建议:")
                            callback?.onStatusChanged("   • 检查目标设备蓝牙设置")
                            callback?.onStatusChanged("   • 尝试在系统蓝牙设置中手动配对")
                            callback?.onStatusChanged("   • 重启两台设备的蓝牙")
                            isConnecting = false
                        }
                    }, 15000) // 15秒超时
                }
            }, 30000) // 30秒超时
            
        } catch (e: Exception) {
            Log.e(TAG, "直接连接失败: ${e.message}")
            callback?.onError("直接连接失败: ${e.message}")
            isConnecting = false
        }
    }
    
    
    /**
     * 计算CRC16-CCITT-FALSE校验
     */
    private fun calculateCRC16(data: ByteArray, offset: Int, length: Int): Int {
        var wCRCin = 0xFFFF
        val wCPoly = 0x1021
        
        for (i in offset until offset + length) {
            for (j in 0..7) {
                val bit = ((data[i].toInt() shr (7 - j)) and 1) == 1
                val c15 = ((wCRCin shr 15) and 1) == 1
                wCRCin = wCRCin shl 1
                if (c15 xor bit) {
                    wCRCin = wCRCin xor wCPoly
                }
            }
        }
        
        return wCRCin and 0xFFFF
    }
    
    /**
     * GATT回调
     */
    private val gattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            when (newState) {
                BluetoothProfile.STATE_CONNECTED -> {
                    Log.d(TAG, "设备已连接，状态: $status")
                    isConnected = true
                    isConnecting = false
                    callback?.onConnected(gatt.device)
                    callback?.onStatusChanged("✅ 设备已连接: ${gatt.device.name ?: gatt.device.address}")
                    
                    // 发现服务
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        gatt.discoverServices()
                    }
                }
                BluetoothProfile.STATE_DISCONNECTED -> {
                    Log.d(TAG, "设备已断开，状态: $status")
                    isConnected = false
                    isConnecting = false
                    callback?.onDisconnected()
                    
                    when (status) {
                        0 -> {
                            callback?.onStatusChanged("❌ 设备已断开连接")
                            callback?.onStatusChanged("💡 可能原因：设备超出范围、蓝牙关闭、连接超时等")
                        }
                        8 -> {
                            callback?.onStatusChanged("❌ 连接超时")
                            callback?.onStatusChanged("💡 设备可能不可见或距离过远")
                        }
                        19 -> {
                            callback?.onStatusChanged("❌ 连接被拒绝")
                            callback?.onStatusChanged("💡 设备可能正在与其他设备连接")
                        }
                        22 -> {
                            callback?.onStatusChanged("❌ 连接失败")
                            callback?.onStatusChanged("💡 设备可能不支持此连接方式")
                        }
                        else -> {
                            callback?.onStatusChanged("❌ 连接失败，状态码: $status")
                            callback?.onStatusChanged("💡 请检查设备状态和设置")
                        }
                    }
                    callback?.onStatusChanged("🔄 如需重新连接，请点击'连接蓝牙'按钮")
                }
            }
        }
        
        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "服务发现成功")
                callback?.onStatusChanged("🔍 服务发现成功")
                
                // 打印所有可用服务
                val services = gatt.services
                Log.d(TAG, "设备提供的服务数量: ${services.size}")
                callback?.onStatusChanged("📋 发现 ${services.size} 个服务")
                
                for (service in services) {
                    Log.d(TAG, "发现服务: ${service.uuid}")
                    callback?.onStatusChanged("发现服务: ${service.uuid}")
                    
                    // 打印服务的所有特征
                    val characteristics = service.characteristics
                    Log.d(TAG, "服务 ${service.uuid} 的特征数量: ${characteristics.size}")
                    
                    for (characteristic in characteristics) {
                        Log.d(TAG, "发现特征: ${characteristic.uuid}")
                        callback?.onStatusChanged("发现特征: ${characteristic.uuid}")
                    }
                }
                
                // 尝试查找匹配的服务和特征
                var foundService: BluetoothGattService? = null
                var foundCharacteristic: BluetoothGattCharacteristic? = null
                var foundNotifyCharacteristic: BluetoothGattCharacteristic? = null
                
                // 首先尝试预设的UUID列表
                for (i in SERVICE_UUIDS.indices) {
                    val serviceUuid = SERVICE_UUIDS[i]
                    val service = gatt.getService(serviceUuid)
                    if (service != null) {
                        Log.d(TAG, "找到匹配的服务: $serviceUuid")
                        foundService = service
                        
                        // 根据服务UUID确定设备类型
                        currentDeviceType = when (serviceUuid.toString().uppercase()) {
                            "0000ABF0-0000-1000-8000-00805F9B34FB" -> DeviceType.ESP32S3_DEVICE
                            "1BD790EC-E8B9-7580-0A46-44D30102EDA6" -> DeviceType.NEW_DEVICE
                            "6E400001-B5A3-F393-E0A9-68716563686F" -> DeviceType.QINGXUN
                            else -> DeviceType.QINGXUN // 默认为轻迅设备
                        }
                        
                        Log.d(TAG, "检测到设备类型: $currentDeviceType")
                        callback?.onStatusChanged("🔍 检测到设备类型: $currentDeviceType")
                        
                        // 查找对应的TX特征（用于发送数据）
                        val characteristicUuid = CHARACTERISTIC_UUIDS[i]
                        val characteristic = service.getCharacteristic(characteristicUuid)
                        if (characteristic != null) {
                            Log.d(TAG, "找到TX特征: $characteristicUuid")
                            foundCharacteristic = characteristic
                        }
                        
                        // 查找对应的RX特征（用于接收数据）
                        val notifyUuid = NOTIFY_CHARACTERISTIC_UUIDS[i]
                        val notifyCharacteristic = service.getCharacteristic(notifyUuid)
                        if (notifyCharacteristic != null) {
                            Log.d(TAG, "找到RX特征: $notifyUuid")
                            foundNotifyCharacteristic = notifyCharacteristic
                        }
                        break
                    }
                }
                
                // 如果预设UUID没有找到，尝试智能检测
                if (foundService == null || foundCharacteristic == null || foundNotifyCharacteristic == null) {
                    Log.d(TAG, "预设UUID未找到匹配，尝试智能检测")
                    
                    // 查找所有非标准蓝牙服务的UUID
                    for (service in services) {
                        val serviceUuid = service.uuid.toString()
                        
                        // 跳过标准蓝牙服务（如2a00, 2a01等）
                        if (!serviceUuid.contains("00002a") && !serviceUuid.contains("000018")) {
                            Log.d(TAG, "发现自定义服务: $serviceUuid")
                            
                            // 查找该服务下的所有特征
                            for (characteristic in service.characteristics) {
                                val characteristicUuid = characteristic.uuid.toString()
                                
                                // 跳过标准特征
                                if (!characteristicUuid.contains("00002a")) {
                                    Log.d(TAG, "发现自定义特征: $characteristicUuid")
                                    
                                    // 检查特征是否支持写入（TX特征）
                                    if (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE != 0 ||
                                        characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE != 0) {
                                        
                                        Log.d(TAG, "找到支持写入的特征(TX): $characteristicUuid")
                                        if (foundService == null) foundService = service
                                        if (foundCharacteristic == null) foundCharacteristic = characteristic
                                    }
                                    
                                    // 检查特征是否支持通知（RX特征）
                                    if (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0 ||
                                        characteristic.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0) {
                                        
                                        Log.d(TAG, "找到支持通知的特征(RX): $characteristicUuid")
                                        if (foundService == null) foundService = service
                                        if (foundNotifyCharacteristic == null) foundNotifyCharacteristic = characteristic
                                    }
                                }
                            }
                            if (foundService != null && foundCharacteristic != null && foundNotifyCharacteristic != null) break
                        }
                    }
                }
                
                if (foundService != null && foundCharacteristic != null && foundNotifyCharacteristic != null) {
                    // 保存当前服务特征，用于发送和接收数据
                    currentService = foundService
                    currentCharacteristic = foundCharacteristic
                    currentNotifyCharacteristic = foundNotifyCharacteristic
                    
                    // 启用通知
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "=== 启用特征通知 ===")
                        Log.d(TAG, "服务UUID: ${foundService.uuid}")
                        Log.d(TAG, "TX特征UUID: ${foundCharacteristic.uuid}")
                        Log.d(TAG, "RX特征UUID: ${foundNotifyCharacteristic.uuid}")
                        Log.d(TAG, "TX特征属性: ${foundCharacteristic.properties}")
                        Log.d(TAG, "RX特征属性: ${foundNotifyCharacteristic.properties}")
                        
                        // 启用RX特征的通知
                        val success = gatt.setCharacteristicNotification(foundNotifyCharacteristic, true)
                        Log.d(TAG, "启用RX特征通知结果: $success")
                        
                        // 写入Descriptor来激活通知
                        val descriptor = foundNotifyCharacteristic.getDescriptor(
                            UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") // Client Characteristic Configuration Descriptor
                        )
                        if (descriptor != null) {
                            descriptor.value = android.bluetooth.BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                            val writeSuccess = gatt.writeDescriptor(descriptor)
                            Log.d(TAG, "写入Descriptor结果: $writeSuccess")
                        } else {
                            Log.w(TAG, "未找到Client Characteristic Configuration Descriptor")
                        }
                        
                        callback?.onStatusChanged("📡 数据通道已建立，可以发送指令开始接收数据")
                        callback?.onStatusChanged("💡 提示: 长按'发送指令'按钮可以发送测试数据")
                    } else {
                        Log.e(TAG, "缺少BLUETOOTH_CONNECT权限")
                        callback?.onError("缺少BLUETOOTH_CONNECT权限")
                    }
                } else {
                    Log.e(TAG, "未找到匹配的服务或特征")
                    callback?.onError("未找到匹配的服务或特征，请检查设备协议")
                    
                    // 提供所有可用服务的UUID供参考
                    val availableServices = services.joinToString(", ") { it.uuid.toString() }
                    Log.d(TAG, "可用服务UUID: $availableServices")
                    callback?.onStatusChanged("可用服务: $availableServices")
                }
            } else {
                Log.e(TAG, "服务发现失败，状态: $status")
                callback?.onError("服务发现失败，状态: $status")
            }
        }
        
                override fun onDescriptorWrite(gatt: android.bluetooth.BluetoothGatt, descriptor: android.bluetooth.BluetoothGattDescriptor, status: Int) {
            if (status == android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "Descriptor写入成功: ${descriptor.uuid}")
                callback?.onStatusChanged("✅ Notify通道已激活，可以接收设备数据")
            } else {
                Log.e(TAG, "Descriptor写入失败，状态: $status")
                callback?.onError("Notify通道激活失败，状态: $status")
            }
        }
        
        override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
            val data = characteristic.value
            Log.d(TAG, "=== 蓝牙特征值变化 ===")
            Log.d(TAG, "特征UUID: ${characteristic.uuid}")
            Log.d(TAG, "当前RX特征UUID: ${currentNotifyCharacteristic?.uuid}")
            Log.d(TAG, "接收到数据: ${data.size} 字节")
            
            if (data.isNotEmpty()) {
                Log.d(TAG, "数据前10字节: ${data.take(10).joinToString(", ") { "0x%02X".format(it) }}")
                
                // 分析244字节数据包结构
                if (data.size == 244) {
                    Log.d(TAG, "=== 244字节数据包结构分析 ===")
                    Log.d(TAG, "前4字节: ${data.take(4).joinToString(", ") { "0x%02X".format(it) }}")
                    Log.d(TAG, "后4字节: ${data.takeLast(4).joinToString(", ") { "0x%02X".format(it) }}")
                    
                    // 尝试解析为轻迅协议
                    val functionCode = (data[1].toInt() and 0xFF shl 8) or (data[0].toInt() and 0xFF)
                    val dataLength = (data[3].toInt() and 0xFF shl 8) or (data[2].toInt() and 0xFF)
                    
                    Log.d(TAG, "解析功能码: 0x${functionCode.toString(16).uppercase()}")
                    Log.d(TAG, "解析数据长度: $dataLength")
                    
                                if (functionCode == Protocol.FUNC_DATA_STREAM && dataLength == 238) {
                         Log.d(TAG, "✅ 确认是轻迅协议数据流包")
                         Log.d(TAG, "协议包结构: 功能码(2) + 数据长度(2) + 数据内容(238) + CRC16(2) = 244字节")
                         
                         // 提取238字节的设备数据内容（跳过功能码和数据长度，不包含CRC16）
                         val deviceData = ByteArray(238)
                         System.arraycopy(data, 4, deviceData, 0, 238)
                         
                         Log.d(TAG, "提取设备数据: ${deviceData.size} 字节")
                         Log.d(TAG, "设备数据前10字节: ${deviceData.take(10).joinToString(", ") { "0x%02X".format(it) }}")
                         
                         // 238字节设备数据直接传递给回调，不进行轻迅协议解析
                         Log.d(TAG, "✅ 设备数据直接传递给C++解析器")
                         callback?.onDataReceived(deviceData)
                         callback?.onProtocolDataReceived(Protocol.FUNC_DATA_STREAM, deviceData)
                    } else {
                        Log.d(TAG, "⚠️ 不是标准轻迅协议格式，尝试其他解析方式")
                        handleRawData(data)
                    }
                } else {
                    Log.d(TAG, "数据包大小: ${data.size} 字节，不是244字节")
                    handleRawData(data)
                }
            }
            
            // 检查是否是RX特征
            if (characteristic.uuid == currentNotifyCharacteristic?.uuid) {
                Log.d(TAG, "✅ 收到RX特征数据")
            } else {
                Log.d(TAG, "⚠️ 收到非RX特征数据，UUID不匹配")
                Log.d(TAG, "收到特征UUID: ${characteristic.uuid}")
                Log.d(TAG, "期望RX特征UUID: ${currentNotifyCharacteristic?.uuid}")
                callback?.onDataReceived(data)
            }
        }
    }
    
    /**
     * BLE扫描回调
     */
    private val bleScanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            super.onScanResult(callbackType, result)
            
            val device = result.device
            val deviceName = device.name ?: "未知设备"
            val deviceAddress = device.address
            val rssi = result.rssi
            
            Log.d(TAG, "🔍 发现BLE设备: $deviceName ($deviceAddress) RSSI: $rssi")
            Log.d(TAG, "📊 设备详情: 名称=$deviceName, 地址=$deviceAddress, 信号=$rssi")
            
            // 显示详细的设备信息
            callback?.onStatusChanged("📱 发现BLE设备: $deviceName")
            callback?.onStatusChanged("   📍 地址: $deviceAddress")
            callback?.onStatusChanged("   📶 信号强度: $rssi dBm")
            callback?.onStatusChanged("   🔧 设备类型: ${device.type}")
            Log.d(TAG, "📱 设备类型: ${device.type}")
            
            // 检查是否是目标设备
            if (deviceAddress.equals("A4:C3:37:86:9F:73", ignoreCase = true) || 
                deviceAddress.equals("A4-C3-37-86-9F-73", ignoreCase = true)) {
                callback?.onStatusChanged("🎯 找到目标设备！")
                callback?.onStatusChanged("💡 建议：长按'连接蓝牙'按钮直接连接")
            }
            
            // 添加所有发现的设备（不进行过滤）
            addDiscoveredDevice(device)
            callback?.onDeviceFound(device)
        }
        
        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            Log.e(TAG, "BLE扫描失败，错误码: $errorCode")
            
            val errorMessage = when (errorCode) {
                SCAN_FAILED_ALREADY_STARTED -> "扫描已在进行中"
                SCAN_FAILED_APPLICATION_REGISTRATION_FAILED -> "应用注册失败"
                SCAN_FAILED_FEATURE_UNSUPPORTED -> "设备不支持BLE"
                SCAN_FAILED_INTERNAL_ERROR -> "内部错误"
                SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES -> "硬件资源不足"
                else -> "未知错误: $errorCode"
            }
            
            callback?.onError("❌ BLE扫描失败: $errorMessage")
            
            // 只在非混合模式下回退到传统蓝牙
            val isMixedScan = android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O || 
                             android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1
            
            if (!isMixedScan) {
                callback?.onStatusChanged("💡 尝试使用传统蓝牙扫描...")
                
                // 延迟1秒后启动传统蓝牙扫描，避免同时启动太多扫描
                android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                    try {
                        startClassicScan()
                    } catch (fallbackE: Exception) {
                        callback?.onError("❌ 传统蓝牙扫描也失败: ${fallbackE.message}")
                    }
                }, 1000)
            } else {
                callback?.onStatusChanged("⚠️ BLE扫描失败，但混合扫描模式将继续使用传统蓝牙")
            }
            
            // 在混合扫描模式下，只记录错误但不结束扫描
            if (!isMixedScan) {
                // 扫描失败时完成扫描
                callback?.onStatusChanged("扫描完成，找到 ${discoveredDevices.size} 个设备")
                callback?.onScanComplete(discoveredDevices.toList())
            }
        }
    }
    
    /**
     * 传统蓝牙扫描回调
     */
    private val classicScanReceiver = object : android.content.BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: android.content.Intent?) {
            when (intent?.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    device?.let {
                        Log.d(TAG, "🔍 发现传统蓝牙设备: ${it.name ?: "未知"} (${it.address})")
                        Log.d(TAG, "📱 设备类型: ${it.type}")
                        Log.d(TAG, "📶 设备状态: ${it.bondState}")
                        
                        // Android 8.1特殊处理
                        if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1) {
                            Log.d(TAG, "📱 Android 8.1检测到传统蓝牙设备")
                            callback?.onStatusChanged("📱 Android 8.1发现设备: ${it.name ?: "未知设备"}")
                        }
                        
                        // 添加所有发现的设备（不进行过滤）
                        addDiscoveredDevice(it)
                        callback?.onDeviceFound(it)
                    } ?: Log.w(TAG, "⚠️ ACTION_FOUND广播中未找到设备信息")
                }
                BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
                    Log.d(TAG, "传统蓝牙扫描开始")
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    Log.d(TAG, "传统蓝牙扫描完成")
                    val classicDeviceCount = discoveredDevices.count { it.type != BluetoothDevice.DEVICE_TYPE_LE }
                    val totalDeviceCount = discoveredDevices.size
                    
                    callback?.onStatusChanged("🔍 传统蓝牙扫描完成")
                    callback?.onStatusChanged("📊 传统蓝牙扫描结果：找到 $classicDeviceCount 个经典蓝牙设备")
                    callback?.onStatusChanged("📊 总共发现 $totalDeviceCount 个设备")
                    
                    // Android 8.1混合扫描模式特殊处理
                    val isMixedScan = android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O || 
                                     android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1
                    
                    if (isMixedScan) {
                        callback?.onStatusChanged("✅ Android 8.1混合扫描完成")
                        callback?.onStatusChanged("📱 BLE + 传统蓝牙双重扫描完成")
                    }
                    
                    callback?.onScanComplete(discoveredDevices.toList())
                }
            }
        }
    }
    
    /**
     * 注册传统蓝牙扫描广播接收器
     */
    private fun registerClassicScanReceiver() {
        try {
            if (!isClassicScanReceiverRegistered) {
                val filter = android.content.IntentFilter().apply {
                    addAction(BluetoothDevice.ACTION_FOUND)
                    addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
                    addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
                    // Android 8.1可能需要额外的广播动作
                    addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
                }
                
                // Android 8.1特殊处理：可能需要不同的注册方式
                if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1) {
                    Log.d(TAG, "📱 Android 8.1特殊注册广播接收器")
                    context.registerReceiver(classicScanReceiver, filter)
                    Log.d(TAG, "✅ Android 8.1广播接收器注册成功")
                } else {
                    context.registerReceiver(classicScanReceiver, filter)
                    Log.d(TAG, "✅ 传统蓝牙扫描广播接收器已注册")
                }
                
                isClassicScanReceiverRegistered = true
                Log.d(TAG, "传统蓝牙扫描广播接收器已注册")
                
                // Android 8.1特殊状态
                if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.O_MR1) {
                    Log.d(TAG, "📱 Android 8.1检测：扫描接收器已配置")
                    callback?.onStatusChanged("📱 Android 8.1检测：广播接收器已配置")
                }
            } else {
                Log.d(TAG, "传统蓝牙扫描广播接收器已注册，跳过重复注册")
            }
        } catch (e: Exception) {
            Log.e(TAG, "注册广播接收器失败: ${e.message}")
            callback?.onStatusChanged("❌ 广播接收器注册失败: ${e.message}")
            isClassicScanReceiverRegistered = false
        }
    }
    
    /**
     * 注销传统蓝牙扫描广播接收器
     */
    private fun unregisterClassicScanReceiver() {
        try {
            // 检查接收器是否已注册
            if (isClassicScanReceiverRegistered) {
                context.unregisterReceiver(classicScanReceiver)
                isClassicScanReceiverRegistered = false
                Log.d(TAG, "传统蓝牙扫描广播接收器已注销")
            } else {
                Log.d(TAG, "传统蓝牙扫描广播接收器未注册，跳过注销")
            }
        } catch (e: Exception) {
            Log.e(TAG, "注销广播接收器失败: ${e.message}")
            isClassicScanReceiverRegistered = false
        }
    }
    
    /**
     * 添加发现的设备
     */
    fun addDiscoveredDevice(device: BluetoothDevice) {
        if (!discoveredDevices.contains(device)) {
            discoveredDevices.add(device)
            
            // 显示详细的设备信息
            val deviceName = device.name ?: "未知设备"
            val deviceAddress = device.address
            val deviceType = when (device.type) {
                BluetoothDevice.DEVICE_TYPE_CLASSIC -> "经典蓝牙"
                BluetoothDevice.DEVICE_TYPE_LE -> "低功耗蓝牙"
                BluetoothDevice.DEVICE_TYPE_DUAL -> "双模蓝牙"
                else -> "未知类型"
            }
            
            Log.d(TAG, "发现设备: $deviceName ($deviceAddress) - $deviceType")
            callback?.onStatusChanged("📱 发现设备: $deviceName")
            callback?.onStatusChanged("   📍 地址: $deviceAddress")
            callback?.onStatusChanged("   🔧 类型: $deviceType")
            
            // 检查是否是ESP32S3 SPP服务器或目标设备
            val isESP32S3Device = deviceName.contains("ESP_SPP_SERVER", ignoreCase = true)
            val isLegacyTargetDevice = deviceAddress.equals("A4:C3:37:86:9F:73", ignoreCase = true) || 
                                     deviceAddress.equals("A4-C3-37-86-9F-73", ignoreCase = true)
            
            if (isESP32S3Device) {
                callback?.onStatusChanged("🔌 ESP32S3 SPP服务器！")
                callback?.onStatusChanged("   📡 SPP服务：0xABF0")
                callback?.onStatusChanged("   📤 数据发送：0xABF1/0xABF3")
                callback?.onStatusChanged("   📥 数据接收：0xABF2/0xABF4")
                callback?.onStatusChanged("💡 优先级设备，建议立即连接")
            } else if (isLegacyTargetDevice) {
                callback?.onStatusChanged("🎯 找到传统目标设备！")
                callback?.onStatusChanged("💡 建议：长按'连接蓝牙'按钮直接连接")
            }
            
            callback?.onDeviceFound(device)
        }
    }
    
    /**
     * 获取发现的设备列表
     */
    fun getDiscoveredDevices(): List<BluetoothDevice> {
        return discoveredDevices.toList()
    }
    
    /**
     * 获取连接状态
     */
    fun isConnected(): Boolean = isConnected
    
    /**
     * 获取连接中状态
     */
    fun isConnecting(): Boolean = isConnecting
    
    /**
     * 调试函数：检查当前连接状态和特征
     */
    fun debugConnectionStatus(): String {
        val status = StringBuilder()
        status.append("=== 连接状态调试信息 ===\n")
        status.append("连接状态: ${if (isConnected) "已连接" else "未连接"}\n")
        status.append("连接中状态: ${if (isConnecting) "连接中" else "未连接中"}\n")
        status.append("当前服务: ${currentService?.uuid ?: "未设置"}\n")
        status.append("当前TX特征: ${currentCharacteristic?.uuid ?: "未设置"}\n")
        status.append("当前RX特征: ${currentNotifyCharacteristic?.uuid ?: "未设置"}\n")
        status.append("RX特征属性: ${currentNotifyCharacteristic?.properties ?: "未设置"}\n")
        status.append("数据统计:\n")
        status.append("  发送包数: $totalPacketsSent\n")
        status.append("  发送字节: $totalBytesSent\n")
        status.append("  接收包数: $totalPacketsReceived\n")
        status.append("  接收字节: $totalBytesReceived\n")
        return status.toString()
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            Log.d(TAG, "开始清理BluetoothManager资源")
            
            // 设置清理标志，防止后续操作
            isCleaningUp = true
            
            // 取消所有延迟任务
            bleScanStopRunnable?.let { 
                mainHandler.removeCallbacks(it)
                bleScanStopRunnable = null
                Log.d(TAG, "已取消BLE扫描延迟任务")
            }
            
            // 断开连接
            disconnect()
            
            // 停止扫描（现在会检查isCleaningUp标志）
            stopScan()
            
            // 注销广播接收器（如果已注册）
            if (isClassicScanReceiverRegistered) {
                unregisterClassicScanReceiver()
            }
            
            // 清理状态
            isClassicScanReceiverRegistered = false
            isConnected = false
            isConnecting = false
            
            Log.d(TAG, "BluetoothManager资源清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "清理BluetoothManager资源时发生异常: ${e.message}")
        } finally {
            // 确保清理标志被设置
            isCleaningUp = true
        }
    }
}
