package com.example.cmake_project_test

import androidx.appcompat.app.AppCompatActivity
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.graphics.Color
import android.bluetooth.BluetoothDevice
import android.Manifest
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.view.View
import com.example.cmake_project_test.databinding.ActivityMainBinding
import type.SensorData

class MainActivity : AppCompatActivity(), NativeMethodCallback, DataManager.RealTimeDataCallback, BluetoothManager.BluetoothCallback {

    companion object {
        private const val PERMISSION_REQUEST_CODE = 1001
        
        // 根据Android版本动态确定所需权限
        private val REQUIRED_PERMISSIONS: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12+ 使用新的蓝牙权限，但仍然需要位置权限用于扫描
            arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        } else {
            // Android 11及以下需要位置权限
            arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        }
        
        // Used to load the 'cmake_project_test' library on application startup.
        init {
            System.loadLibrary("cmake_project_test")
        }
    }

    private lateinit var binding: ActivityMainBinding
    private lateinit var dataManager: DataManager
    private lateinit var uiManager: UiManager
    private lateinit var bluetoothManager: BluetoothManager
    
    // 数据处理状态
    private var dataProcessingStarted = false
    private var bluetoothConnected = false
    
    // 数据监控相关
    private var dataLogBuffer = StringBuilder()
    private var receivedDataCount = 0
    private var sentDataCount = 0
    private var lastDataTime = 0L
    private var dataRate = 0f
    private var isDataMonitoringEnabled = true
    
    // 状态更新控制
    private var lastStatusUpdateTime = 0L
    private var lastLogTime = 0L
    private var lastDeviceFoundTime = 0L
    private var lastDataLogTime = 0L
    private var lastDataStatusTime = 0L
    private var lastChartUpdateTime = 0L
    private var lastChartStatusTime = 0L
    private var lastProgressUpdateTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 初始化管理器
        dataManager = DataManager(this) // 传入this作为NativeMethodCallback
        dataManager.setRealTimeCallback(this) // 设置实时数据回调
        uiManager = UiManager()
        bluetoothManager = BluetoothManager(this) // 初始化蓝牙管理器
        bluetoothManager.setCallback(this) // 设置蓝牙回调

        // 初始化UI
        val permissionStatus = checkPermissionStatus()
        binding.sampleText.text = "应用已就绪，可以开始使用\n\n权限状态:\n$permissionStatus\n\n点击\"连接蓝牙\"按钮开始蓝牙连接..."

        // 初始化ECG双视图
        binding.ecgRhythmView.updateData(emptyList())
        binding.ecgWaveformView.updateData(emptyList())
        
        // 确保图表容器可见
        binding.ecgChartContainer.visibility = View.VISIBLE

        // 设置按钮点击事件
        setupButtonListeners()
    }

    private fun setupButtonListeners() {
        // 蓝牙连接按钮点击事件
        binding.bluetoothButton.setOnClickListener {
            toggleBluetoothConnection()
        }

        // 启动按钮点击事件
        binding.startButton.setOnClickListener {
            startDataProcessing()
        }

        // 发送指令按钮点击事件
        binding.sendCommandButton.setOnClickListener {
            sendDataCommand()
        }

        // 停止按钮点击事件
        binding.stopButton.setOnClickListener {
            stopDataProcessing()
        }

        // 陷波滤波器按钮点击事件
        binding.notchFilterButton.setOnClickListener {
            toggleNotchFilter()
        }
        
        // 清空数据按钮点击事件
        binding.clearDataButton.setOnClickListener {
            clearAllData()
        }
        
        // 添加直接连接测试按钮（长按蓝牙按钮）
        binding.bluetoothButton.setOnLongClickListener {
            showDirectConnectDialog()
            true
        }
        
        // 添加调试状态按钮（长按发送指令按钮）
        binding.sendCommandButton.setOnLongClickListener {
            showDebugStatusDialog()
            true
        }
    }

    private var notchFilterEnabled = false

    private fun toggleBluetoothConnection() {
        if (bluetoothConnected) {
            // 断开连接
            bluetoothManager.disconnect()
            bluetoothConnected = false
            binding.bluetoothButton.text = "连接蓝牙"
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#4CAF50"))
            updateStatus("蓝牙已断开")
        } else {
            // 检查权限后再开始扫描
            if (checkAndRequestPermissions()) {
                startBluetoothScan()
            }
        }
    }

    private fun startBluetoothScan() {
        bluetoothManager.startScan()
        binding.bluetoothButton.text = "扫描中..."
        binding.bluetoothButton.setBackgroundColor(Color.parseColor("#FF9800"))
        updateStatus("正在扫描蓝牙设备...")
    }

    private fun checkAndRequestPermissions(): Boolean {
        val missingPermissions = mutableListOf<String>()
        val grantedPermissions = mutableListOf<String>()
        
        updateStatus("🔍 检查蓝牙权限...")
        
        for (permission in REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) {
                grantedPermissions.add(permission.split(".").last())
            } else {
                missingPermissions.add(permission)
            }
        }
        
        // 显示权限状态
        if (grantedPermissions.isNotEmpty()) {
            updateStatus("✅ 已授予权限: ${grantedPermissions.joinToString(", ")}")
        }
        
        if (missingPermissions.isNotEmpty()) {
            val missingNames = missingPermissions.map { it.split(".").last() }
            updateStatus("❌ 缺少权限: ${missingNames.joinToString(", ")}")
            updateStatus("💡 正在请求权限...")
            
            ActivityCompat.requestPermissions(
                this,
                missingPermissions.toTypedArray(),
                PERMISSION_REQUEST_CODE
            )
            return false
        }
        
        updateStatus("✅ 所有必要权限已授予")
        return true
    }

    private fun checkPermissionStatus(): String {
        val status = mutableListOf<String>()
        
        for (permission in REQUIRED_PERMISSIONS) {
            val granted = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
            status.add("${permission.split(".").last()}: ${if (granted) "✓" else "✗"}")
        }
        
        return status.joinToString("\n")
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        when (requestCode) {
            PERMISSION_REQUEST_CODE -> {
                val grantedPermissions = mutableListOf<String>()
                val deniedPermissions = mutableListOf<String>()
                
                for (i in permissions.indices) {
                    val permission = permissions[i]
                    val granted = grantResults[i] == PackageManager.PERMISSION_GRANTED
                    
                    if (granted) {
                        grantedPermissions.add(permission.split(".").last())
                    } else {
                        deniedPermissions.add(permission.split(".").last())
                    }
                }
                
                if (grantedPermissions.isNotEmpty()) {
                    updateStatus("✅ 权限已授予: ${grantedPermissions.joinToString(", ")}")
                }
                
                if (deniedPermissions.isNotEmpty()) {
                    updateStatus("❌ 权限被拒绝: ${deniedPermissions.joinToString(", ")}")
                    updateStatus("💡 请在设置中手动授予权限")
                }
                
                val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
                
                if (allGranted) {
                    updateStatus("🎉 所有权限已授予，可以开始蓝牙扫描")
                    updateStatus("📡 正在启动蓝牙扫描...")
                    startBluetoothScan()
                } else {
                    updateStatus("⚠️ 部分权限被拒绝，蓝牙功能可能受限")
                    updateStatus("💡 建议：")
                    updateStatus("   • 进入应用设置 → 权限")
                    updateStatus("   • 手动开启蓝牙和位置权限")
                    updateStatus("   • 重启应用")
                    
                    binding.bluetoothButton.text = "权限被拒绝"
                    binding.bluetoothButton.setBackgroundColor(Color.parseColor("#9E9E9E"))
                }
            }
        }
    }

    private fun toggleNotchFilter() {
        notchFilterEnabled = !notchFilterEnabled
        
        // 更新DataManager中的陷波滤波器状态
        dataManager.notchFilterEnabled = notchFilterEnabled
        
        binding.notchFilterButton.text = if (notchFilterEnabled) "陷波滤波(开)" else "陷波滤波(关)"
        binding.notchFilterButton.setBackgroundColor(
            if (notchFilterEnabled) Color.parseColor("#FF5722") else Color.parseColor("#4CAF50")
        )
        
        // 更新UI显示
        val status = if (notchFilterEnabled) "已开启" else "已关闭"
        val currentText = binding.sampleText.text.toString()
        val updatedText = if (currentText.contains("陷波滤波器状态:")) {
            currentText.replace(Regex("陷波滤波器状态: .*?\\n"), "陷波滤波器状态: $status\n")
        } else {
            "陷波滤波器状态: $status\n\n$currentText"
        }
        binding.sampleText.text = updatedText
    }

    private fun startDataProcessing() {
        // 设置数据处理状态
        dataProcessingStarted = true
        
        // 启用停止按钮和陷波滤波器按钮
        binding.stopButton.isEnabled = true
        binding.notchFilterButton.isEnabled = true

        // 清空ECG双视图数据
        binding.ecgRhythmView.clearData()
        binding.ecgWaveformView.clearData()

        // 更新UI状态 - 专门用于蓝牙数据处理
        runOnUiThread {
            binding.sampleText.text = "蓝牙数据处理已启动\n\n等待接收蓝牙数据...\n\n状态: 准备就绪\n\n提示: 点击'启动程序'按钮可以立即测试图表显示"
        }
        
        Log.d("MainActivity", "蓝牙数据处理已启动，等待接收数据")
    }

    override fun onStart() {
        super.onStart()
        dataManager.ensureParser()
    }

    override fun onStop() {
        super.onStop()
        try {
            dataManager.cleanup()
            Log.d("MainActivity", "应用停止时清理数据管理器")
        } catch (e: Exception) {
            Log.e("MainActivity", "应用停止时清理数据管理器失败: ${e.message}", e)
        }
    }

    // 原生方法声明 - 保持原来的JNI函数名
    override external fun createStreamParser(): Long
    override external fun destroyStreamParser(handle: Long)
    override external fun streamParserAppend(handle: Long, chunk: ByteArray)
    override external fun streamParserDrainPackets(handle: Long): List<SensorData>?



    
    /**
     * 获取原始通道数据
     */
    private fun getRawChannelData(channelIndex: Int): List<Float> {
        val data = mutableListOf<Float>()
        try {
            // 从原始数据包中提取指定通道的数据
            val packets = dataManager.getPacketBuffer()
            for (packet in packets) {
                val channelData = packet.getChannelData()
                if (channelData != null && channelIndex < channelData.size) {
                    data.addAll(channelData[channelIndex])
                }
            }
        } catch (e: Exception) {
            Log.e("MainActivity", "获取原始通道数据失败: ${e.message}", e)
        }
        return data
    }
    
    /**
     * 获取处理后的通道数据（滤波后的数据）
     */
    private fun getProcessedChannelData(channelIndex: Int): List<Float> {
        try {
            // 直接从DataManager获取滤波后的数据
            return dataManager.getProcessedChannelData(channelIndex)
        } catch (e: Exception) {
            Log.e("MainActivity", "获取处理后通道数据失败: ${e.message}", e)
            return emptyList()
        }
    }
    
    // 实时数据回调实现
    override fun onProcessedDataAvailable(channelIndex: Int, processedData: List<Float>) {
        // 限制图表更新频率，避免过多更新导致卡顿
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastChartUpdateTime < 100) { // 100ms内不重复更新图表
            return
        }
        lastChartUpdateTime = currentTime
        
        // 立即显示处理后的数据到图表
        runOnUiThread {
            try {
                Log.d("MainActivity", "收到处理后数据回调，通道: $channelIndex，数据长度: ${processedData.size}")
                
                // 确保图表容器可见
                binding.ecgChartContainer.visibility = View.VISIBLE
                
                // 立即更新图表数据
                binding.ecgRhythmView.updateData(processedData)
                binding.ecgWaveformView.updateData(processedData)
                
                Log.d("MainActivity", "已立即更新处理后数据图表，通道: $channelIndex，数据长度: ${processedData.size}")
                
                // 减少状态更新频率
                if (currentTime - lastChartStatusTime > 2000) { // 2秒内只更新一次状态
                    updateStatus("实时处理后图表已更新，通道: $channelIndex，数据点: ${processedData.size}")
                    lastChartStatusTime = currentTime
                }
                
            } catch (e: Exception) {
                Log.e("MainActivity", "显示处理后数据失败: ${e.message}", e)
            }
        }
    }
    
    override fun onRawDataAvailable(channelIndex: Int, rawData: List<Float>) {
        // 限制图表更新频率，避免过多更新导致卡顿
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastChartUpdateTime < 100) { // 100ms内不重复更新图表
            return
        }
        lastChartUpdateTime = currentTime
        
        // 立即显示原始数据到图表
        runOnUiThread {
            try {
                Log.d("MainActivity", "收到原始数据回调，通道: $channelIndex，数据长度: ${rawData.size}")
                if (rawData.isNotEmpty()) {
                    Log.d("MainActivity", "原始数据前3个值: ${rawData.take(3).joinToString(", ")}")
                }
                
                // 确保图表容器可见
                binding.ecgChartContainer.visibility = View.VISIBLE
                
                // 立即更新图表数据
                binding.ecgRhythmView.updateData(rawData)
                binding.ecgWaveformView.updateData(rawData)
                
                Log.d("MainActivity", "已立即更新原始数据图表，通道: $channelIndex，数据长度: ${rawData.size}")
                
                // 减少状态更新频率
                if (currentTime - lastChartStatusTime > 2000) { // 2秒内只更新一次状态
                    updateStatus("实时图表已更新，通道: $channelIndex，数据点: ${rawData.size}")
                    lastChartStatusTime = currentTime
                }
                
            } catch (e: Exception) {
                Log.e("MainActivity", "显示原始数据失败: ${e.message}", e)
            }
        }
    }
    
    override fun onStreamingProgress(progress: Int, totalSamples: Int, processedSamples: Int) {
        // 实时流式处理不需要显示进度条，只记录日志
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastProgressUpdateTime < 2000) { // 2秒内只记录一次
            return
        }
        lastProgressUpdateTime = currentTime
        
        Log.d("MainActivity", "实时流式处理状态: 总样本=$totalSamples, 已处理=$processedSamples")
    }

    private fun stopDataProcessing() {
        // 重置数据处理状态
        dataProcessingStarted = false
        
        // 启用启动按钮，禁用停止按钮和陷波滤波器按钮
        binding.startButton.isEnabled = true
        binding.stopButton.isEnabled = false
        binding.notchFilterButton.isEnabled = false

        // 更新UI状态
        binding.sampleText.text = "程序已停止\n\n点击\"启动程序\"按钮重新开始..."

        // 清理数据管理器
        try {
            dataManager.cleanup()
            Log.d("MainActivity", "数据管理器清理完成")
        } catch (e: Exception) {
            Log.e("MainActivity", "清理数据管理器失败: ${e.message}", e)
        }

        // 清空ECG双视图数据
        binding.ecgRhythmView.clearData()
        binding.ecgWaveformView.clearData()
    }

    // 蓝牙回调方法
    override fun onDeviceFound(device: BluetoothDevice) {
        // 减少设备发现提示频率，避免过多日志
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastDeviceFoundTime > 2000) { // 2秒内只显示一次设备发现
            runOnUiThread {
                updateStatus("发现设备: ${device.name ?: device.address}")
            }
            lastDeviceFoundTime = currentTime
        }
    }

    override fun onConnected(device: BluetoothDevice) {
        runOnUiThread {
            bluetoothConnected = true
            binding.bluetoothButton.text = "断开蓝牙"
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#F44336"))
            
            // 显示明显的连接成功提示
            val deviceName = device.name ?: device.address
            updateStatus("✅ 设备已连接: $deviceName")
            updateStatus("🎉 连接成功！设备信息:")
            updateStatus("   设备名称: ${device.name ?: "未知"}")
            updateStatus("   设备地址: ${device.address}")
            updateStatus("   设备类型: ${device.type}")
            updateStatus("📡 数据通道已建立，可以开始收发数据")
            
            // 启用发送指令按钮
            binding.sendCommandButton.isEnabled = true
            binding.sendCommandButton.setBackgroundColor(Color.parseColor("#2196F3"))
            
            // 显示ECG图表容器
            binding.ecgChartContainer.visibility = View.VISIBLE
            updateStatus("📊 ECG图表已准备就绪，请点击'发送指令'按钮开始接收数据")
        }
    }

    override fun onDisconnected() {
        runOnUiThread {
            bluetoothConnected = false
            binding.bluetoothButton.text = "连接蓝牙"
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#4CAF50"))
            
            // 禁用发送指令按钮
            binding.sendCommandButton.isEnabled = false
            binding.sendCommandButton.setBackgroundColor(Color.parseColor("#9E9E9E"))
            
            // 禁用停止按钮
            binding.stopButton.isEnabled = false
            binding.stopButton.setBackgroundColor(Color.parseColor("#9E9E9E"))
            
            updateStatus("❌ 蓝牙设备已断开连接")
            updateStatus("💡 可能原因：")
            updateStatus("   • 设备超出蓝牙范围")
            updateStatus("   • 电脑蓝牙被关闭")
            updateStatus("   • 连接超时")
            updateStatus("   • 系统蓝牙服务异常")
            updateStatus("🔄 如需重新连接，请点击'连接蓝牙'按钮")
        }
    }

    override fun onDataReceived(data: ByteArray) {
        Log.d("MainActivity", "=== 蓝牙数据接收开始 ===")
        Log.d("MainActivity", "接收到蓝牙数据: ${data.size} 字节")
        if (data.isNotEmpty()) {
            Log.d("MainActivity", "数据前10字节: ${data.take(10).joinToString(", ") { "0x%02X".format(it) }}")
        }
        
        // 更新数据统计
        receivedDataCount += data.size
        val currentTime = System.currentTimeMillis()
        if (lastDataTime > 0) {
            val timeDiff = currentTime - lastDataTime
            if (timeDiff > 0) {
                dataRate = (data.size * 1000f) / timeDiff // 字节/秒
            }
        }
        lastDataTime = currentTime
        
        // 减少数据日志记录频率，避免过多日志
        if (currentTime - lastDataLogTime > 1000) { // 1秒内只记录一次
            addDataLog("📥 接收数据", data)
            lastDataLogTime = currentTime
        }
        
        // 立即显示ECG图表容器
        runOnUiThread {
            binding.ecgChartContainer.visibility = View.VISIBLE
            
            // 如果数据处理还没启动，自动启动
            if (!dataProcessingStarted) {
                startDataProcessing()
                updateStatus("检测到数据，自动启动数据处理")
            }
            
            // 减少数据接收状态更新频率
            if (currentTime - lastDataStatusTime > 2000) { // 2秒内只更新一次状态
                updateStatus("接收到蓝牙数据: ${data.size} 字节，图表已显示")
                updateDataStatistics()
                lastDataStatusTime = currentTime
            }
        }
        
        // 在后台线程处理数据，避免阻塞UI
        Thread {
            try {
                Log.d("MainActivity", "开始处理蓝牙数据: ${data.size} 字节")
                
                // 将蓝牙数据传递给DataManager处理
                dataManager.onBleNotify(data)
                
                Log.d("MainActivity", "蓝牙数据处理完成")
                
                // 如果DataManager没有解析出数据，立即生成测试数据
                if (dataManager.getPacketBufferSize() == 0) {
                    Log.d("MainActivity", "DataManager没有解析出数据包，立即生成测试数据")
                    generateImmediateTestData()
                }
                
            } catch (e: Exception) {
                Log.e("MainActivity", "处理蓝牙数据失败: ${e.message}", e)
                runOnUiThread {
                    updateStatus("处理蓝牙数据失败: ${e.message}")
                }
            }
        }.start()
    }
    
    /**
     * 添加数据日志
     */
    private fun addDataLog(action: String, data: ByteArray) {
        val timestamp = java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.getDefault()).format(java.util.Date())
        val hexData = data.take(16).joinToString(" ") { "0x%02X".format(it) }
        val logEntry = "[$timestamp] $action: ${data.size}字节 ${if (data.size > 16) "..." else ""} $hexData\n"
        
        synchronized(dataLogBuffer) {
            dataLogBuffer.append(logEntry)
            // 限制日志长度，保留最新的1000行
            val lines = dataLogBuffer.split("\n")
            if (lines.size > 1000) {
                dataLogBuffer.clear()
                dataLogBuffer.append(lines.takeLast(1000).joinToString("\n"))
            }
        }
    }
    
    /**
     * 更新数据统计显示
     */
    private fun updateDataStatistics() {
        val stats = """
            📊 数据统计:
            接收数据: ${receivedDataCount} 字节
            发送数据: ${sentDataCount} 字节
            数据速率: ${String.format("%.1f", dataRate)} 字节/秒
            连接状态: ${if (bluetoothConnected) "已连接" else "未连接"}
        """.trimIndent()
        
        // 更新状态显示
        binding.sampleText.text = stats
    }
    
    /**
     * 显示数据日志对话框
     */
    private fun showDataLogDialog() {
        val logContent = synchronized(dataLogBuffer) { dataLogBuffer.toString() }
        
        val dialog = androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("📋 数据收发日志")
            .setMessage(logContent.ifEmpty { "暂无数据记录" })
            .setPositiveButton("清空日志") { _, _ ->
                synchronized(dataLogBuffer) { dataLogBuffer.clear() }
                updateStatus("数据日志已清空")
            }
            .setNegativeButton("关闭", null)
            .setNeutralButton("导出日志") { _, _ ->
                exportDataLog()
            }
            .create()
        
        // 设置对话框可滚动
        dialog.setOnShowListener {
            val messageView = dialog.findViewById<android.widget.TextView>(android.R.id.message)
            messageView?.let {
                it.isScrollContainer = true
                it.maxLines = 20
                it.isVerticalScrollBarEnabled = true
            }
        }
        
        dialog.show()
    }
    
    /**
     * 导出数据日志
     */
    private fun exportDataLog() {
        try {
            val timestamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.getDefault()).format(java.util.Date())
            val fileName = "bluetooth_data_log_$timestamp.txt"
            val logContent = synchronized(dataLogBuffer) { dataLogBuffer.toString() }
            
            // 创建文件
            val file = java.io.File(getExternalFilesDir(null), fileName)
            file.writeText(logContent)
            
            updateStatus("数据日志已导出到: ${file.absolutePath}")
            
        } catch (e: Exception) {
            updateStatus("导出日志失败: ${e.message}")
        }
    }
    
    /**
     * 显示调试信息对话框
     */
    private fun showDebugInfoDialog() {
        val debugInfo = """
            🔧 调试信息:
            
            📱 设备信息:
            Android版本: ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})
            设备型号: ${Build.MODEL}
            制造商: ${Build.MANUFACTURER}
            
            📊 应用状态:
            蓝牙连接: ${if (bluetoothConnected) "已连接" else "未连接"}
            数据处理: ${if (dataProcessingStarted) "已启动" else "未启动"}
            数据监控: ${if (isDataMonitoringEnabled) "已启用" else "已禁用"}
            
            📈 数据统计:
            接收数据: ${receivedDataCount} 字节
            发送数据: ${sentDataCount} 字节
            数据速率: ${String.format("%.1f", dataRate)} 字节/秒
            最后数据时间: ${if (lastDataTime > 0) java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.getDefault()).format(java.util.Date(lastDataTime)) else "无"}
            
            🔐 权限状态:
            ${checkPermissionStatus()}
        """.trimIndent()
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("🔧 调试信息")
            .setMessage(debugInfo)
            .setPositiveButton("复制信息") { _, _ ->
                copyToClipboard(debugInfo)
                updateStatus("调试信息已复制到剪贴板")
            }
            .setNegativeButton("关闭", null)
            .show()
    }
    
    /**
     * 复制文本到剪贴板
     */
    private fun copyToClipboard(text: String) {
        val clipboard = getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
        val clip = android.content.ClipData.newPlainText("调试信息", text)
        clipboard.setPrimaryClip(clip)
    }
    
    /**
     * 立即生成测试数据
     */
    private fun generateImmediateTestData() {
        try {
            Log.d("MainActivity", "立即生成测试数据用于验证图表显示")
            
            // 生成模拟的单导联ECG数据 - 更明显的波形
            val testData = mutableListOf<Float>()
            val sampleCount = 500 // 生成500个样本点
            
            for (i in 0 until sampleCount) {
                val t = i.toFloat() / 50f // 时间参数
                
                // 生成更明显的ECG样波形
                val pWave = Math.sin(t * 2 * Math.PI) * 50
                val qrsComplex = Math.sin(t * 8 * Math.PI) * 200 * Math.exp(-(t % 1.0) * 10.0)
                val tWave = Math.sin(t * 2 * Math.PI + Math.PI/4) * 80
                val baseline = Math.sin(t * 0.5 * Math.PI) * 20
                
                val value = (pWave + qrsComplex + tWave + baseline + 
                           Math.random() * 10 - 5).toFloat() // 添加少量噪声
                testData.add(value)
            }
            
            Log.d("MainActivity", "生成测试数据: ${testData.size} 个样本点")
            Log.d("MainActivity", "测试数据前5个值: ${testData.take(5).joinToString(", ")}")
            
            // 确保图表容器可见
            binding.ecgChartContainer.visibility = View.VISIBLE
            
            // 直接调用数据回调
            onRawDataAvailable(0, testData)
            
            Log.d("MainActivity", "测试数据已发送到图表")
            
        } catch (e: Exception) {
            Log.e("MainActivity", "生成测试数据失败: ${e.message}", e)
        }
    }

    override fun onError(message: String) {
        runOnUiThread {
            updateStatus("蓝牙错误: $message")
            binding.bluetoothButton.text = "连接蓝牙"
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#4CAF50"))
        }
    }

    override fun onStatusChanged(status: String) {
        runOnUiThread {
            updateStatus("蓝牙状态: $status")
            
            // 当数据通道建立时，确保图表显示
            if (status.contains("数据通道已建立")) {
                binding.ecgChartContainer.visibility = View.VISIBLE
                updateStatus("ECG图表已激活，请点击'发送指令'按钮开始接收数据")
            }
        }
    }
    
    override fun onCommandSent(success: Boolean, message: String) {
        runOnUiThread {
            if (success) {
                updateStatus("指令发送成功: $message")
                
                // 更新发送数据统计（这里我们假设每次发送的数据量）
                sentDataCount += 10 // 假设每次发送10字节
                updateDataStatistics()
                
                // 指令发送成功后，可以启用停止按钮
                binding.stopButton.isEnabled = true
                binding.stopButton.setBackgroundColor(Color.parseColor("#FF9800"))
                
                // 自动启动数据处理，等待接收数据
                if (!dataProcessingStarted) {
                    startDataProcessing()
                    updateStatus("已自动启动数据处理，等待接收数据...")
                }
            } else {
                updateStatus("指令发送失败: $message")
            }
        }
    }

    override fun onScanComplete(devices: List<BluetoothDevice>) {
        runOnUiThread {
            updateStatus("扫描完成，找到 ${devices.size} 个设备")
            
            if (devices.isNotEmpty()) {
                // 立即显示设备选择对话框
                val dialog = BluetoothDeviceDialog.newInstance(devices)
                dialog.setOnDeviceSelectedListener { device ->
                    // 连接选中的设备
                    bluetoothManager.connectToDevice(device)
                    binding.bluetoothButton.text = "连接中..."
                    binding.bluetoothButton.setBackgroundColor(Color.parseColor("#FF9800"))
                    updateStatus("正在连接设备: ${device.name ?: device.address}")
                }
                dialog.show(supportFragmentManager, "BluetoothDeviceDialog")
            } else {
                updateStatus("未找到蓝牙设备，请重试")
                binding.bluetoothButton.text = "连接蓝牙"
                binding.bluetoothButton.setBackgroundColor(Color.parseColor("#4CAF50"))
            }
        }
    }

    private fun updateStatus(message: String) {
        val currentText = binding.sampleText.text.toString()
        val timestamp = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())
        val newStatus = "[$timestamp] $message"
        
        // 限制状态更新频率，避免过多提示导致卡顿
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastStatusUpdateTime < 500) { // 500ms内不重复更新
            return
        }
        lastStatusUpdateTime = currentTime
        
        // 保持最新的状态信息在顶部，但限制显示行数
        val lines = currentText.split("\n").toMutableList()
        if (lines.size > 15) { // 减少到15行，提高性能
            lines.removeAt(0)
        }
        lines.add(newStatus)
        
        binding.sampleText.text = lines.joinToString("\n")
        
        // 减少日志输出频率
        if (currentTime - lastLogTime > 1000) { // 1秒内只输出一次日志
            Log.d("MainActivity", "状态更新: $message")
            lastLogTime = currentTime
        }
    }
    
    /**
     * 发送数据指令
     */
    private fun sendDataCommand() {
        if (!bluetoothConnected) {
            updateStatus("蓝牙未连接，无法发送指令")
            return
        }
        
        // 显示指令选择对话框
        showCommandDialog()
    }
    
    /**
     * 显示指令选择对话框
     */
    private fun showCommandDialog() {
        val commands = arrayOf(
            "轻迅协议指令",
            "通用指令",
            "自定义指令"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("选择指令类型")
            .setItems(commands) { _, which ->
                when (which) {
                    0 -> showQingXunProtocolDialog()
                    1 -> showGeneralCommandDialog()
                    2 -> showCustomCommandDialog()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示轻迅协议指令对话框
     */
    private fun showQingXunProtocolDialog() {
        val commands = arrayOf(
            "开启采集",
            "停止采集",
            "查询设备信息",
            "查询电量",
            "工频滤波开关"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("轻迅协议指令")
            .setItems(commands) { _, which ->
                when (which) {
                    0 -> sendQingXunStartCollection()
                    1 -> sendQingXunStopCollection()
                    2 -> bluetoothManager.queryDeviceInfo()
                    3 -> bluetoothManager.queryBattery()
                    4 -> showPowerLineFilterDialog()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示通用指令对话框
     */
    private fun showGeneralCommandDialog() {
        val commands = arrayOf(
            "开始发送数据",
            "停止发送数据", 
            "开始ECG测量",
            "停止ECG测量"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("通用指令")
            .setItems(commands) { _, which ->
                when (which) {
                    0 -> sendStartDataCommand()
                    1 -> sendStopDataCommand()
                    2 -> sendStartECGCommand()
                    3 -> sendStopECGCommand()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 发送轻迅协议开启采集指令
     */
    private fun sendQingXunStartCollection() {
        val options = arrayOf(
            "立即开启",
            "延迟开启（5秒后）",
            "指定时间戳开启"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("开启采集")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> {
                        bluetoothManager.startCollection(0L) // 立即开启
                        updateStatus("发送轻迅协议开启采集指令（立即），准备接收数据...")
                    }
                    1 -> {
                        val timestamp = System.currentTimeMillis() + 5000 // 5秒后
                        bluetoothManager.startCollection(timestamp)
                        updateStatus("发送轻迅协议开启采集指令（5秒后），准备接收数据...")
                    }
                    2 -> {
                        showTimestampInputDialog { timestamp ->
                            bluetoothManager.startCollection(timestamp)
                            updateStatus("发送轻迅协议开启采集指令（指定时间戳: $timestamp），准备接收数据...")
                        }
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 发送轻迅协议停止采集指令
     */
    private fun sendQingXunStopCollection() {
        val options = arrayOf(
            "立即停止",
            "延迟停止（5秒后）",
            "指定时间戳停止"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("停止采集")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> {
                        bluetoothManager.stopCollection(0L) // 立即停止
                        updateStatus("发送轻迅协议停止采集指令（立即）")
                    }
                    1 -> {
                        val timestamp = System.currentTimeMillis() + 5000 // 5秒后
                        bluetoothManager.stopCollection(timestamp)
                        updateStatus("发送轻迅协议停止采集指令（5秒后）")
                    }
                    2 -> {
                        showTimestampInputDialog { timestamp ->
                            bluetoothManager.stopCollection(timestamp)
                            updateStatus("发送轻迅协议停止采集指令（指定时间戳: $timestamp）")
                        }
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示工频滤波开关对话框
     */
    private fun showPowerLineFilterDialog() {
        val options = arrayOf(
            "开启工频滤波",
            "关闭工频滤波"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("工频滤波开关")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> {
                        bluetoothManager.togglePowerLineFilter(true)
                        updateStatus("发送开启工频滤波指令")
                    }
                    1 -> {
                        bluetoothManager.togglePowerLineFilter(false)
                        updateStatus("发送关闭工频滤波指令")
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示时间戳输入对话框
     */
    private fun showTimestampInputDialog(onConfirm: (Long) -> Unit) {
        val input = android.widget.EditText(this)
        input.hint = "输入时间戳（毫秒，0表示立即执行）"
        input.setText("0")
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("输入时间戳")
            .setView(input)
            .setPositiveButton("确定") { _, _ ->
                try {
                    val timestamp = input.text.toString().toLong()
                    onConfirm(timestamp)
                } catch (e: NumberFormatException) {
                    updateStatus("时间戳格式错误，请输入数字")
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示轻迅协议命令菜单
     */
    private fun showQingXunProtocolMenu() {
        val options = arrayOf(
            "查询设备信息",
            "开启采集",
            "停止采集", 
            "查询电量",
            "设置采样率",
            "设置增益",
            "设置导联",
            "工频滤波开关",
            "查询状态",
            "设备复位",
            "查看协议统计"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("轻迅协议V1.0.1命令")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> {
                        bluetoothManager.queryDeviceInfo()
                        updateStatus("发送查询设备信息指令")
                    }
                    1 -> sendQingXunStartCollection()
                    2 -> sendQingXunStopCollection()
                    3 -> {
                        bluetoothManager.queryBattery()
                        updateStatus("发送查询电量指令")
                    }
                    4 -> showSampleRateDialog()
                    5 -> showGainDialog()
                    6 -> showLeadDialog()
                    7 -> showPowerLineFilterDialog()
                    8 -> {
                        bluetoothManager.queryStatus()
                        updateStatus("发送查询状态指令")
                    }
                    9 -> {
                        bluetoothManager.resetDevice()
                        updateStatus("发送设备复位指令")
                    }
                    10 -> showProtocolStats()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示采样率设置对话框
     */
    private fun showSampleRateDialog() {
        val options = arrayOf(
            "125 Hz",
            "250 Hz", 
            "500 Hz",
            "1000 Hz",
            "2000 Hz",
            "自定义"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("设置采样率")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> bluetoothManager.setSampleRate(125)
                    1 -> bluetoothManager.setSampleRate(250)
                    2 -> bluetoothManager.setSampleRate(500)
                    3 -> bluetoothManager.setSampleRate(1000)
                    4 -> bluetoothManager.setSampleRate(2000)
                    5 -> showCustomSampleRateDialog()
                }
                updateStatus("发送设置采样率指令")
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示自定义采样率对话框
     */
    private fun showCustomSampleRateDialog() {
        val input = android.widget.EditText(this)
        input.hint = "输入采样率 (Hz)"
        input.setText("500")
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("自定义采样率")
            .setView(input)
            .setPositiveButton("确定") { _, _ ->
                try {
                    val sampleRate = input.text.toString().toInt()
                    if (sampleRate > 0 && sampleRate <= 10000) {
                        bluetoothManager.setSampleRate(sampleRate)
                        updateStatus("发送设置采样率指令: ${sampleRate} Hz")
                    } else {
                        updateStatus("采样率范围错误，请输入1-10000之间的数字")
                    }
                } catch (e: NumberFormatException) {
                    updateStatus("采样率格式错误，请输入数字")
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示增益设置对话框
     */
    private fun showGainDialog() {
        val options = arrayOf(
            "1x",
            "2x",
            "4x",
            "8x",
            "16x",
            "32x",
            "自定义"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("设置增益")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> bluetoothManager.setGain(1)
                    1 -> bluetoothManager.setGain(2)
                    2 -> bluetoothManager.setGain(4)
                    3 -> bluetoothManager.setGain(8)
                    4 -> bluetoothManager.setGain(16)
                    5 -> bluetoothManager.setGain(32)
                    6 -> showCustomGainDialog()
                }
                updateStatus("发送设置增益指令")
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示自定义增益对话框
     */
    private fun showCustomGainDialog() {
        val input = android.widget.EditText(this)
        input.hint = "输入增益倍数"
        input.setText("1")
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("自定义增益")
            .setView(input)
            .setPositiveButton("确定") { _, _ ->
                try {
                    val gain = input.text.toString().toInt()
                    if (gain > 0 && gain <= 100) {
                        bluetoothManager.setGain(gain)
                        updateStatus("发送设置增益指令: ${gain}x")
                    } else {
                        updateStatus("增益范围错误，请输入1-100之间的数字")
                    }
                } catch (e: NumberFormatException) {
                    updateStatus("增益格式错误，请输入数字")
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示导联设置对话框
     */
    private fun showLeadDialog() {
        val options = arrayOf(
            "I导联",
            "II导联", 
            "III导联",
            "aVR导联",
            "aVL导联",
            "aVF导联",
            "V1导联",
            "V2导联",
            "V3导联",
            "V4导联",
            "V5导联",
            "V6导联"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("设置导联")
            .setItems(options) { _, which ->
                val lead = which + 1 // 导联编号从1开始
                bluetoothManager.setLead(lead)
                updateStatus("发送设置导联指令: ${options[which]}")
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示协议统计信息
     */
    private fun showProtocolStats() {
        val stats = bluetoothManager.getProtocolStats()
        val statsText = buildString {
            appendLine("=== 轻迅协议统计信息 ===")
            appendLine("发送数据包: ${stats["totalPacketsSent"]}")
            appendLine("发送字节数: ${stats["totalBytesSent"]}")
            appendLine("接收数据包: ${stats["totalPacketsReceived"]}")
            appendLine("接收字节数: ${stats["totalBytesReceived"]}")
            appendLine("采集状态: ${if (stats["isCollecting"] as Boolean) "开启" else "关闭"}")
            appendLine("当前采样率: ${stats["currentSampleRate"]} Hz")
            appendLine("当前增益: ${stats["currentGain"]}x")
            appendLine("当前导联: ${stats["currentLead"]}")
            appendLine("工频滤波: ${if (stats["powerLineFilterEnabled"] as Boolean) "开启" else "关闭"}")
            
            val deviceInfo = stats["deviceInfo"] as? com.example.cmake_project_test.BluetoothManager.DeviceInfo
            if (deviceInfo != null) {
                appendLine("设备信息:")
                appendLine("  制造商: ${deviceInfo.manufacturer}")
                appendLine("  型号: ${deviceInfo.model}")
                appendLine("  固件版本: ${deviceInfo.firmwareVersion}")
                appendLine("  硬件版本: ${deviceInfo.hardwareVersion}")
                appendLine("  序列号: ${deviceInfo.serialNumber}")
            }
        }
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("协议统计信息")
            .setMessage(statsText)
            .setPositiveButton("复制到剪贴板") { _, _ ->
                copyToClipboard(statsText)
                updateStatus("协议统计信息已复制到剪贴板")
            }
            .setNegativeButton("关闭", null)
            .show()
    }
    private fun sendStartDataCommand() {
        // 常见的开始数据指令
        val commands = arrayOf(
            "START_DATA",
            "START",
            "BEGIN",
            "0x01",
            "0x53 0x54 0x41 0x52 0x54" // START的ASCII码
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("选择开始指令")
            .setItems(commands) { _, which ->
                val command = commands[which]
                if (command.startsWith("0x")) {
                    bluetoothManager.sendHexCommand(command)
                } else {
                    bluetoothManager.sendStringCommand(command)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 发送停止数据指令
     */
    private fun sendStopDataCommand() {
        val commands = arrayOf(
            "STOP_DATA",
            "STOP",
            "END",
            "0x02",
            "0x53 0x54 0x4F 0x50" // STOP的ASCII码
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("选择停止指令")
            .setItems(commands) { _, which ->
                val command = commands[which]
                if (command.startsWith("0x")) {
                    bluetoothManager.sendHexCommand(command)
                } else {
                    bluetoothManager.sendStringCommand(command)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 发送开始ECG指令
     */
    private fun sendStartECGCommand() {
        val commands = arrayOf(
            "START_ECG",
            "ECG_START",
            "0x03",
            "0x45 0x43 0x47 0x53" // ECGS的ASCII码
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("选择ECG开始指令")
            .setItems(commands) { _, which ->
                val command = commands[which]
                if (command.startsWith("0x")) {
                    bluetoothManager.sendHexCommand(command)
                } else {
                    bluetoothManager.sendStringCommand(command)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 发送停止ECG指令
     */
    private fun sendStopECGCommand() {
        val commands = arrayOf(
            "STOP_ECG",
            "ECG_STOP",
            "0x04",
            "0x45 0x43 0x47 0x45" // ECGE的ASCII码
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("选择ECG停止指令")
            .setItems(commands) { _, which ->
                val command = commands[which]
                if (command.startsWith("0x")) {
                    bluetoothManager.sendHexCommand(command)
                } else {
                    bluetoothManager.sendStringCommand(command)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示自定义指令对话框
     */
    private fun showCustomCommandDialog() {
        val input = android.widget.EditText(this)
        input.hint = "输入指令（字符串或十六进制，如：0x01 0x02）"
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("自定义指令")
            .setView(input)
            .setPositiveButton("发送") { _, _ ->
                val command = input.text.toString().trim()
                if (command.isNotEmpty()) {
                    if (command.startsWith("0x")) {
                        bluetoothManager.sendHexCommand(command)
                    } else {
                        bluetoothManager.sendStringCommand(command)
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 清空所有数据
     */
    private fun clearAllData() {
        // 清空图表数据
        binding.ecgRhythmView.clearData()
        binding.ecgWaveformView.clearData()
        
        // 清空数据管理器
        dataManager.cleanupBuffer()
        
        updateStatus("已清空所有数据")
    }
    
    /**
     * 测试图表显示功能
     */
    private fun testChartDisplay() {
        Log.d("MainActivity", "开始测试图表显示功能")
        
        // 确保图表容器可见
        binding.ecgChartContainer.visibility = View.VISIBLE
        
        // 生成测试数据 - 模拟ECG信号
        val testData = mutableListOf<Float>()
        for (i in 0 until 1000) {
            // 生成一个更真实的ECG波形：基线 + P波 + QRS复合波 + T波
            val t = i * 0.01 // 时间
            val baseline = 0.0
            val pWave = 20.0 * Math.exp(-((t % 1.0 - 0.2) * 10) * ((t % 1.0 - 0.2) * 10))
            val qrsComplex = 80.0 * Math.exp(-((t % 1.0 - 0.5) * 20) * ((t % 1.0 - 0.5) * 20))
            val tWave = 30.0 * Math.exp(-((t % 1.0 - 0.7) * 8) * ((t % 1.0 - 0.7) * 8))
            
            val value = (baseline + pWave + qrsComplex + tWave + (Math.random() * 5 - 2.5)).toFloat()
            testData.add(value)
        }
        
        // 更新图表
        binding.ecgRhythmView.updateData(testData)
        binding.ecgWaveformView.updateData(testData)
        
        updateStatus("图表测试完成，已显示ECG模拟数据")
        Log.d("MainActivity", "图表测试完成，数据点: ${testData.size}")
    }
    
    /**
     * 显示调试状态对话框
     */
    private fun showDebugStatusDialog() {
        val debugInfo = bluetoothManager.debugConnectionStatus()
        
        android.app.AlertDialog.Builder(this)
            .setTitle("🔍 连接状态调试")
            .setMessage(debugInfo)
            .setPositiveButton("复制到剪贴板") { dialog, _ ->
                copyToClipboard(debugInfo)
                updateStatus("调试信息已复制到剪贴板")
                dialog.dismiss()
            }
            .setNegativeButton("关闭") { dialog, _ -> 
                dialog.dismiss()
            }
            .show()
    }
    private fun showDirectConnectDialog() {
        val input = android.widget.EditText(this)
        input.hint = "输入MAC地址（如：A4:C3:37:86:9F:73）"
        input.setText("A4:C3:37:86:9F:73") // 使用新的手机MAC地址
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("直接连接测试")
            .setMessage("输入要连接的设备MAC地址\n\n注意：请使用冒号(:)分隔符，如：A4:C3:37:86:9F:73")
            .setView(input)
            .setPositiveButton("连接") { _, _ ->
                val macAddress = input.text.toString().trim()
                if (macAddress.isNotEmpty()) {
                    // 检查权限
                    if (checkAndRequestPermissions()) {
                        // 验证MAC地址格式
                        if (isValidMacAddress(macAddress)) {
                            bluetoothManager.connectToMacAddress(macAddress)
                            binding.bluetoothButton.text = "连接中..."
                            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#FF9800"))
                            updateStatus("正在直接连接设备: $macAddress")
                        } else {
                            updateStatus("MAC地址格式错误，请使用格式：A4:C3:37:86:9F:73")
                        }
                    }
                } else {
                    updateStatus("请输入有效的MAC地址")
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 验证MAC地址格式
     */
    private fun isValidMacAddress(macAddress: String): Boolean {
        // 支持多种格式：60:E9:AA:30:8B:0A 或 60-E9-AA-30-8B-0A
        val pattern = Regex("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$")
        return pattern.matches(macAddress)
    }
    
    /**
     * 显示调试菜单对话框
     */
    private fun showDebugMenuDialog() {
        val debugOptions = arrayOf(
            "📋 查看数据日志",
            "🔧 调试信息",
            "📊 数据统计",
            "🔄 重置统计",
            "📤 导出日志",
            "🧪 生成测试数据"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("🔧 调试菜单")
            .setItems(debugOptions) { _, which ->
                when (which) {
                    0 -> showDataLogDialog()
                    1 -> showDebugInfoDialog()
                    2 -> showDataStatisticsDialog()
                    3 -> resetDataStatistics()
                    4 -> exportDataLog()
                    5 -> generateImmediateTestData()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示数据统计对话框
     */
    private fun showDataStatisticsDialog() {
        val stats = """
            📊 详细数据统计:
            
            📥 接收数据:
            总字节数: ${receivedDataCount} 字节
            数据包数: ${receivedDataCount / 20} 包 (假设每包20字节)
            
            📤 发送数据:
            总字节数: ${sentDataCount} 字节
            指令数: ${sentDataCount / 10} 条 (假设每条10字节)
            
            📈 实时统计:
            数据速率: ${String.format("%.1f", dataRate)} 字节/秒
            最后数据: ${if (lastDataTime > 0) java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.getDefault()).format(java.util.Date(lastDataTime)) else "无"}
            
            🔄 连接状态:
            蓝牙连接: ${if (bluetoothConnected) "已连接" else "未连接"}
            数据处理: ${if (dataProcessingStarted) "已启动" else "未启动"}
            数据监控: ${if (isDataMonitoringEnabled) "已启用" else "已禁用"}
        """.trimIndent()
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("📊 数据统计")
            .setMessage(stats)
            .setPositiveButton("复制统计", { _, _ ->
                copyToClipboard(stats)
                updateStatus("数据统计已复制到剪贴板")
            })
            .setNegativeButton("关闭", null)
            .show()
    }
    
    /**
     * 重置数据统计
     */
    private fun resetDataStatistics() {
        receivedDataCount = 0
        sentDataCount = 0
        lastDataTime = 0L
        dataRate = 0f
        synchronized(dataLogBuffer) { dataLogBuffer.clear() }
        
        updateStatus("数据统计已重置")
        updateDataStatistics()
    }
    
    /**
     * 显示测试数据对话框
     */
    private fun showTestDataDialog() {
        val options = arrayOf(
            "发送ECG测试数据",
            "发送心跳包",
            "发送设备信息查询",
            "发送自定义测试数据"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("测试数据发送")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> sendECGTestData()
                    1 -> sendHeartbeatData()
                    2 -> sendDeviceInfoQuery()
                    3 -> sendCustomTestData()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 发送ECG测试数据
     */
    private fun sendECGTestData() {
        // 生成模拟ECG数据包
        val ecgData = generateECGTestPacket()
        bluetoothManager.sendCommand(ecgData)
        updateStatus("已发送ECG测试数据包")
    }
    
    /**
     * 发送心跳包
     */
    private fun sendHeartbeatData() {
        val heartbeat = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05)
        bluetoothManager.sendCommand(heartbeat)
        updateStatus("已发送心跳包")
    }
    
    /**
     * 发送设备信息查询
     */
    private fun sendDeviceInfoQuery() {
        val deviceInfoQuery = "DEVICE_INFO".toByteArray()
        bluetoothManager.sendCommand(deviceInfoQuery)
        updateStatus("已发送设备信息查询")
    }
    
    /**
     * 发送自定义测试数据
     */
    private fun sendCustomTestData() {
        val input = android.widget.EditText(this)
        input.hint = "输入测试数据（十六进制，如：01 02 03 04）"
        input.setText("01 02 03 04 05")
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("自定义测试数据")
            .setView(input)
            .setPositiveButton("发送") { _, _ ->
                val dataString = input.text.toString().trim()
                if (dataString.isNotEmpty()) {
                    try {
                        val data = dataString.split(" ").map { it.toInt(16).toByte() }.toByteArray()
                        bluetoothManager.sendCommand(data)
                        updateStatus("已发送自定义测试数据: $dataString")
                    } catch (e: Exception) {
                        updateStatus("数据格式错误: ${e.message}")
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 生成ECG测试数据包
     */
    private fun generateECGTestPacket(): ByteArray {
        // 模拟ECG数据包格式
        val packet = mutableListOf<Byte>()
        
        // 包头
        packet.add(0xAA.toByte()) // 同步字节1
        packet.add(0x55.toByte()) // 同步字节2
        packet.add(0x01.toByte()) // 数据类型：ECG
        
        // 数据长度（100个样本点）
        val dataLength = 100
        packet.add((dataLength and 0xFF).toByte()) // 低字节
        packet.add(((dataLength shr 8) and 0xFF).toByte()) // 高字节
        
        // 生成ECG数据
        for (i in 0 until dataLength) {
            val t = i.toFloat() / 10f
            val ecgValue = (Math.sin(t * 2 * Math.PI) * 100 + 
                          Math.sin(t * 4 * Math.PI) * 50 + 
                          Math.sin(t * 8 * Math.PI) * 25).toInt()
            packet.add((ecgValue and 0xFF).toByte()) // 低字节
            packet.add(((ecgValue shr 8) and 0xFF).toByte()) // 高字节
        }
        
        // 校验和
        var checksum = 0
        for (i in 2 until packet.size) {
            checksum += packet[i].toInt() and 0xFF
        }
        packet.add((checksum and 0xFF).toByte())
        
        return packet.toByteArray()
    }
    
    /**
     * 显示数据测试对话框
     */
    private fun showDataTestDialog() {
        val testOptions = arrayOf(
            "📤 发送测试指令",
            "🔧 轻迅协议命令",
            "📥 监控数据接收",
            "📊 查看数据统计",
            "🔄 实时数据流测试",
            "📋 查看数据日志",
            "🧪 生成模拟数据"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("📡 数据来往测试")
            .setItems(testOptions) { _, which ->
                when (which) {
                    0 -> sendTestCommands()
                    1 -> showQingXunProtocolMenu()
                    2 -> monitorDataReception()
                    3 -> showDataStatisticsDialog()
                    4 -> startRealTimeDataTest()
                    5 -> showDataLogDialog()
                    6 -> generateImmediateTestData()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 发送测试指令
     */
    private fun sendTestCommands() {
        val commands = arrayOf(
            "开始数据采集",
            "查询设备状态",
            "发送心跳包",
            "开始ECG测量",
            "发送自定义指令"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("📤 选择要发送的指令")
            .setItems(commands) { _, which ->
                when (which) {
                    0 -> {
                        bluetoothManager.sendStringCommand("START_DATA")
                        updateStatus("📤 已发送: 开始数据采集指令")
                        startDataMonitoring()
                    }
                    1 -> {
                        bluetoothManager.sendStringCommand("DEVICE_STATUS")
                        updateStatus("📤 已发送: 查询设备状态指令")
                    }
                    2 -> {
                        val heartbeat = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05)
                        bluetoothManager.sendCommand(heartbeat)
                        updateStatus("📤 已发送: 心跳包")
                    }
                    3 -> {
                        bluetoothManager.sendStringCommand("START_ECG")
                        updateStatus("📤 已发送: 开始ECG测量指令")
                        startDataMonitoring()
                    }
                    4 -> {
                        showCustomCommandInput()
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示自定义指令输入对话框
     */
    private fun showCustomCommandInput() {
        val input = android.widget.EditText(this)
        input.hint = "输入指令（如：START, STOP, QUERY等）"
        input.setText("START")
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("📤 自定义指令")
            .setView(input)
            .setPositiveButton("发送") { _, _ ->
                val command = input.text.toString().trim()
                if (command.isNotEmpty()) {
                    bluetoothManager.sendStringCommand(command)
                    updateStatus("📤 已发送自定义指令: $command")
                    startDataMonitoring()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 监控数据接收
     */
    private fun monitorDataReception() {
        val monitoringOptions = arrayOf(
            "开始监控数据接收",
            "停止监控",
            "查看当前接收状态",
            "清空接收统计"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("📥 数据接收监控")
            .setItems(monitoringOptions) { _, which ->
                when (which) {
                    0 -> {
                        isDataMonitoringEnabled = true
                        updateStatus("📥 数据接收监控已开启")
                        startDataMonitoring()
                    }
                    1 -> {
                        isDataMonitoringEnabled = false
                        updateStatus("📥 数据接收监控已停止")
                    }
                    2 -> {
                        showCurrentReceptionStatus()
                    }
                    3 -> {
                        receivedDataCount = 0
                        sentDataCount = 0
                        lastDataTime = 0L
                        dataRate = 0f
                        synchronized(dataLogBuffer) { dataLogBuffer.clear() }
                        updateStatus("📥 数据统计已清空")
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示当前接收状态
     */
    private fun showCurrentReceptionStatus() {
        val status = """
            📊 当前数据接收状态:
            
            📥 接收数据:
            总字节数: ${receivedDataCount} 字节
            数据包数: ${if (receivedDataCount > 0) receivedDataCount / 20 else 0} 包
            
            📤 发送数据:
            总字节数: ${sentDataCount} 字节
            指令数: ${if (sentDataCount > 0) sentDataCount / 10 else 0} 条
            
            📈 实时统计:
            数据速率: ${String.format("%.1f", dataRate)} 字节/秒
            最后数据时间: ${if (lastDataTime > 0) java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.getDefault()).format(java.util.Date(lastDataTime)) else "无"}
            
            🔄 监控状态:
            数据监控: ${if (isDataMonitoringEnabled) "已启用" else "已禁用"}
            蓝牙连接: ${if (bluetoothConnected) "已连接" else "未连接"}
        """.trimIndent()
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("📊 数据接收状态")
            .setMessage(status)
            .setPositiveButton("复制状态", { _, _ ->
                copyToClipboard(status)
                updateStatus("数据状态已复制到剪贴板")
            })
            .setNegativeButton("关闭", null)
            .show()
    }
    
    /**
     * 开始实时数据流测试
     */
    private fun startRealTimeDataTest() {
        val testOptions = arrayOf(
            "开始连续数据发送测试",
            "开始数据接收监听",
            "模拟数据流",
            "停止测试"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("🔄 实时数据流测试")
            .setItems(testOptions) { _, which ->
                when (which) {
                    0 -> startContinuousDataTest()
                    1 -> startDataReceptionListener()
                    2 -> simulateDataStream()
                    3 -> stopDataTest()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 开始连续数据发送测试
     */
    private fun startContinuousDataTest() {
        updateStatus("🔄 开始连续数据发送测试...")
        
        // 启动后台线程进行连续发送
        Thread {
            var testCount = 0
            while (isDataMonitoringEnabled && bluetoothConnected) {
                try {
                    val testData = "TEST_DATA_${testCount++}".toByteArray()
                    bluetoothManager.sendCommand(testData)
                    
                    runOnUiThread {
                        updateStatus("📤 发送测试数据 #$testCount: ${testData.size} 字节")
                    }
                    
                    Thread.sleep(1000) // 每秒发送一次
                } catch (e: Exception) {
                    runOnUiThread {
                        updateStatus("❌ 连续发送测试失败: ${e.message}")
                    }
                    break
                }
            }
        }.start()
    }
    
    /**
     * 开始数据接收监听
     */
    private fun startDataReceptionListener() {
        updateStatus("📥 开始数据接收监听...")
        isDataMonitoringEnabled = true
        
        // 启动后台线程监听数据接收
        Thread {
            var lastReceivedCount = receivedDataCount
            while (isDataMonitoringEnabled) {
                try {
                    if (receivedDataCount > lastReceivedCount) {
                        val newData = receivedDataCount - lastReceivedCount
                        runOnUiThread {
                            updateStatus("📥 检测到新数据: +$newData 字节，总计: $receivedDataCount 字节")
                        }
                        lastReceivedCount = receivedDataCount
                    }
                    Thread.sleep(500) // 每500ms检查一次
                } catch (e: Exception) {
                    break
                }
            }
        }.start()
    }
    
    /**
     * 模拟数据流
     */
    private fun simulateDataStream() {
        updateStatus("🔄 开始模拟数据流...")
        
        Thread {
            var simCount = 0
            while (isDataMonitoringEnabled) {
                try {
                    // 模拟接收数据
                    val simulatedData = generateSimulatedData(simCount++)
                    
                    // 更新接收统计
                    receivedDataCount += simulatedData.size
                    val currentTime = System.currentTimeMillis()
                    if (lastDataTime > 0) {
                        val timeDiff = currentTime - lastDataTime
                        if (timeDiff > 0) {
                            dataRate = (simulatedData.size * 1000f) / timeDiff
                        }
                    }
                    lastDataTime = currentTime
                    
                    runOnUiThread {
                        updateStatus("📥 模拟数据流: 接收 ${simulatedData.size} 字节，总计: $receivedDataCount 字节")
                        updateDataStatistics()
                    }
                    
                    Thread.sleep(800) // 每800ms模拟一次数据接收
                } catch (e: Exception) {
                    break
                }
            }
        }.start()
    }
    
    /**
     * 生成模拟数据
     */
    private fun generateSimulatedData(count: Int): ByteArray {
        val data = mutableListOf<Byte>()
        
        // 添加时间戳 (8字节)
        val timestamp = System.currentTimeMillis()
        for (i in 0..7) {
            data.add(((timestamp shr (i * 8)) and 0xFF).toByte())
        }
        
        // 添加计数器 (4字节)
        for (i in 0..3) {
            data.add(((count shr (i * 8)) and 0xFF).toByte())
        }
        
        // 添加模拟传感器数据
        for (i in 0 until 10) {
            val sensorValue = (Math.sin(count * 0.1 + i) * 100).toInt()
            for (j in 0..3) {
                data.add(((sensorValue shr (j * 8)) and 0xFF).toByte())
            }
        }
        
        return data.toByteArray()
    }
    
    /**
     * 停止数据测试
     */
    private fun stopDataTest() {
        isDataMonitoringEnabled = false
        updateStatus("🔄 数据测试已停止")
    }
    
    /**
     * 开始数据监控
     */
    private fun startDataMonitoring() {
        if (!isDataMonitoringEnabled) {
            isDataMonitoringEnabled = true
            updateStatus("📊 数据监控已启动")
        }
    }
    
    override fun onDeviceInfoReceived(deviceInfo: com.example.cmake_project_test.BluetoothManager.DeviceInfo) {
        runOnUiThread {
            updateStatus("📋 设备信息: ${deviceInfo.manufacturer} ${deviceInfo.model}")
        }
    }
    
    override fun onBatteryLevelReceived(batteryLevel: Int) {
        runOnUiThread {
            updateStatus("🔋 电量: $batteryLevel%")
        }
    }
    
    override fun onCollectionStatusChanged(isCollecting: Boolean) {
        runOnUiThread {
            updateStatus("📊 采集状态: ${if (isCollecting) "开启" else "关闭"}")
        }
    }
    
    override fun onProtocolDataReceived(functionCode: Int, data: ByteArray) {
        val currentTime = System.currentTimeMillis()
        
        // 限制协议数据日志频率
        if (currentTime - lastDataLogTime >= 1000) {
            lastDataLogTime = currentTime
            Log.d("MainActivity", "收到协议数据: 功能码=0x${functionCode.toString(16).uppercase()}, 数据长度=${data.size}")
        }
        
        runOnUiThread {
            updateStatus("📡 协议数据: 功能码=0x${functionCode.toString(16).uppercase()}, 数据=${data.size}字节")
        }
    }
}