package com.example.cmake_project_test

import android.app.Activity
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
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Environment
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*
import android.content.Intent
import androidx.core.content.FileProvider
import android.net.Uri
import android.widget.Toast
import android.os.Handler
import android.os.Looper

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 lateinit var dynamicChartManager: DynamicChartManager
    
    // 数据处理状态
    private var dataProcessingStarted = false
    private var bluetoothConnected = false
    
    // 数据监控相关
    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 lastProgressUpdateTime = 0L
    
    // 导出功能相关
    private var exportedDataCount = 0
    private val dataExportBuffer = mutableListOf<Float>()
    private val exportTimeStamps = mutableListOf<Long>()

    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) // 设置蓝牙回调
        
        // 初始化动态图表管理器
        dynamicChartManager = DynamicChartManager(
            context = this,
            chartsContainer = binding.chartsContainer,
            chartTitle = binding.chartTitle
        )

        // 设置图表全屏按钮点击监听器
        dynamicChartManager.setOnChartFullscreenClickListener { chartIndex, chart ->
            showSingleChartFullscreen(chartIndex, chart)
        }


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

        // 确保图表容器可见
        binding.dynamicChartContainer.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.resetChartsButton.setOnClickListener {
            dynamicChartManager.resetAllCharts()
            updateStatus("已重置所有图表到默认状态")
        }
        
        // 全屏按钮点击事件（已移除，现在每张图表都有独立的全屏按钮）
        
        
        // 添加导出按钮（长按清空数据按钮）
        binding.clearDataButton.setOnLongClickListener {
            exportChartData()
            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
        
        // 启用图表控制按钮
        binding.resetChartsButton.isEnabled = true

        // 清空动态图表数据
        dynamicChartManager.clearAllCharts()

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

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

    override fun onResume() {
        super.onResume()
        Log.d("MainActivity", "MainActivity恢复")
        
        // 检查蓝牙连接状态
        if (bluetoothConnected) {
            Log.d("MainActivity", "蓝牙连接状态正常")
        } else {
            Log.w("MainActivity", "⚠️ 蓝牙连接已断开，需要重新连接")
        }
    }
    
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Log.d("MainActivity", "MainActivity收到新Intent（singleTop模式）")
        setIntent(intent)
    }
    
    override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.d("MainActivity", "MainActivity配置变更，避免重新创建Activity")
        
        // 确保蓝牙连接状态保持
        if (bluetoothConnected) {
            Log.d("MainActivity", "配置变更时蓝牙连接状态正常")
        }
    }

    override fun onStop() {
        super.onStop()
        // 不要在这里清理数据管理器，因为全屏Activity启动时MainActivity会进入onStop
        // 数据管理器应该在应用真正退出时才清理
        Log.d("MainActivity", "MainActivity进入onStop状态，保持数据管理器运行")
    }
    
    override fun onDestroy() {
        super.onDestroy()
        try {
            Log.w("MainActivity", "⚠️ MainActivity正在被销毁！这通常不应该发生")
            Log.w("MainActivity", "⚠️ 可能的原因：应用被系统杀死、内存不足、或异常退出")
            Log.w("MainActivity", "⚠️ 正常情况下MainActivity应该继续运行，只有FullscreenChartActivity会被销毁")
            
            // 记录当前状态
            Log.d("MainActivity", "当前状态 - 蓝牙连接: $bluetoothConnected, 数据处理: $dataProcessingStarted")
            Log.d("MainActivity", "开始清理应用资源")
            
            // 先清理蓝牙管理器，避免FragmentManager问题
            try {
                bluetoothManager.cleanup()
                Log.d("MainActivity", "蓝牙管理器清理完成")
            } catch (e: Exception) {
                Log.e("MainActivity", "蓝牙管理器清理失败: ${e.message}", e)
            }
            
            // 再清理数据管理器
            try {
                dataManager.cleanup()
                Log.d("MainActivity", "数据管理器清理完成")
            } catch (e: Exception) {
                Log.e("MainActivity", "数据管理器清理失败: ${e.message}", e)
            }
            
            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>) {
        // 性能优化：减少UI线程调用频率
        if (channelIndex == 0) {
            // 直接在主线程更新，避免频繁的线程切换
            try {
                // 获取当前设备类型和映射后的通道数据
                val packets = dataManager.getPacketBuffer()
                if (packets.isNotEmpty()) {
                    val latestPacket = packets.last()
                    val deviceType = latestPacket.getDataType()
                    
                    // 获取映射后的通道数据
                    val mappedPackets = dataManager.getMappedPacketBuffer()
                    if (mappedPackets.isNotEmpty()) {
                        val latestMappedPacket = mappedPackets.last()
                        val channelData = latestMappedPacket.getChannelData()
                        if (channelData != null && channelData.isNotEmpty()) {
                            // 在主线程中更新UI
                            runOnUiThread {
                                try {
                                    // 显示动态图表容器
                                    Log.d("MainActivity", "设置动态图表容器可见")
                                    binding.dynamicChartContainer.visibility = View.VISIBLE
                                    
                                    // 根据设备类型创建对应数量的图表
                                    val currentDeviceType = dynamicChartManager.getCurrentDeviceType()
                                    val currentChannelCount = dynamicChartManager.getCurrentChannelCount()
                                    
                                    Log.d("MainActivity", "当前设备类型: $currentDeviceType, 当前通道数: $currentChannelCount")
                                    Log.d("MainActivity", "新设备类型: $deviceType")
                                    
                                    if (currentDeviceType != deviceType || currentChannelCount == 0) {
                                        Log.d("MainActivity", "设备类型改变或首次创建图表: $deviceType")
                                        dynamicChartManager.createChartsForDevice(deviceType)
                                        Log.d("MainActivity", "图表创建完成，当前图表数量: ${dynamicChartManager.getCharts().size}")
                                    }
                                    
                                    // 更新所有图表的数据
                                    Log.d("MainActivity", "开始更新图表数据，通道数: ${channelData.size}")
                                    dynamicChartManager.updateChartsData(channelData)
                                    
                                    Log.d("MainActivity", "已更新动态图表（处理后数据），设备: $deviceType，通道数: ${channelData.size}")
                                } catch (e: Exception) {
                                    Log.e("MainActivity", "更新UI时发生异常: ${e.message}", e)
                                }
                            }
                        }
                    } else {
                        // 如果没有映射数据，使用原始数据
                        val channelData = latestPacket.getChannelData()
                        if (channelData != null && channelData.isNotEmpty()) {
                            // 在主线程中更新UI
                            runOnUiThread {
                                // 显示动态图表容器
                                Log.d("MainActivity", "设置动态图表容器可见")
                                binding.dynamicChartContainer.visibility = View.VISIBLE
                                
                                // 根据设备类型创建对应数量的图表
                                val currentDeviceType = dynamicChartManager.getCurrentDeviceType()
                                val currentChannelCount = dynamicChartManager.getCurrentChannelCount()
                                
                                Log.d("MainActivity", "当前设备类型: $currentDeviceType, 当前通道数: $currentChannelCount")
                                Log.d("MainActivity", "新设备类型: $deviceType")
                                
                                if (currentDeviceType != deviceType || currentChannelCount == 0) {
                                    Log.d("MainActivity", "设备类型改变或首次创建图表: $deviceType")
                                    dynamicChartManager.createChartsForDevice(deviceType)
                                    Log.d("MainActivity", "图表创建完成，当前图表数量: ${dynamicChartManager.getCharts().size}")
                                }
                                
                                // 更新所有图表的数据
                                Log.d("MainActivity", "开始更新图表数据，通道数: ${channelData.size}")
                                dynamicChartManager.updateChartsData(channelData)
                                
                                Log.d("MainActivity", "已更新动态图表（处理后数据，原始通道），设备: $deviceType，通道数: ${channelData.size}")
                            }
                        }
                    }
                }
                
                // 注意：ECG图表已移除，现在只使用动态图表
                
            } catch (e: Exception) {
                Log.e("MainActivity", "处理实时数据失败: ${e.message}", e)
            }
        }
    }
    
    override fun onRawDataAvailable(channelIndex: Int, rawData: List<Float>) {
        // 处理多通道数据，根据设备类型动态创建图表
        try {
            Log.d("MainActivity", "=== 收到原始数据回调 ===")
            Log.d("MainActivity", "通道: $channelIndex，数据长度: ${rawData.size}")
            if (rawData.isNotEmpty()) {
                Log.d("MainActivity", "原始数据前3个值: ${rawData.take(3).joinToString(", ")}")
            }
            
            // 获取当前设备类型和映射后的通道数据
            val packets = dataManager.getPacketBuffer()
            if (packets.isNotEmpty()) {
                val latestPacket = packets.last()
                val deviceType = latestPacket.getDataType()

                // 获取映射后的通道数据
                val mappedPackets = dataManager.getMappedPacketBuffer()
                if (mappedPackets.isNotEmpty()) {
                    val latestMappedPacket = mappedPackets.last()
                    val channelData = latestMappedPacket.getChannelData()
                    if (channelData != null && channelData.isNotEmpty()) {
                        // 在主线程中更新UI
                        runOnUiThread {
                            try {
                                // 显示动态图表容器
                                Log.d("MainActivity", "设置动态图表容器可见")
                                binding.dynamicChartContainer.visibility = View.VISIBLE
                                
                                // 根据设备类型创建对应数量的图表
                                val currentDeviceType = dynamicChartManager.getCurrentDeviceType()
                                val currentChannelCount = dynamicChartManager.getCurrentChannelCount()
                                
                                Log.d("MainActivity", "当前设备类型: $currentDeviceType, 当前通道数: $currentChannelCount")
                                Log.d("MainActivity", "新设备类型: $deviceType")
                                
                                if (currentDeviceType != deviceType || currentChannelCount == 0) {
                                    Log.d("MainActivity", "设备类型改变或首次创建图表: $deviceType")
                                    dynamicChartManager.createChartsForDevice(deviceType)
                                    Log.d("MainActivity", "图表创建完成，当前图表数量: ${dynamicChartManager.getCharts().size}")
                                }
                                
                                // 更新所有图表的数据
                                Log.d("MainActivity", "开始更新图表数据，通道数: ${channelData.size}")
                                dynamicChartManager.updateChartsData(channelData)
                                
                                Log.d("MainActivity", "已更新动态图表，设备: $deviceType，通道数: ${channelData.size}")
                            } catch (e: Exception) {
                                Log.e("MainActivity", "更新UI时发生异常: ${e.message}", e)
                            }
                        }
                    }
                } else {
                    // 如果没有映射数据，使用原始数据
                    val channelData = latestPacket.getChannelData()
                    if (channelData != null && channelData.isNotEmpty()) {
                        // 在主线程中更新UI
                        runOnUiThread {
                            // 显示动态图表容器
                            Log.d("MainActivity", "设置动态图表容器可见")
                            binding.dynamicChartContainer.visibility = View.VISIBLE
                            
                            // 根据设备类型创建对应数量的图表
                            val currentDeviceType = dynamicChartManager.getCurrentDeviceType()
                            val currentChannelCount = dynamicChartManager.getCurrentChannelCount()
                            
                            Log.d("MainActivity", "当前设备类型: $currentDeviceType, 当前通道数: $currentChannelCount")
                            Log.d("MainActivity", "新设备类型: $deviceType")
                            
                            if (currentDeviceType != deviceType || currentChannelCount == 0) {
                                Log.d("MainActivity", "设备类型改变或首次创建图表: $deviceType")
                                dynamicChartManager.createChartsForDevice(deviceType)
                                Log.d("MainActivity", "图表创建完成，当前图表数量: ${dynamicChartManager.getCharts().size}")
                            }
                            
                            // 更新所有图表的数据
                            Log.d("MainActivity", "开始更新图表数据，通道数: ${channelData.size}")
                            dynamicChartManager.updateChartsData(channelData)
                            
                            Log.d("MainActivity", "已更新动态图表（原始数据），设备: $deviceType，通道数: ${channelData.size}")
                        }
                    }
                }
            }
            
            // 注意：ECG图表已移除，现在只使用动态图表
            
        } 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
        
        // 禁用图表控制按钮
        binding.resetChartsButton.isEnabled = false

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

        // 轻量级清理数据管理器（保持解析器运行）
        try {
            dataManager.lightCleanup()
            Log.d("MainActivity", "数据管理器轻量级清理完成")
        } catch (e: Exception) {
            Log.e("MainActivity", "轻量级清理数据管理器失败: ${e.message}", e)
        }

        // 清空动态图表数据
        dynamicChartManager.clearAllCharts()

    }

    // 蓝牙回调方法
    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"))
            
            // 显示动态图表容器
            binding.dynamicChartContainer.visibility = View.VISIBLE
            updateStatus("📊 动态图表已准备就绪，请点击'发送指令'按钮开始接收数据")
        }
    }

    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
        
        
        // 立即显示动态图表容器
        runOnUiThread {
            binding.dynamicChartContainer.visibility = View.VISIBLE
            
            // 如果数据处理还没启动，自动启动
            if (!dataProcessingStarted) {
                startDataProcessing()
                updateStatus("检测到数据，自动启动数据处理")
            }
            
            // 减少数据接收状态更新频率
            if (currentTime - lastDataStatusTime > 5000) { // 改为5秒内只更新一次状态
                updateStatus("接收到蓝牙数据: ${data.size} 字节，图表已显示")
                updateDataStatistics()
                lastDataStatusTime = currentTime
            }
        }
        
        // 在后台线程处理数据，避免阻塞UI
        Thread {
            try {
                Log.d("MainActivity", "开始处理蓝牙数据: ${data.size} 字节")
                
                // 将蓝牙数据传递给DataManager处理
                dataManager.onBleNotify(data)
                
                Log.d("MainActivity", "蓝牙数据处理完成")
                
                
            } catch (e: Exception) {
                Log.e("MainActivity", "处理蓝牙数据失败: ${e.message}", e)
                runOnUiThread {
                    updateStatus("处理蓝牙数据失败: ${e.message}")
                }
            }
        }.start()
    }
    
    
    /**
     * 更新数据统计显示
     */
    private fun updateDataStatistics() {
        val stats = """
            📊 数据统计:
            接收数据: ${receivedDataCount} 字节
            发送数据: ${sentDataCount} 字节
            数据速率: ${String.format("%.1f", dataRate)} 字节/秒
            连接状态: ${if (bluetoothConnected) "已连接" else "未连接"}
        """.trimIndent()
        
        // 更新状态显示
        binding.sampleText.text = stats
    }
    
    
    
    /**
     * 显示调试信息对话框
     */
    
    
    /**
     * 立即生成测试数据
     */

    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.dynamicChartContainer.visibility = View.VISIBLE
                updateStatus("动态图表已激活，请点击'发送指令'按钮开始接收数据")
            }
        }
    }
    
    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"))
            }
        }
    }

    // 使用StringBuilder缓存状态文本，提高性能
    private val statusBuilder = StringBuilder()
    private val statusLines = mutableListOf<String>()

    private fun updateStatus(message: String) {
        // 限制状态更新频率，避免过多提示导致卡顿
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastStatusUpdateTime < 800) { // 增加到800ms，减少更新频率
            return
        }
        lastStatusUpdateTime = currentTime

        // 使用高效的方式构建状态文本
        val timestamp = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())
        val newStatus = "[$timestamp] $message"

        // 使用MutableList管理状态行，避免频繁的字符串分割
        if (statusLines.size >= 12) { // 减少到12行，进一步提高性能
            statusLines.removeAt(0)
        }
        statusLines.add(newStatus)

        // 使用StringBuilder构建最终文本
        statusBuilder.clear()
        statusLines.forEachIndexed { index, line ->
            if (index > 0) statusBuilder.append('\n')
            statusBuilder.append(line)
        }

        binding.sampleText.text = statusBuilder.toString()

        // 减少日志输出频率
        if (currentTime - lastLogTime > 1500) { // 增加到1.5秒
            Log.d("MainActivity", "状态更新: $message")
            lastLogTime = currentTime
        }
    }
    
    /**
     * 发送数据指令
     */
    private fun sendDataCommand() {
        if (!bluetoothConnected) {
            updateStatus("蓝牙未连接，无法发送指令")
            return
        }
        
        // 显示指令选择对话框
        showCommandDialog()
    }
    

    
    /**
     * 显示指令选择对话框
     */
    private fun showCommandDialog() {
        val commands = arrayOf(
            "轻迅协议指令",
            "PPTM协议指令"
        )

        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("选择指令类型")
            .setItems(commands) { _, which ->
                when (which) {
                    0 -> showQingXunProtocolDialog()
                    1 -> showPptmProtocolDialog()
                }
            }
            .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()
    }
    
    /**
     * 显示PPTM协议指令对话框
     */
    private fun showPptmProtocolDialog() {
        val commands = arrayOf(
            "开始采样",
            "停止采样",
            "自定义PPTM指令"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("PPTM协议指令")
            .setItems(commands) { _, which ->
                when (which) {
                    0 -> {
                        bluetoothManager.sendPptmStartSampleCmd()
                        updateStatus("发送PPTM开始采样指令")
                    }
                    1 -> {
                        bluetoothManager.sendPptmStopSampleCmd()
                        updateStatus("发送PPTM停止采样指令")
                    }
                    2 -> showCustomPptmCommandDialog()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示自定义PPTM指令对话框
     */
    private fun showCustomPptmCommandDialog() {
        val input = android.widget.EditText(this)
        input.hint = "输入操作码（如：0x0001）"
        
        val payloadInput = android.widget.EditText(this)
        payloadInput.hint = "输入负载数据（十六进制，如：01 00 00 00）"
        
        val layout = android.widget.LinearLayout(this).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(50, 20, 50, 20)
            addView(input)
            addView(payloadInput)
        }
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("自定义PPTM指令")
            .setView(layout)
            .setPositiveButton("发送") { _, _ ->
                val opcodeStr = input.text.toString().trim()
                val payloadStr = payloadInput.text.toString().trim()
                
                if (opcodeStr.isNotEmpty()) {
                    try {
                        val opcode = if (opcodeStr.startsWith("0x")) {
                            opcodeStr.substring(2).toShort(16)
                        } else {
                            opcodeStr.toShort()
                        }
                        
                        val payload = if (payloadStr.isNotEmpty()) {
                            payloadStr.split(" ").map { it.toInt(16).toByte() }.toByteArray()
                        } else {
                            ByteArray(0)
                        }
                        
                        bluetoothManager.sendCustomPptmCmd(opcode, payload)
                        updateStatus("发送自定义PPTM指令: 操作码=0x%04X".format(opcode))
                    } catch (e: Exception) {
                        updateStatus("PPTM指令格式错误: ${e.message}")
                    }
                }
            }
            .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("发送设备复位指令")
                    }
                }
            }
            .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 clearAllData() {
        // 清空动态图表数据
        dynamicChartManager.clearAllCharts()
        
        // 清空数据管理器
        dataManager.cleanupBuffer()
        
        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}字节")
        }
    }

    /**
     * 导出图表数据
     */
    private fun exportChartData() {
        try {
            // 获取当前图表数据
            val charts = dynamicChartManager.getCharts()
            if (charts.isEmpty()) {
                updateStatus("❌ 没有图表数据可以导出，请先连接设备并接收数据")
                return
            }
            
            // 显示导出选项对话框
            showDynamicChartExportOptionsDialog(charts)
            
        } catch (e: Exception) {
            Log.e("MainActivity", "导出图表数据失败: ${e.message}", e)
            updateStatus("❌ 导出图表数据失败: ${e.message}")
        }
    }
    
    /**
     * 显示动态图表导出选项对话框
     */
    private fun showDynamicChartExportOptionsDialog(charts: List<DynamicChartView>) {
        val exportOptions = arrayOf(
            "导出所有通道数据 (CSV)"
        )

        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("📊 选择导出图表数据")
            .setItems(exportOptions) { _, which ->
                when (which) {
                    0 -> exportAllChannelsData(charts)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 导出所有通道数据
     */
    private fun exportAllChannelsData(charts: List<DynamicChartView>) {
        Thread {
            try {
                val timestamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.getDefault()).format(java.util.Date())
                val fileName = "AllChannelsData_$timestamp.csv"
                
                val csvContent = buildString {
                    appendLine("多通道生理信号数据")
                    appendLine("导出时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())}")
                    appendLine("通道数量: ${charts.size}")
                    appendLine()
                    
                    // 添加通道标题
                    val channelHeaders = charts.mapIndexed { index, _ -> "通道${index + 1}" }
                    appendLine("时间(ms),${channelHeaders.joinToString(",")}")
                    
                    // 获取最大数据长度
                    val maxLength = charts.map { it.getCurrentData().size }.maxOrNull() ?: 0
                    
                    // 导出数据
                    for (i in 0 until maxLength) {
                        val timeMs = i * 4L // 假设250Hz采样率
                        val values = charts.map { chart ->
                            val data = chart.getCurrentData()
                            if (i < data.size) data[i] else ""
                        }
                        appendLine("$timeMs,${values.joinToString(",")}")
                    }
                }
                
                val file = saveFileToExternalStorage(fileName, csvContent)
                if (file != null) {
                    runOnUiThread {
                        updateStatus("✅ 所有通道数据已导出: ${file.name}")
                        Log.d("MainActivity", "文件导出成功，准备显示分享对话框: ${file.absolutePath}")
                        // 显示分享选项
                        showFileShareDialog(file, "所有通道数据")
                    }
                } else {
                    runOnUiThread {
                        updateStatus("❌ 导出所有通道数据失败")
                        Log.e("MainActivity", "文件保存失败")
                    }
                }
                
            } catch (e: Exception) {
                Log.e("MainActivity", "导出所有通道数据失败: ${e.message}", e)
                runOnUiThread {
                    updateStatus("❌ 导出所有通道数据失败: ${e.message}")
                }
            }
        }.start()
    }
    
    
    /**
     * 导出设备信息
     */
    
    /**
     * 导出节律视图数据
     */
    
    /**
     * 导出波形视图数据
     */
    private fun exportWaveformData(data: List<Float>, stats: Map<String, Any>) {
        Thread {
            try {
                if (data.isEmpty()) {
                    runOnUiThread {
                        updateStatus("❌ 波形视图没有数据可以导出")
                    }
                    return@Thread
                }
                
                val timestamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.getDefault()).format(java.util.Date())
                val fileName = "ECG_WaveformData_$timestamp.csv"
                
                val csvContent = buildString {
                    appendLine("ECG波形视图数据 (2.5秒显示窗口)")
                    appendLine("导出时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())}")
                    appendLine("数据统计:")
                    appendLine("- 数据点数量: ${stats["dataPoints"]}")
                    appendLine("- 最小值: ${stats["minValue"]}")
                    appendLine("- 最大值: ${stats["maxValue"]}")
                    appendLine("- 数据范围: ${stats["range"]}")
                    appendLine("- 采样率: 250Hz")
                    appendLine("- 时间窗口: 2.5秒")
                    appendLine()
                    appendLine("时间(ms),数据点,ECG值")
                    
                    val sampleInterval = 4L // 4ms per sample (250Hz)
                    data.forEachIndexed { index, value ->
                        val timeMs = index * sampleInterval
                        appendLine("$timeMs,$index,$value")
                    }
                }
                
                val file = saveFileToExternalStorage(fileName, csvContent)
                if (file != null) {
                    runOnUiThread {
                        updateStatus("✅ 波形视图数据已导出: ${file.name}")
                    }
                } else {
                    runOnUiThread {
                        updateStatus("❌ 导出波形视图数据失败")
                    }
                }
                
            } catch (e: Exception) {
                Log.e("MainActivity", "导出波形视图数据失败: ${e.message}", e)
                runOnUiThread {
                    updateStatus("❌ 导出波形视图数据失败: ${e.message}")
                }
            }
        }.start()
    }
    
    /**
     * 导出所有图表数据
     */
    private fun exportAllChartData(
        waveformData: List<Float>,
        waveformStats: Map<String, Any>
    ) {
        Thread {
            try {
                if (waveformData.isEmpty()) {
                    runOnUiThread {
                        updateStatus("❌ 没有图表数据可以导出")
                    }
                    return@Thread
                }

                val timestamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.getDefault()).format(java.util.Date())
                val fileName = "ECG_AllChartData_$timestamp.csv"

                val csvContent = buildString {
                    appendLine("ECG图表数据完整导出")
                    appendLine("导出时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())}")
                    appendLine("采样率: 250Hz")
                    appendLine()

                    // 波形视图数据
                    appendLine("=== 波形视图数据 (2.5秒窗口) ===")
                    appendLine("数据点数量: ${waveformStats["dataPoints"]}")
                    appendLine("最小值: ${waveformStats["minValue"]}")
                    appendLine("最大值: ${waveformStats["maxValue"]}")
                    appendLine("数据范围: ${waveformStats["range"]}")
                    appendLine()
                    appendLine("时间(ms),数据点,波形ECG值")

                    val sampleInterval = 4L // 4ms per sample (250Hz)
                    waveformData.forEachIndexed { index, value ->
                        val timeMs = index * sampleInterval
                        appendLine("$timeMs,$index,$value")
                    }
                }

                val file = saveFileToExternalStorage(fileName, csvContent)
                if (file != null) {
                    runOnUiThread {
                        updateStatus("✅ 所有图表数据已导出: ${file.name}")
                    }
                } else {
                    runOnUiThread {
                        updateStatus("❌ 导出所有图表数据失败")
                    }
                }

            } catch (e: Exception) {
                Log.e("MainActivity", "导出所有图表数据失败: ${e.message}", e)
                runOnUiThread {
                    updateStatus("❌ 导出所有图表数据失败: ${e.message}")
                }
            }
        }.start()
    }
    
    /**
     * 导出图表统计信息
     */
    private fun exportChartStats(waveformStats: Map<String, Any>) {
        Thread {
            try {
                val timestamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.getDefault()).format(java.util.Date())
                val fileName = "ECG_ChartStats_$timestamp.txt"
                
                val statsContent = buildString {
                    appendLine("ECG图表统计信息")
                    appendLine("导出时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date())}")
                    appendLine("=".repeat(50))
                    appendLine()
                    
                    appendLine("波形视图统计 (2.5秒窗口):")
                    appendLine("- 数据点数量: ${waveformStats["dataPoints"]}")
                    appendLine("- 最小值: ${waveformStats["minValue"]}")
                    appendLine("- 最大值: ${waveformStats["maxValue"]}")
                    appendLine("- 数据范围: ${waveformStats["range"]}")
                    appendLine("- 是否有数据: ${waveformStats["isDataAvailable"]}")
                    appendLine("- 采样率: 250Hz")
                    appendLine("- 时间窗口: 2.5秒")
                    appendLine()

                    appendLine("数据质量评估:")
                    val waveformRange = waveformStats["range"] as Float

                    when {
                        waveformRange > 100f -> appendLine("- 波形视图: 信号强度良好")
                        waveformRange > 50f -> appendLine("- 波形视图: 信号强度中等")
                        else -> appendLine("- 波形视图: 信号强度较弱")
                    }
                }
                
                val file = saveFileToExternalStorage(fileName, statsContent)
                if (file != null) {
                    runOnUiThread {
                        updateStatus("✅ 图表统计信息已导出: ${file.name}")
                    }
                } else {
                    runOnUiThread {
                        updateStatus("❌ 导出图表统计信息失败")
                    }
                }
                
            } catch (e: Exception) {
                Log.e("MainActivity", "导出图表统计信息失败: ${e.message}", e)
                runOnUiThread {
                    updateStatus("❌ 导出图表统计信息失败: ${e.message}")
                }
            }
        }.start()
    }
    
    /**
     * 显示文件分享对话框
     */
    private fun showFileShareDialog(file: File, fileType: String) {
        Log.d("MainActivity", "显示文件分享对话框: ${file.absolutePath}")

        try {
            // 使用更简单可靠的对话框实现
            val builder = androidx.appcompat.app.AlertDialog.Builder(this, androidx.appcompat.R.style.Theme_AppCompat_Light_Dialog_Alert)
            builder.setTitle("📤 $fileType 已导出")
            builder.setMessage("文件路径: ${file.absolutePath}\n文件大小: ${file.length()} bytes\n\n请选择操作:")

            // 设置正面按钮 - 分享文件
            builder.setPositiveButton("📤 分享文件") { dialog, which ->
                Log.d("MainActivity", "用户点击分享文件按钮")
                dialog.dismiss()
                shareFile(file, fileType)
            }

            // 设置中性按钮 - 仅保存
            builder.setNeutralButton("💾 仅保存") { dialog, which ->
                Log.d("MainActivity", "用户点击仅保存按钮")
                dialog.dismiss()
                updateStatus("✅ 文件已保存到: ${file.absolutePath}")
                Toast.makeText(this, "文件已保存", Toast.LENGTH_SHORT).show()
            }

            // 设置负面按钮 - 取消
            builder.setNegativeButton("取消") { dialog, which ->
                Log.d("MainActivity", "用户点击取消按钮")
                dialog.dismiss()
                updateStatus("分享已取消")
            }

            builder.setCancelable(true)

            val dialog = builder.create()

            // 确保对话框在显示时获得焦点
            dialog.setOnShowListener {
                Log.d("MainActivity", "分享对话框显示成功")
                // 添加Toast提示
                Toast.makeText(this, "请选择分享方式", Toast.LENGTH_SHORT).show()

                // 强制请求焦点
                dialog.window?.setFlags(
                    android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                )
                dialog.window?.clearFlags(android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
            }

            // 在UI线程中显示对话框
            runOnUiThread {
                dialog.show()
                Log.d("MainActivity", "分享对话框已显示")
            }

        } catch (e: Exception) {
            Log.e("MainActivity", "显示分享对话框失败: ${e.message}", e)
            updateStatus("❌ 显示分享对话框失败: ${e.message}")

            // 如果对话框显示失败，至少告诉用户文件位置
            Toast.makeText(this, "分享对话框显示失败，文件已保存到本地", Toast.LENGTH_LONG).show()
            updateStatus("💡 文件位置: ${file.absolutePath}")

            // 尝试直接分享文件作为备用方案
            try {
                Log.d("MainActivity", "尝试直接分享文件")
                shareFile(file, fileType)
            } catch (shareException: Exception) {
                Log.e("MainActivity", "备用分享也失败: ${shareException.message}", shareException)
            }
        }
    }

    /**
     * 分享文件
     */
    private fun shareFile(file: File, fileType: String) {
        Log.d("MainActivity", "开始分享文件: ${file.absolutePath}")

        try {
            // 检查文件是否存在
            if (!file.exists()) {
                Log.e("MainActivity", "文件不存在: ${file.absolutePath}")
                updateStatus("❌ 文件不存在，无法分享")
                Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show()
                return
            }

            Log.d("MainActivity", "文件存在，大小: ${file.length()} bytes")

            // 获取正确的authorities
            val authorities = "${packageName}.fileprovider"
            Log.d("MainActivity", "FileProvider authorities: $authorities")

            val uri = FileProvider.getUriForFile(
                this,
                authorities,
                file
            )
            Log.d("MainActivity", "FileProvider URI: $uri")

            val intent = Intent(Intent.ACTION_SEND).apply {
                type = "text/csv"  // 指定为CSV文件类型
                putExtra(Intent.EXTRA_STREAM, uri)
                putExtra(Intent.EXTRA_SUBJECT, fileType + " - " + file.name)
                putExtra(Intent.EXTRA_TEXT, "分享导出的" + fileType + "文件")
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            }

            // 检查是否有应用可以处理这个Intent
            val packageManager = packageManager
            val resolveInfoList = packageManager.queryIntentActivities(intent, 0)
            Log.d("MainActivity", "找到 ${resolveInfoList.size} 个可以处理分享的应用")

            if (resolveInfoList.isEmpty()) {
                Log.e("MainActivity", "没有应用可以处理分享Intent")
                updateStatus("❌ 没有找到可以分享的应用")
                Toast.makeText(this, "没有找到可以分享的应用", Toast.LENGTH_SHORT).show()

                // 显示文件位置作为备用
                updateStatus("💡 文件已保存到: ${file.absolutePath}")
                return
            }

            // 使用Intent.createChooser确保用户可以选择应用
            val chooser = Intent.createChooser(intent, "分享" + fileType + "文件")

            Log.d("MainActivity", "启动分享Intent")
            startActivity(chooser)

            updateStatus("📤 正在分享" + fileType + "文件...")
            Log.d("MainActivity", "分享Intent已启动")

            // 添加Toast提示
            Toast.makeText(this, "正在打开分享应用...", Toast.LENGTH_SHORT).show()

        } catch (e: Exception) {
            Log.e("MainActivity", "分享文件失败: ${e.message}", e)
            updateStatus("❌ 分享文件失败: ${e.message}")
            Toast.makeText(this, "分享失败: ${e.message}", Toast.LENGTH_SHORT).show()

            // 提供备用方案
            updateStatus("💡 提示: 文件已保存到 ${file.absolutePath}")
        }
    }


    /**
     * 保存文件到外部存储
     */
    private fun saveFileToExternalStorage(fileName: String, content: String): File? {
        return try {
            val externalDir = getExternalFilesDir(null)
            Log.d("MainActivity", "外部存储目录: $externalDir")

            val file = File(externalDir, fileName)
            Log.d("MainActivity", "保存文件到: ${file.absolutePath}")

            file.writeText(content)
            Log.d("MainActivity", "文件保存成功，大小: ${file.length()} 字节")

            file
        } catch (e: Exception) {
            Log.e("MainActivity", "保存文件失败: ${e.message}", e)
            null
        }
    }
    
    /**
     * 显示单图表全屏模式
     */
    private fun showSingleChartFullscreen(chartIndex: Int, chart: DynamicChartView) {
        val deviceType = dynamicChartManager.getCurrentDeviceType()
        if (deviceType == null) {
            updateStatus("❌ 设备类型未知，无法进入全屏模式")
            return
        }
        
        // 创建全屏Intent
        val intent = Intent(this, FullscreenChartActivity::class.java)
        
        // 传递单个图表数据
        val chartData = mapOf(
            "title" to "通道${chartIndex + 1}",
            "data" to chart.getCurrentData(),
            "stats" to chart.getDataStats(),
            "deviceType" to deviceType.name,
            "chartIndex" to chartIndex
        )
        
        intent.putExtra("chartData", arrayOf(chartData))
        intent.putExtra("deviceType", deviceType.name)
        intent.putExtra("isSingleChart", true)
        intent.putExtra("chartIndex", chartIndex)
        
        // 设置全屏Activity的数据管理器引用
        FullscreenChartActivity.setMainDataManager(dataManager)
        
        // 使用简单的startActivity启动全屏模式
        startActivity(intent)
        updateStatus("📺 通道${chartIndex + 1} 已进入全屏模式")
    }
    
 }