package com.example.cmake_project_test

import androidx.appcompat.app.AppCompatActivity
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
        private val REQUIRED_PERMISSIONS = 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

    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())

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

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

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

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

        // 陷波滤波器按钮点击事件
        binding.notchFilterButton.setOnClickListener {
            toggleNotchFilter()
        }
    }

    private var notchFilterEnabled = false
    private var bluetoothConnected = 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>()
        
        for (permission in REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add(permission)
            }
        }
        
        if (missingPermissions.isNotEmpty()) {
            updateStatus("需要蓝牙权限: ${missingPermissions.joinToString(", ")}")
            ActivityCompat.requestPermissions(
                this,
                missingPermissions.toTypedArray(),
                PERMISSION_REQUEST_CODE
            )
            return false
        }
        
        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 allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
                
                if (allGranted) {
                    updateStatus("蓝牙权限已授予，开始扫描...")
                    startBluetoothScan()
                } else {
                    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() {
        // 禁用启动按钮，启用停止按钮和陷波滤波器按钮
        binding.startButton.isEnabled = false
        binding.stopButton.isEnabled = true
        binding.notchFilterButton.isEnabled = true

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

        // 更新UI状态
        binding.sampleText.text = "正在启动程序...\n\n请稍候，正在加载数据文件..."

        // 在后台线程处理数据加载和解析
        Thread {
            try {
                Log.d("MainActivity", "开始加载数据文件...")
                
                // 从 assets 文件夹读取文件
                val fileData = FileHelper.readAssetFile(this, Constants.DEFAULT_DATA_FILE)
                Log.d("MainActivity", "文件读取结果: ${if (fileData != null) "成功，大小: ${fileData.size} 字节" else "失败"}")

                if (fileData != null) {
                    // 先显示文件读取成功的信息
                    runOnUiThread {
                        binding.sampleText.text = "文件读取成功！\n文件大小: ${fileData.size} 字节\n\n正在处理数据，请稍候..."
                    }
                    
                    // 使用真实流式解析路径：按块喂数据 -> drain -> 展示
                    Log.d("MainActivity", "开始处理文件数据...")
                    try {
                        // 添加进度回调
                        dataManager.processFileData(fileData) { progress ->
                            // 进度更新回调
                            runOnUiThread {
                                val progressText = buildString {
                                    append("文件读取成功！\n")
                                    append("文件大小: ${fileData.size} 字节\n\n")
                                    append("正在处理数据...\n")
                                    append("进度: $progress%\n")
                                    append("进度条: ${"█".repeat(progress / 5)}${"░".repeat(20 - (progress / 5))}\n")
                                    append("请稍候...")
                                }
                                binding.sampleText.text = progressText
                            }
                        }
                        Log.d("MainActivity", "文件数据处理完成")
                        
                        // 直接更新UI，显示加载结果
                        runOnUiThread {
                            try {
                                Log.d("MainActivity", "开始UI更新流程")
                                
                                // 暂时禁用测试指标计算功能，避免闪退
                                Log.d("MainActivity", "跳过测试指标计算功能")
                                /*
                                try {
                                    dataManager.testIndicatorCalculation()
                                    Log.d("MainActivity", "测试指标计算完成")
                                } catch (e: Exception) {
                                    Log.e("MainActivity", "测试指标计算失败: ${e.message}", e)
                                }
                                */
                                
                                Log.d("MainActivity", "开始构建显示内容")
                                val displayContent = try {
                                    // 构建详细的显示内容，包括映射信息
                                    val detailedContent = buildString {
                                        append("=== 设备数据概览 ===\n")
                                        append("原始数据包: ${dataManager.getPacketBufferSize()} 个\n")
                                        append("映射后数据包: ${dataManager.getProcessedPacketsSize()} 个\n")
                                        append("计算指标数: ${dataManager.getCalculatedMetricsSize()} 个\n")
                                        append("总数据量: ${dataManager.getRawStreamSize()} 字节\n")
                                        append("总共解析: ${dataManager.getTotalPacketsParsed()} 个数据包\n")
                                        
                                        // 显示原始数据包信息
                                        if (dataManager.getPacketBufferSize() > 0) {
                                            append("\n=== 原始数据信息 ===\n")
                                            try {
                                                val firstPacket = dataManager.getPacketBuffer().firstOrNull()
                                                if (firstPacket != null) {
                                                    append("第一个数据包类型: ${firstPacket.getDataType()}\n")
                                                    append("第一个数据包序号: ${firstPacket.getPacketSn()}\n")
                                                    append("第一个数据包时间戳: ${firstPacket.getTimestamp()}\n")
                                                    
                                                    val channelData = firstPacket.getChannelData()
                                                    if (channelData != null) {
                                                        append("通道数量: ${channelData.size}\n")
                                                        if (channelData.isNotEmpty()) {
                                                            val firstChannel = channelData[0]
                                                            append("第一个通道数据点数: ${firstChannel.size}\n")
                                                            if (firstChannel.isNotEmpty()) {
                                                                append("第一个通道前3个值: ${firstChannel.take(3).joinToString(", ")}\n")
                                                            }
                                                        }
                                                    }
                                                }
                                            } catch (e: Exception) {
                                                append("获取原始数据包信息时出错: ${e.message}\n")
                                            }
                                        }
                                        
                                        // 显示映射后的数据包信息
                                        if (dataManager.getProcessedPacketsSize() > 0) {
                                            append("\n=== 映射后数据信息 ===\n")
                                            try {
                                                val processedPackets = dataManager.getProcessedPackets()
                                                append("DEBUG: 处理后数据包总数: ${processedPackets.size}\n")
                                                
                                                // 统计ECG_12LEAD数据包的通道数量分布
                                                val ecg12LeadPackets = processedPackets.filter { it.getDataType() == type.SensorData.DataType.ECG_12LEAD }
                                                val packetsWith8Channels = ecg12LeadPackets.count { it.getChannelData()?.size == 8 }
                                                val packetsWith12Channels = ecg12LeadPackets.count { it.getChannelData()?.size == 12 }
                                                append("DEBUG: ECG_12LEAD数据包统计 - 8通道: ${packetsWith8Channels}个, 12通道: ${packetsWith12Channels}个\n")
                                                
                                                // 详细统计前10个ECG_12LEAD数据包
                                                val first10EcgPackets = ecg12LeadPackets.take(10)
                                                append("DEBUG: 前10个ECG_12LEAD数据包详情:\n")
                                                first10EcgPackets.forEachIndexed { index, packet ->
                                                    append("  数据包${index + 1}: 序号=${packet.getPacketSn()}, 通道数=${packet.getChannelData()?.size}\n")
                                                }
                                                
                                                // 查找第一个映射成功的ECG_12LEAD数据包（12通道）
                                                val mappedEcg12LeadPacket = processedPackets.find { packet ->
                                                    packet.getDataType() == type.SensorData.DataType.ECG_12LEAD && 
                                                    packet.getChannelData()?.size == 12
                                                }
                                                val firstMappedPacket = mappedEcg12LeadPacket ?: processedPackets.firstOrNull()
                                                
                                                if (firstMappedPacket != null) {
                                                    append("选择的数据包类型: ${firstMappedPacket.getDataType()}\n")
                                                    append("选择的数据包序号: ${firstMappedPacket.getPacketSn()}\n")
                                                    append("选择的数据包时间戳: ${firstMappedPacket.getTimestamp()}\n")
                                                    
                                                    val mappedChannelData = firstMappedPacket.getChannelData()
                                                    if (mappedChannelData != null) {
                                                        append("映射后通道数量: ${mappedChannelData.size}\n")
                                                        append("DEBUG: 通道数据详情: ${mappedChannelData}\n")
                                                                                                            if (mappedChannelData.isNotEmpty()) {
                                                        val firstMappedChannel = mappedChannelData[0]
                                                        append("第一个映射通道数据点数: ${firstMappedChannel.size}\n")
                                                        if (firstMappedChannel.isNotEmpty()) {
                                                            append("第一个映射通道前3个值: ${firstMappedChannel.take(3).joinToString(", ")}\n")
                                                        }
                                                        
                                                        // 显示第二个通道数据
                                                        if (mappedChannelData.size > 1) {
                                                            val secondMappedChannel = mappedChannelData[1]
                                                            append("第二个映射通道数据点数: ${secondMappedChannel.size}\n")
                                                            if (secondMappedChannel.isNotEmpty()) {
                                                                append("第二个映射通道前3个值: ${secondMappedChannel.take(3).joinToString(", ")}\n")
                                                            }
                                                        }
                                                    }
                                                    }
                                                }
                                            } catch (e: Exception) {
                                                append("获取映射数据包信息时出错: ${e.message}\n")
                                            }
                                        }
                                        
                                        // 显示计算出的指标
                                        if (dataManager.getCalculatedMetricsSize() > 0) {
                                            append("\n=== 计算指标信息 ===\n")
                                            try {
                                                val latestMetrics = dataManager.getLatestMetrics()
                                                if (latestMetrics != null) {
                                                    append("最新指标数量: ${latestMetrics.size}\n")
                                                    append("指标详情:\n")
                                                    latestMetrics.forEach { (key, value) ->
                                                        append("  $key: ${String.format("%.2f", value)}\n")
                                                    }
                                                }
                                                
                                                // 显示所有指标的平均值
                                                val allMetrics = dataManager.getCalculatedMetrics()
                                                if (allMetrics.isNotEmpty()) {
                                                    val heartRates = allMetrics.mapNotNull { metrics -> metrics["heart_rate"] }.filter { it > 0 }
                                                    val qualities = allMetrics.mapNotNull { metrics -> metrics["signal_quality"] }.filter { it >= 0 }
                                                    
                                                    if (heartRates.isNotEmpty()) {
                                                        val avgHeartRate = heartRates.average()
                                                        append("平均心率: ${String.format("%.1f", avgHeartRate)} bpm\n")
                                                    }
                                                    
                                                    if (qualities.isNotEmpty()) {
                                                        val avgQuality = qualities.average()
                                                        append("平均信号质量: ${String.format("%.2f", avgQuality)}\n")
                                                    }
                                                }
                                            } catch (e: Exception) {
                                                append("获取指标信息时出错: ${e.message}\n")
                                            }
                                        }
                                        
                                        append("\n=== 状态信息 ===\n")
                                                append("数据解析完成 ✓\n")
        append("数据映射完成 ✓\n")
        append("信号处理完成 ✓\n")
        append("指标计算完成 ✓\n")
        append("应用已就绪，可以开始使用\n")
        
        // 显示流式处理状态
        val processingStatus = dataManager.getProcessingStatus()
        append("\n=== 流式处理状态 ===\n")
        append("当前数据类型: ${processingStatus["currentDataType"]}\n")
        append("总样本数: ${processingStatus["totalSamples"]}/${processingStatus["minSamplesRequired"]}\n")
        append("距离上次处理: ${processingStatus["timeSinceLastProcess"]}ms/${processingStatus["processingInterval"]}ms\n")
        append("总处理样本数: ${processingStatus["totalProcessedSamples"]}\n")
        
        // 显示流式指标计算结果
        val latestMetrics = dataManager.getLatestMetrics()
        if (latestMetrics.isNotEmpty()) {
            append("\n=== 流式指标计算结果 ===\n")
            append("基于流式数据处理的最新指标:\n")
            latestMetrics.forEach { (key, value) ->
                append("  $key: $value\n")
            }
        } else {
            append("\n=== 流式指标计算结果 ===\n")
            append("暂无流式指标计算结果\n")
        }
        
        // 显示原始通道缓冲区状态
        val channelBuffers = dataManager.getChannelBuffersStatus()
        if (channelBuffers.isNotEmpty()) {
            append("\n=== 原始通道缓冲区状态 ===\n")
            channelBuffers.forEach { (channel, sampleCount) ->
                append("  通道 $channel: $sampleCount 个样本\n")
            }
        }
        
        // 显示处理后通道缓冲区状态
        val processedChannelBuffers = dataManager.getProcessedChannelBuffersStatus()
        if (processedChannelBuffers.isNotEmpty()) {
            append("\n=== 处理后通道缓冲区状态 ===\n")
            processedChannelBuffers.forEach { (channel, sampleCount) ->
                append("  通道 $channel: $sampleCount 个样本\n")
            }
        }
                                    }
                                    detailedContent
                                } catch (e: Exception) {
                                    Log.e("MainActivity", "构建显示内容失败: ${e.message}", e)
                                    "构建显示内容失败: ${e.message}\n\n请检查数据格式。"
                                }
                                Log.d("MainActivity", "显示内容构建完成，长度: ${displayContent.length}")
                                
                                try {
                                    binding.sampleText.text = displayContent
                                    Log.d("MainActivity", "UI文本设置成功")
                                    

                                    
                                } catch (e: Exception) {
                                    Log.e("MainActivity", "设置UI文本失败: ${e.message}", e)
                                    binding.sampleText.text = "设置UI文本失败: ${e.message}"
                                }
                                
                                // 记录日志
                                Log.d("MainActivity", "UI更新完成，数据包数量: ${dataManager.getPacketBufferSize()}, 总解析: ${dataManager.getTotalPacketsParsed()}")
                            } catch (e: Exception) {
                                Log.e("MainActivity", "UI更新失败: ${e.message}", e)
                                val errorMessage = buildString {
                                    append("UI更新失败: ${e.message}\n\n")
                                    append("数据包数量: ${dataManager.getPacketBufferSize()}\n")
                                    append("总解析: ${dataManager.getTotalPacketsParsed()}\n")
                                    append("错误详情: ${e.stackTraceToString()}")
                                }
                                try {
                                    binding.sampleText.text = errorMessage
                                } catch (e2: Exception) {
                                    Log.e("MainActivity", "设置错误信息也失败: ${e2.message}", e2)
                                }
                            }
                        }
                    } catch (e: Exception) {
                        Log.e("MainActivity", "数据处理失败: ${e.message}", e)
                        runOnUiThread {
                            binding.sampleText.text = "数据处理失败: ${e.message}\n\n请检查数据文件格式是否正确。"
                        }
                    }
                } else {
                    runOnUiThread {
                        binding.sampleText.text = "读取文件失败：无法从assets文件夹读取${Constants.DEFAULT_DATA_FILE}\n\n请检查：\n1. assets文件夹中是否存在该文件\n2. 文件名是否正确\n3. 文件是否损坏"
                    }
                }
            } catch (e: Exception) {
                Log.e("MainActivity", "Error processing data", e)
                runOnUiThread {
                    binding.sampleText.text = "错误: ${e.message}\n\n请检查assets文件夹中是否存在${Constants.DEFAULT_DATA_FILE}文件"
                }
            }
        }.apply { 
            // 设置线程名称，便于调试
            name = "DataLoadingThread"
            // 设置为守护线程，避免阻塞应用退出
            isDaemon = true
        }.start()
    }

    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)
        }
    }

    // 蓝牙通知回调时调用：将 chunk 追加到解析器并拉取新包
    fun onBleNotify(chunk: ByteArray) {
        dataManager.onBleNotify(chunk)
        
        // 触发UI更新
        uiManager.scheduleUiUpdate(dataManager) {
            val text = uiManager.buildDisplayContent(dataManager)
                binding.sampleText.text = text
        }
    }



    
    // 原生方法声明 - 保持原来的JNI函数名
    override external fun createStreamParser(): Long
    override external fun destroyStreamParser(handle: Long)
    

    
    /**
     * 获取原始通道数据
     */
    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>) {
        // 性能优化：减少UI线程调用频率
        if (channelIndex == 0) {
            // 直接在主线程更新，避免频繁的线程切换
            try {
                // 显示ECG图表
                binding.ecgChartContainer.visibility = View.VISIBLE
                
                binding.ecgRhythmView.updateData(processedData)
                binding.ecgWaveformView.updateData(processedData)
            } catch (e: Exception) {
                Log.e("MainActivity", "处理实时数据失败: ${e.message}", e)
            }
        }
    }
    
    override fun onRawDataAvailable(channelIndex: Int, rawData: List<Float>) {
        // 立即显示原始数据到图表
        try {
            Log.d("MainActivity", "收到原始数据回调，通道: $channelIndex，数据长度: ${rawData.size}")
            if (rawData.isNotEmpty()) {
                Log.d("MainActivity", "原始数据前3个值: ${rawData.take(3).joinToString(", ")}")
            }
            
            // 显示ECG图表
            binding.ecgChartContainer.visibility = View.VISIBLE
            
            binding.ecgRhythmView.updateData(rawData)
            binding.ecgWaveformView.updateData(rawData)
            
            Log.d("MainActivity", "已更新图表，通道: $channelIndex，数据长度: ${rawData.size}")
        } catch (e: Exception) {
            Log.e("MainActivity", "显示原始数据失败: ${e.message}", e)
        }
    }
    
    override fun onStreamingProgress(progress: Int, totalSamples: Int, processedSamples: Int) {
        runOnUiThread {
            try {
                Log.d("MainActivity", "流式处理进度: $progress%, 总样本: $totalSamples, 已处理: $processedSamples")
                
                // 更新进度显示
                val progressText = buildString {
                    append("=== 实时流式处理 ===\n")
                    append("处理进度: $progress%\n")
                    append("进度条: ${"█".repeat(progress / 5)}${"░".repeat(20 - (progress / 5))}\n")
                    append("总样本数: $totalSamples\n")
                    append("已处理样本: $processedSamples\n")
                    append("实时曲线图已更新 ✓\n")
                }
                
                // 在文本区域显示进度信息
                val currentText = binding.sampleText.text.toString()
                val updatedText = if (currentText.contains("=== 实时流式处理 ===")) {
                    // 替换现有的进度信息
                    currentText.replace(Regex("=== 实时流式处理 ===\\n.*?实时曲线图已更新 ✓\\n", RegexOption.DOT_MATCHES_ALL), progressText)
                } else {
                    // 在开头添加进度信息
                    progressText + currentText
                }
                
                binding.sampleText.text = updatedText
                
            } catch (e: Exception) {
                Log.e("MainActivity", "更新流式进度失败: ${e.message}", e)
            }
        }
    }

    private fun stopDataProcessing() {
        // 启用启动按钮，禁用停止按钮和陷波滤波器按钮
        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 external fun streamParserAppend(handle: Long, chunk: ByteArray)
    override external fun streamParserDrainPackets(handle: Long): List<SensorData>?

    // 蓝牙回调方法
    override fun onDeviceFound(device: BluetoothDevice) {
        runOnUiThread {
            updateStatus("发现设备: ${device.name ?: device.address}")
        }
    }

    override fun onConnected(device: BluetoothDevice) {
        runOnUiThread {
            bluetoothConnected = true
            binding.bluetoothButton.text = "断开蓝牙"
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#F44336"))
            updateStatus("蓝牙设备已连接: ${device.name ?: device.address}")
        }
    }

    override fun onDisconnected() {
        runOnUiThread {
            bluetoothConnected = false
            binding.bluetoothButton.text = "连接蓝牙"
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#4CAF50"))
            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) }}")
        }
        
        // 在后台线程处理数据，避免阻塞UI
        Thread {
            try {
                Log.d("MainActivity", "开始处理蓝牙数据: ${data.size} 字节")
                
                // 将蓝牙数据传递给DataManager处理
                dataManager.onBleNotify(data)
                
                // 在UI线程更新状态和显示图表
                runOnUiThread {
                    updateStatus("接收到蓝牙数据: ${data.size} 字节")
                    
                    // 显示ECG图表
                    binding.ecgChartContainer.visibility = View.VISIBLE
                }
                
            } catch (e: Exception) {
                Log.e("MainActivity", "处理蓝牙数据失败: ${e.message}", e)
                runOnUiThread {
                    updateStatus("处理蓝牙数据失败: ${e.message}")
                }
            }
        }.start()
    }

    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")
        }
    }

    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 lines = currentText.split("\n").toMutableList()
        if (lines.size > 20) { // 限制显示行数
            lines.removeAt(0)
        }
        lines.add(newStatus)
        
        binding.sampleText.text = lines.joinToString("\n")
    }
}