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
import android.widget.TextView
import android.widget.EditText
import android.widget.Spinner
import android.widget.ArrayAdapter
import androidx.appcompat.widget.SwitchCompat
import androidx.core.widget.NestedScrollView
import android.widget.LinearLayout

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

    companion object {
        private const val PERMISSION_REQUEST_CODE = 1001
        
        // 根据Android版本动态确定所需权限
        private val REQUIRED_PERMISSIONS: Array<String> = when {
            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
                )
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
                // Android 6-11 只需要位置权限
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                )
            }
            else -> {
                // Android 5.1及以下不需要动态权限
                emptyArray()
            }
        }
        
        // 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()
        val androidVersion = android.os.Build.VERSION.RELEASE
        val apiLevel = android.os.Build.VERSION.SDK_INT
        
        updateStatus("📱 Android $androidVersion (API $apiLevel) - 就绪")
        updateStatus("✅ 蓝牙管理器已初始化")
        updateStatus("📋 权限状态:")
        for (line in permissionStatus.split("\n")) {
            updateStatus("   $line")
        }
        updateStatus("🎯 准备连接蓝牙设备")
        updateStatus("💡 点击'连接蓝牙'按钮开始扫描")

        // 确保图表容器可见
        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() {
        // 检查当前按钮状态
        val currentButtonText = binding.bluetoothButton.text.toString()
        
        when {
            bluetoothConnected -> {
                // 已连接，断开连接
                bluetoothManager.disconnect()
                bluetoothConnected = false
                binding.bluetoothButton.text = "连接蓝牙"
                binding.bluetoothButton.setBackgroundColor(Color.parseColor("#4CAF50"))
                updateStatus("蓝牙已断开")
            }
            currentButtonText == "扫描中..." -> {
                // 正在扫描，停止扫描
                stopBluetoothScan()
            }
            currentButtonText == "扫描失败" || currentButtonText == "权限检查中..." -> {
                // 重试扫描
                retryBluetoothScan()
            }
            else -> {
                // 开始新扫描
                startNewBluetoothScan()
            }
        }
    }
    
    private fun startNewBluetoothScan() {
        updateStatus("🚀 开始蓝牙连接流程...")
        updateStatus("📱 检测到Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
        
        // Android 15特殊提示
        if (Build.VERSION.SDK_INT >= 35) {
            updateStatus("🔔 Android 15检测：确保已授予所有必要权限")
        }
        
        // 检查权限后再开始扫描
        when {
            Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> {
                // Android 6.0以下不需要动态权限
                updateStatus("✅ Android ${Build.VERSION.RELEASE} 无需动态权限")
                startBluetoothScan()
            }
            checkAndRequestPermissions() -> {
                // 权限检查通过，开始扫描
                updateStatus("🎯 权限检查通过，正在启动蓝牙扫描...")
                startBluetoothScan()
            }
            else -> {
                // 权限检查未通过或正在请求权限
                updateStatus("⏳ 权限检查中，请稍候...")
                updateStatus("💡 Android ${Build.VERSION.RELEASE} 权限指引：")
                if (Build.VERSION.SDK_INT >= 35) {
                    updateStatus("   • 可能的权限：蓝牙扫描、蓝牙连接、位置")
                    updateStatus("   • 如果权限对话框没有出现，请手动进入应用设置→权限")
                } else {
                    updateStatus("   • 需要的权限：蓝牙扫描、蓝牙连接、位置")
                    updateStatus("   • 请在弹出的权限对话框中点击 允许")
                }
                binding.bluetoothButton.text = "权限检查中..."
                binding.bluetoothButton.setBackgroundColor(Color.parseColor("#FF9800"))
            }
        }
    }
    
    private fun stopBluetoothScan() {
        try {
            bluetoothManager.stopScan()
            binding.bluetoothButton.text = "重新扫描"
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#4CAF50"))
            updateStatus("⏹️ 蓝牙扫描已停止")
            updateStatus("💡 点击'重新扫描'按钮重新开始扫描")
        } catch (e: Exception) {
            Log.e("MainActivity", "停止蓝牙扫描失败: ${e.message}", e)
            updateStatus("❌ 停止扫描失败: ${e.message}")
        }
    }
    
    private fun retryBluetoothScan() {
        binding.bluetoothButton.text = "重试扫描"
        binding.bluetoothButton.setBackgroundColor(Color.parseColor("#FF9800"))
        updateStatus("🔄 重试扫描...")
        startNewBluetoothScan()
    }

    private fun startBluetoothScan() {
        try {
            updateStatus("🚀 准备启动蓝牙扫描...")
            bluetoothManager.startScan()
            binding.bluetoothButton.text = "扫描中..."
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#FF9800"))
            updateStatus("✅ 蓝牙扫描已启动")
            updateStatus("⏱️ 扫描时长15秒，请稍候...")
            
            Log.d("MainActivity", "✅ 蓝牙扫描启动成功")
            
            // 15秒后如果还在扫描，显示提示
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                if (binding.bluetoothButton.text == "扫描中...") {
                    updateStatus("💡 扫描时间较长，可能附近没有BLE设备")
                    updateStatus("🔄 可以尝试停止后重新扫描")
                }
            }, 15000)
            
        } catch (e: Exception) {
            Log.e("MainActivity", "启动蓝牙扫描失败: ${e.message}", e)
            updateStatus("❌ 蓝牙扫描启动失败: ${e.message}")
            binding.bluetoothButton.text = "扫描失败"
            binding.bluetoothButton.setBackgroundColor(Color.parseColor("#F44336"))
        }
    }

    private fun checkAndRequestPermissions(): Boolean {
        val missingPermissions = mutableListOf<String>()
        val grantedPermissions = mutableListOf<String>()
        
        Log.d("MainActivity", "=== 权限检查开始 ===")
        Log.d("MainActivity", "Android版本: ${Build.VERSION.SDK_INT}")
        Log.d("MainActivity", "需要检查的权限: ${REQUIRED_PERMISSIONS.contentToString()}")
        
        updateStatus("🔍 检查蓝牙权限...")
        updateStatus("📱 Android版本: ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
        
        for (permission in REQUIRED_PERMISSIONS) {
            val permissionStatus = ContextCompat.checkSelfPermission(this, permission)
            val permissionName = permission.split(".").last()
            
            Log.d("MainActivity", "权限 $permissionName 状态: $permissionStatus")
            
            if (permissionStatus == PackageManager.PERMISSION_GRANTED) {
                grantedPermissions.add(permissionName)
                updateStatus("✅ 已授权: $permissionName")
            } else {
                missingPermissions.add(permission)
                updateStatus("❌ 缺少权限: $permissionName")
            }
        }
        
        // 显示权限状态
        if (grantedPermissions.isNotEmpty()) {
            updateStatus("✅ 已授予权限: ${grantedPermissions.joinToString(", ")}")
        }
        
        if (missingPermissions.isNotEmpty()) {
            updateStatus("💡 正在请求权限...")
            
            try {
                ActivityCompat.requestPermissions(
                    this,
                    missingPermissions.toTypedArray(),
                    PERMISSION_REQUEST_CODE
                )
                updateStatus("📋 权限请求对话框已弹出")
                return false
            } catch (e: Exception) {
                Log.e("MainActivity", "请求权限失败: ${e.message}", e)
                updateStatus("❌ 权限请求失败: ${e.message}")
                return false
            }
        }
        
        updateStatus("✅ 所有必要权限已授予")
        Log.d("MainActivity", "=== 权限检查完成：通过 ===")
        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 -> {
                Log.d("MainActivity", "=== 权限请求结果回调 ===")
                Log.d("MainActivity", "请求的权限数量: ${permissions.size}")
                Log.d("MainActivity", "权限: ${permissions.contentToString()}")
                Log.d("MainActivity", "结果: ${grantResults.contentToString()}")
                
                val grantedPermissions = mutableListOf<String>()
                val deniedPermissions = mutableListOf<String>()
                
                updateStatus("📋 权限请求结果:")
                
                for (i in permissions.indices) {
                    val permission = permissions[i]
                    val granted = grantResults[i] == PackageManager.PERMISSION_GRANTED
                    val permissionName = permission.split(".").last()
                    
                    Log.d("MainActivity", "权限 $permissionName: ${if (granted) "已授予" else "被拒绝"}")
                    
                    if (granted) {
                        grantedPermissions.add(permissionName)
                        updateStatus("✅ $permissionName: 已授权")
                    } else {
                        deniedPermissions.add(permissionName)
                        updateStatus("❌ $permissionName: 被拒绝")
                    }
                }
                
                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("📡 正在启动蓝牙扫描...")
                    binding.bluetoothButton.text = "权限通过"
                    binding.bluetoothButton.setBackgroundColor(Color.parseColor("#4CAF50"))
                    startBluetoothScan()
                } else {
                    updateStatus("⚠️ 部分权限被拒绝，蓝牙功能可能受限")
                    updateStatus("💡 Android ${Build.VERSION.RELEASE} 解决方案：")
                    updateStatus("   • 进入设置 → 应用 → ${getString(android.R.string.unknownName)} → 权限")
                    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.d("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>?



    
    
    
    // 实时数据回调实现
    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) }}")
        }
        
        val currentTime = System.currentTimeMillis()
        
        // 传输速率限制：防止过高频率导致闪退
        if (lastDataTime > 0) {
            val timeDiff = currentTime - lastDataTime
            if (timeDiff < 20) { // 小于20ms间隔，跳过处理
                Log.w("MainActivity", "数据传输频率过高(${timeDiff}ms)，跳过本次处理")
                return
            }
        }
        
        // 更新数据统计
        receivedDataCount += data.size
        if (lastDataTime > 0) {
            val timeDiff = currentTime - lastDataTime
            if (timeDiff > 0) {
                dataRate = (data.size * 1000f) / timeDiff // 字节/秒
                
                // 如果传输速率超过阈值，执行紧急处理
                if (dataRate > 15000) { // 超过15KB/s
                    Log.w("MainActivity", "传输速率过高(${String.format("%.1f", dataRate)}字节/秒)，执行紧急清理")
                    dataManager.checkMemoryUsage()
                }
            }
        }
        lastDataTime = currentTime
        
        // 定期检查内存使用情况，防止闪退
        if (currentTime - lastDataTime > 5000) { // 每5秒检查一次
            dataManager.checkMemoryUsage()
        }
        
        
        // UI更新频率限制：防止过高频率导致UI阻塞
        val shouldUpdateUI = currentTime - lastDataStatusTime > 100 // 最多每100ms更新一次UI
        
        if (shouldUpdateUI) {
            runOnUiThread {
                binding.dynamicChartContainer.visibility = View.VISIBLE
                
                // 如果数据处理还没启动，自动启动
                if (!dataProcessingStarted) {
                    startDataProcessing()
                    updateStatus("检测到数据，自动启动数据处理")
                }
                
                // 减少数据接收状态更新频率
                if (currentTime - lastDataStatusTime > 2000) { // 改为2秒内只更新一次状态
                    updateStatus("接收到蓝牙数据: ${data.size} 字节，图表已显示")
                    updateDataStatistics()
                    lastDataStatusTime = currentTime
                }
            }
        }
        
        // 在后台线程处理数据，避免阻塞UI
        Thread {
            try {
                Log.d("MainActivity", "开始处理蓝牙数据: ${data.size} 字节")
                
                // 将蓝牙数据传递给DataManager处理
                dataManager.onBleNotify(data)
                
                Log.d("MainActivity", "蓝牙数据处理完成")
                
                
            } 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(
            "轻迅协议指令"
        )

        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("选择指令类型")
            .setItems(commands) { _, which ->
                when (which) {
                    0 -> showQingXunProtocolDialog()
                }
            }
            .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 -> showStimSwitchDialog()
                    3 -> showPowerLineFilterDialog()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 显示通用指令对话框
     */
    
    /**
     * 发送轻迅协议开启采集指令
     */
    private fun sendQingXunStartCollection() {
        val options = arrayOf(
            "立即开启"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("开启采集")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> {
                        bluetoothManager.startCollection(0L) // 立即开启
                        updateStatus("发送轻迅协议开启采集指令（立即），准备接收数据...")
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 发送轻迅协议停止采集指令
     */
    private fun sendQingXunStopCollection() {
        val options = arrayOf(
            "立即停止"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("停止采集")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> {
                        bluetoothManager.stopCollection(0L) // 立即停止
                        updateStatus("发送轻迅协议停止采集指令（立即）")
                    }
                }
            }
            .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 showStimSwitchDialog() {
        val dialogOptions = arrayOf(
            "高级电刺激控制",
            "关闭电刺激"
        )
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("电刺激控制")
            .setItems(dialogOptions) { _, which ->
                when (which) {
                    0 -> showAdvancedStimDialog()        // 高级电刺激控制
                    1 -> {
                        bluetoothManager.stimSwitch(enable = false)
                        updateStatus("发送电刺激关闭指令")
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    /**
     * 高级电刺激控制对话框 - 完整参数版本
     */
    private fun showAdvancedStimDialog() {
        val builder = androidx.appcompat.app.AlertDialog.Builder(this)
        builder.setTitle("高级电刺激控制")
        
        // 创建滚动视图
        val scrollView = androidx.core.widget.NestedScrollView(this)
        
        // 创建输入字段的线性布局
        val layout = android.widget.LinearLayout(this).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(40, 20, 40, 20)
        }
        
        // 启用刺激开关
        val enableSwitch = androidx.appcompat.widget.SwitchCompat(this).apply {
            isChecked = true
        }
        val enableLabel = TextView(this).apply {
            text = "启用刺激"
            textSize = 16f
            setPadding(0, 0, 0, 16)
        }
        layout.addView(enableLabel)
        layout.addView(enableSwitch)
        
        // 基础参数
        val stimTypeInput = createSimpleInputField("刺激类型 (0-15):", "1")
        layout.addView(stimTypeInput)
        
        val intensityInput = createSimpleInputField("强度 (%):", "50")
        layout.addView(intensityInput)
        
        val frequencyInput = createSimpleInputField("频率 (Hz):", "100")
        layout.addView(frequencyInput)
        
        val durationInput = createSimpleInputField("总时长 (秒):", "10")
        layout.addView(durationInput)
        
        // 时间参数
        val restTimeInput = createSimpleInputField("休息时间 (毫秒):", "1000")
        layout.addView(restTimeInput)
        
        val silenceTimeInput = createSimpleInputField("静默时间 (毫秒):", "500")
        layout.addView(silenceTimeInput)
        
        val fadeInTimeInput = createSimpleInputField("缓进时间 (秒):", "2")
        layout.addView(fadeInTimeInput)
        
        val holdTimeInput = createSimpleInputField("保持时间 (秒):", "5")
        layout.addView(holdTimeInput)
        
        val fadeOutTimeInput = createSimpleInputField("缓出时间 (秒):", "2")
        layout.addView(fadeOutTimeInput)
        
        // 添加提示信息
        val hintText = TextView(this).apply {
            text = "💡 提示：保持时间建议 = 总时长 - 缓进时间 - 缓出时间"
            textSize = 12f
            setTextColor(ContextCompat.getColor(this@MainActivity, android.R.color.darker_gray))
            setPadding(0, 16, 0, 0)
        }
        layout.addView(hintText)
        
        scrollView.addView(layout)
        builder.setView(scrollView)
        
        builder.setPositiveButton("开始刺激") { dialog, _ ->
            try {
                val enable = enableSwitch.isChecked
                val stimTypeChild = stimTypeInput.getChildAt(1) as EditText
                val intensityChild = intensityInput.getChildAt(1) as EditText
                val frequencyChild = frequencyInput.getChildAt(1) as EditText
                val durationChild = durationInput.getChildAt(1) as EditText
                val restTimeChild = restTimeInput.getChildAt(1) as EditText
                val silenceTimeChild = silenceTimeInput.getChildAt(1) as EditText
                val fadeInTimeChild = fadeInTimeInput.getChildAt(1) as EditText
                val holdTimeChild = holdTimeInput.getChildAt(1) as EditText
                val fadeOutTimeChild = fadeOutTimeInput.getChildAt(1) as EditText
                
                val stimType = stimTypeChild.text.toString().toInt().coerceIn(0, 15)
                val intensity = intensityChild.text.toString().toInt().coerceIn(1, 100)
                val frequency = frequencyChild.text.toString().toInt().coerceIn(1, 200)
                val totalDuration = durationChild.text.toString().toInt().coerceIn(1, 3600) * 1000
                val restTime = restTimeChild.text.toString().toInt().coerceIn(100, 10000)
                val silenceTime = silenceTimeChild.text.toString().toInt().coerceIn(100, 5000)
                val fadeInTime = fadeInTimeChild.text.toString().toInt().coerceIn(1, 30)
                val holdTime = holdTimeChild.text.toString().toInt().coerceIn(1, 300)
                val fadeOutTime = fadeOutTimeChild.text.toString().toInt().coerceIn(1, 30)
                
                bluetoothManager.stimSwitch(
                    enable = enable,
                    stimType = stimType,
                    intensity = intensity,
                    frequency = frequency,
                    totalDuration = totalDuration,
                    restTime = restTime,
                    silenceTime = silenceTime,
                    fadeInTime = fadeInTime,
                    holdTime = holdTime,
                    fadeOutTime = fadeOutTime
                )
                
                updateStatus("发送高级电刺激控制指令:")
                updateStatus("  类型: $stimType, 强度: $intensity%, 频率: ${frequency}Hz")
                updateStatus("  总时长: ${totalDuration/1000}s, 保持: ${holdTime}s")
                updateStatus("  休息: ${restTime}ms, 静默: ${silenceTime}ms")
                updateStatus("  缓进/出: ${fadeInTime}s/${fadeOutTime}s")
                
            } catch (e: NumberFormatException) {
                updateStatus("❌ 参数输入错误，请检查数值格式")
            } catch (e: Exception) {
                updateStatus("❌ 发送失败: ${e.message}")
            }
            dialog.dismiss()
        }
        builder.setNegativeButton("取消", null)
        builder.show()
    }
    
    /**
     * 创建简单的输入字段
     */
    private fun createSimpleInputField(label: String, defaultValue: String): LinearLayout {
        val layout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(0, 16, 0, 8)
        }
        
        val labelView = TextView(this).apply {
            text = label
            textSize = 14f
        }
        
        val inputView = EditText(this).apply {
            setText(defaultValue)
            hint = defaultValue
            inputType = android.text.InputType.TYPE_CLASS_NUMBER
            textSize = 16f
        }
        
        layout.addView(labelView)
        layout.addView(inputView)
        
        return layout
    }

    private fun clearAllData() {
        // 清空动态图表数据
        dynamicChartManager.clearAllCharts()
        
        // 清空数据管理器
        dataManager.cleanupBuffer()
        
        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 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} 已进入全屏模式")
    }
    
 }