package com.example.cmake_project_test

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import com.example.cmake_project_test.databinding.ActivityFullscreenBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import type.SensorData

/**
 * 全屏图表显示Activity
 * 支持ECG和PPG的不同Y轴范围设置
 */
class FullscreenChartActivity : AppCompatActivity(), DataManager.RealTimeDataCallback, NativeMethodCallback {
    
    private lateinit var binding: ActivityFullscreenBinding
    private var fullscreenChartManager: DynamicChartManager? = null
    private var deviceType: String = "未知设备"
    private var isSingleChart = false
    private var chartIndex = 0
    
    // 滤波器管理器
    private var filterManager: FullscreenFilterManager? = null

    // Activity退出标志
    private var isExiting = false
    
    // 数据回调清理标志
    private var callbackRemoved = false
    


    
    companion object {
        // 静态数据管理器引用，用于接收MainActivity的数据
        private var mainDataManager: DataManager? = null
        
        fun setMainDataManager(dataManager: DataManager) {
            mainDataManager = dataManager
            Log.d("FullscreenChartActivity", "设置主数据管理器引用")
        }
        
        fun clearMainDataManager() {
            if (mainDataManager != null) {
                Log.d("FullscreenChartActivity", "清理主数据管理器引用")
                Log.d("FullscreenChartActivity", "注意：这只是清理引用，MainActivity的DataManager应该继续运行")
                mainDataManager = null
            } else {
                Log.d("FullscreenChartActivity", "主数据管理器引用已为空，跳过清理")
            }
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置全局异常处理器
        setupGlobalExceptionHandler()
        
        // 设置全屏模式
        setupFullscreen()
        
        binding = ActivityFullscreenBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 初始化全屏图表管理器（避免重复初始化）
        if (fullscreenChartManager == null) {
            fullscreenChartManager = DynamicChartManager(
                context = this,
                chartsContainer = binding.fullscreenChartsContainer,
                chartTitle = null // 全屏模式下不需要标题
            )
        }
        
        // 注册为数据回调接收器
        val dataManager = mainDataManager
        if (dataManager != null) {
            dataManager.addRealTimeCallback(this)
            Log.d("FullscreenChartActivity", "已注册为数据回调接收器")
        } else {
            Log.w("FullscreenChartActivity", "主数据管理器为空，无法注册回调")
        }
        
        // 获取传递的数据
        val chartDataArray = intent.getSerializableExtra("chartData") as? Array<Map<String, Any>>
        deviceType = intent.getStringExtra("deviceType") ?: "未知设备"
        isSingleChart = intent.getBooleanExtra("isSingleChart", false)
        chartIndex = intent.getIntExtra("chartIndex", 0)
        
        if (chartDataArray != null) {
            setupFullscreenCharts(chartDataArray)
        } else {
            Log.e("FullscreenChartActivity", "没有接收到图表数据")
            finish()
        }
        
        // 设置退出全屏按钮
        binding.exitFullscreenButton.setOnClickListener {
            exitFullscreen()
        }
        
        // 初始化心率和血氧显示
        setupVitalSignsDisplay()
        
        // 初始化滤波器管理器
        setupFilterManager()

    }





    /**
     * 检查内存泄漏迹象
     */
    private fun checkForMemoryLeaks_DISABLED(currentMemoryPercent: Double) {
        try {
            // 如果内存使用率持续高于75%且没有明显的数据积累，可能是内存泄漏
            val chartDataCount = fullscreenChartManager?.let { manager ->
                manager.getCharts().sumOf { chart -> chart.getDataPointCount() }
            } ?: 0

            val filterCacheCount = filterManager?.let { fm ->
                // 简单估算缓存大小
                try {
                    val originalCacheSize = fm.javaClass.getDeclaredField("originalDataCache")
                        .apply { isAccessible = true }
                        .get(fm) as Map<*, *>
                    val filteredCacheSize = fm.javaClass.getDeclaredField("filteredDataCache")
                        .apply { isAccessible = true }
                        .get(fm) as Map<*, *>

                    originalCacheSize.size + filteredCacheSize.size
                } catch (e: Exception) {
                    0
                }
            } ?: 0

            if (currentMemoryPercent > 75.0 && chartDataCount < 5000 && filterCacheCount < 20) {
                Log.w("FullscreenChartActivity", "⚠️ 疑似内存泄漏: 内存使用率${String.format("%.1f", currentMemoryPercent)}%但数据量较少")
                Log.w("FullscreenChartActivity", "图表数据点: $chartDataCount, 滤波缓存: $filterCacheCount")
            }

        } catch (e: Exception) {
            Log.e("FullscreenChartActivity", "内存泄漏检查失败: ${e.message}")
        }
    }

    /**
     * 执行紧急内存清理
     */
    private fun performEmergencyMemoryCleanup_DISABLED() {
        try {
            Log.d("FullscreenChartActivity", "=== 执行紧急内存清理 ===")

            // 清理图表数据
            fullscreenChartManager?.let { chartManager ->
                val charts = chartManager.getCharts()
                var totalCleanedPoints = 0

                charts.forEach { chart ->
                    val currentPoints = chart.getDataPointCount()
                    if (currentPoints > 500) { // 如果数据点超过500个，强制清理到50%
                        val keepPoints = (currentPoints * 0.5).toInt()
                        chart.trimDataToSize(keepPoints)
                        totalCleanedPoints += (currentPoints - keepPoints)
                    }
                }

                if (totalCleanedPoints > 0) {
                    Log.d("FullscreenChartActivity", "紧急清理释放了 $totalCleanedPoints 个数据点")
                }
            }

            // 清理滤波器缓存
            filterManager?.let { fm ->
                try {
                    fm.cleanupMemory()
                } catch (e: Exception) {
                    Log.e("FullscreenChartActivity", "清理滤波器缓存失败: ${e.message}")
                }
            }

            // 强制垃圾回收
            System.gc()
            Log.d("FullscreenChartActivity", "=== 紧急内存清理完成 ===")

        } catch (e: Exception) {
            Log.e("FullscreenChartActivity", "紧急内存清理失败: ${e.message}")
        }
    }


    
    /**
     * 设置心率和血氧显示
     */
    private fun setupVitalSignsDisplay() {
        // 初始化心率和血氧显示区域
        binding.heartRateValue.text = "--"
        binding.spo2Value.text = "--"
        binding.temperatureValue.text = "--"
        
        // 设置标签
        binding.heartRateLabel.text = "心率 (bpm)"
        binding.spo2Label.text = "血氧 (%)"
        binding.temperatureLabel.text = "体温 (°C)"
        
        Log.d("FullscreenChartActivity", "心率和血氧显示区域已初始化")
    }
    
    /**
     * 初始化滤波器管理器
     */
    private fun setupFilterManager() {
        try {
            // 避免重复初始化滤波器管理器
            if (filterManager == null) {
                filterManager = FullscreenFilterManager(
                    context = this,
                    scope = lifecycleScope,
                    dataManager = mainDataManager,
                    chartManager = fullscreenChartManager,
                    deviceType = deviceType
                )
            }

            // 初始化UI组件
            filterManager?.initializeUI(filterBtn = binding.filterButton)

        } catch (e: Exception) {
            Log.e("FullscreenChartActivity", "初始化滤波器管理器失败: ${e.message}", e)
        }
    }
    
    /**
     * 更新心率和血氧显示
     */
    private fun updateVitalSignsDisplay(additionalData: type.SensorData.AdditionalData?) {
        if (additionalData == null) return
        
        runOnUiThread {
            try {
                // 更新心率显示
                val heartRate = additionalData.hr
                if (heartRate > 0) {
                    binding.heartRateValue.text = heartRate.toString()
                    binding.heartRateValue.setTextColor(android.graphics.Color.GREEN)
                } else {
                    binding.heartRateValue.text = "--"
                    binding.heartRateValue.setTextColor(android.graphics.Color.GRAY)
                }
                
                // 更新血氧显示
                val spo2 = additionalData.spo2
                if (spo2 > 0) {
                    binding.spo2Value.text = spo2.toString()
                    binding.spo2Value.setTextColor(android.graphics.Color.BLUE)
                } else {
                    binding.spo2Value.text = "--"
                    binding.spo2Value.setTextColor(android.graphics.Color.GRAY)
                }
                
                // 更新体温显示
                val temperature = additionalData.temperature
                if (temperature > 0) {
                    binding.temperatureValue.text = String.format("%.1f", temperature)
                    binding.temperatureValue.setTextColor(android.graphics.Color.RED)
                } else {
                    binding.temperatureValue.text = "--"
                    binding.temperatureValue.setTextColor(android.graphics.Color.GRAY)
                }
                
                Log.d("FullscreenChartActivity", "更新生命体征: HR=$heartRate, SpO2=$spo2, Temp=$temperature")
                
            } catch (e: Exception) {
                Log.e("FullscreenChartActivity", "更新生命体征显示失败: ${e.message}")
            }
        }
    }
    
    /**
     * 设置全局异常处理器
     */
    private fun setupGlobalExceptionHandler() {
        val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler { thread, exception ->
            Log.e("FullscreenChartActivity", "=== 未捕获的异常 ===")
            Log.e("FullscreenChartActivity", "线程: ${thread.name}")
            Log.e("FullscreenChartActivity", "异常类型: ${exception.javaClass.simpleName}")
            Log.e("FullscreenChartActivity", "异常消息: ${exception.message}")
            Log.e("FullscreenChartActivity", "异常堆栈: ${exception.stackTraceToString()}")

            // 检查是否是JNI相关异常
            if (exception.message?.contains("JNI") == true ||
                exception.stackTrace.any { it.className.contains("native") || it.methodName.contains("native") }) {
                Log.e("FullscreenChartActivity", "检测到JNI相关异常，可能需要检查native代码")
            }

            // 检查是否是内存相关异常
            if (exception is OutOfMemoryError) {
                Log.e("FullscreenChartActivity", "检测到内存不足异常，建议优化内存使用")
            }

            // 检查是否是数组越界异常
            if (exception is IndexOutOfBoundsException) {
                Log.e("FullscreenChartActivity", "检测到数组越界异常，可能需要检查数据访问逻辑")
            }

            // 调用默认处理器
            try {
                defaultHandler?.uncaughtException(thread, exception)
            } catch (e: Exception) {
                Log.e("FullscreenChartActivity", "默认异常处理器也失败了: ${e.message}")
                // 最后手段：强制重启应用
                android.os.Process.killProcess(android.os.Process.myPid())
            }
        }
    }
    
    /**
     * 设置全屏模式
     */
    private fun setupFullscreen() {
        // 隐藏状态栏和导航栏
        window.decorView.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_FULLSCREEN
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        )
        
        // 保持屏幕常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        
        // 设置全屏标题
        supportActionBar?.hide()
    }
    
    /**
     * 设置全屏图表
     */
    private fun setupFullscreenCharts(chartDataArray: Array<Map<String, Any>>) {
        Log.d("FullscreenChartActivity", "设置全屏图表，设备类型: $deviceType，图表数量: ${chartDataArray.size}")
        
        // 根据设备类型创建图表
        val dataType = try {
            SensorData.DataType.valueOf(deviceType)
        } catch (e: IllegalArgumentException) {
            Log.w("FullscreenChartActivity", "未知设备类型: $deviceType，使用默认类型")
            SensorData.DataType.PW_ECG_SL // 默认使用单导联心电
        }
        fullscreenChartManager?.createChartsForDevice(dataType)
        
        // 设置全屏图表管理器的事件监听器
        fullscreenChartManager?.setOnChartFullscreenClickListener { chartIndex, chart ->
            // 在全屏模式下不需要处理全屏按钮点击
        }
        
        // 设置自定义Y轴范围和全屏布局
        val charts = fullscreenChartManager?.getCharts() ?: emptyList()
        for (i in charts.indices) {
            val chart = charts[i]
            
            // 设置全屏模式
            chart.setFullscreenMode(true)
            
            // 设置全屏布局参数
            val layoutParams = android.widget.LinearLayout.LayoutParams(
                android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                android.widget.LinearLayout.LayoutParams.MATCH_PARENT
            ).apply {
                marginStart = 0
                marginEnd = 0
                topMargin = 0
                bottomMargin = 0
            }
            chart.layoutParams = layoutParams
            
            // 根据设备类型设置Y轴范围
            when (deviceType) {
                "ECG_2LEAD",
                "ECG_12LEAD", 
                "PW_ECG_SL" -> {
                    // ECG设备：Y轴范围 -20 到 20
                    chart.setCustomYRange(-20f, 20f)
                    Log.d("FullscreenChartActivity", "设置ECG图表$i Y轴范围: -20 到 20")
                }
                "PPG" -> {
                    // PPG设备：Y轴范围 -2000 到 2000
                    chart.setCustomYRange(-2000f, 2000f)
                    Log.d("FullscreenChartActivity", "设置PPG图表$i Y轴范围: -2000 到 2000")
                }
                else -> {
                    // 其他设备：使用自动范围
                    chart.clearCustomYRange()
                    Log.d("FullscreenChartActivity", "设置图表$i 使用自动Y轴范围")
                }
            }
        }
        
        // 更新图表数据
        val channelData = chartDataArray.map { chartData ->
            @Suppress("UNCHECKED_CAST")
            chartData["data"] as List<Float>
        }
        
        if (channelData.isNotEmpty()) {
            fullscreenChartManager?.updateChartsData(channelData)
            Log.d("FullscreenChartActivity", "已更新全屏图表数据，通道数: ${channelData.size}")
        }
        
        // 全屏模式下不需要更新标题
    }
    
    override fun onResume() {
        super.onResume()
        // 确保全屏模式
        setupFullscreen()

    }

    override fun onPause() {
        super.onPause()
        Log.d("FullscreenChartActivity", "Activity暂停")
    }

    override fun onStop() {
        super.onStop()
        isExiting = true
        Log.d("FullscreenChartActivity", "Activity停止")
    }
    
    override fun onDestroy() {
        try {
            Log.d("FullscreenChartActivity", "开始销毁Activity")
            
            // 设置退出标志，阻止所有回调
            isExiting = true
            
            // 移除数据回调（防止重复移除）
            if (!callbackRemoved) {
                try {
                    mainDataManager?.removeRealTimeCallback(this)
                    callbackRemoved = true
                    Log.d("FullscreenChartActivity", "数据回调已移除")
                } catch (e: Exception) {
                    Log.e("FullscreenChartActivity", "移除数据回调失败: ${e.message}")
                }
            } else {
                Log.d("FullscreenChartActivity", "数据回调已移除，跳过重复移除")
            }
            
            // 清理静态引用
            clearMainDataManager()

            Log.d("FullscreenChartActivity", "Activity销毁完成")

        } catch (e: Exception) {
            Log.e("FullscreenChartActivity", "Activity销毁过程中出现异常: ${e.message}")
        } finally {
            super.onDestroy()
        }
    }
    
    override fun onBackPressed() {
        if (!isFinishing && !isDestroyed) {
            exitFullscreen()
        }
    }
    
    /**
     * 安全退出全屏模式
     */
    private fun exitFullscreen() {
        try {
            Log.d("FullscreenChartActivity", "开始退出全屏模式")
            
            // 立即移除数据回调，防止在finish()后仍有回调执行
            if (!callbackRemoved) {
                try {
                    mainDataManager?.removeRealTimeCallback(this)
                    callbackRemoved = true
                    Log.d("FullscreenChartActivity", "数据回调已移除")
                } catch (e: Exception) {
                    Log.e("FullscreenChartActivity", "移除数据回调失败: ${e.message}")
                }
            } else {
                Log.d("FullscreenChartActivity", "数据回调已移除，跳过重复移除")
            }
            
            // 设置退出标志，阻止所有回调
            isExiting = true

            // 设置结果
            setResult(Activity.RESULT_OK)

            // 使用更安全的方式结束Activity
            if (!isFinishing && !isDestroyed) {
                finish()
            } else {
                Log.w("FullscreenChartActivity", "Activity已经在销毁过程中，跳过finish()")
            }

        } catch (e: Exception) {
            Log.e("FullscreenChartActivity", "退出全屏模式失败: ${e.message}")
            // 如果出错，直接结束
            finish()
        }
    }
    
    
    // 实时数据回调实现 - 从MainActivity接收数据
    override fun onProcessedDataAvailable(channelIndex: Int, processedData: List<Float>) {
        // 检查Activity是否还在运行或正在退出
        if (isFinishing || isDestroyed || isExiting) {
            return
        }

        // 检查资源是否可用
        if (fullscreenChartManager == null || binding == null) {
            return
        }
        
        // 如果是单图表模式，只更新对应的图表
        if (isSingleChart && channelIndex != chartIndex) {
            return
        }
        
        // 检查数据有效性
        if (processedData.isEmpty()) {
            return
        }
        
        runOnUiThread {
            try {
                // 再次检查Activity状态
                if (isFinishing || isDestroyed || isExiting) {
                    Log.d("FullscreenChartActivity", "UI线程中Activity正在销毁，忽略数据回调")
                    return@runOnUiThread
                }
                
                
                // 检查图表管理器是否有效
                val chartManager = fullscreenChartManager
                if (chartManager == null) {
                    Log.w("FullscreenChartActivity", "图表管理器为空，忽略数据回调")
                    return@runOnUiThread
                }
                
                // 通过滤波器管理器处理数据
                val charts = chartManager.getCharts()
                if (charts.isNotEmpty()) {
                    val chart = charts.getOrNull(0)
                    if (chart == null) {
                        Log.e("FullscreenChartActivity", "图表为空，跳过数据处理")
                        return@runOnUiThread
                    }

                    // 再次检查Activity状态，防止在数据处理过程中Activity被销毁
                    if (isFinishing || isDestroyed || isExiting) {
                        Log.d("FullscreenChartActivity", "数据处理过程中Activity状态变化，停止处理")
                        return@runOnUiThread
                    }
                    
                    // 检查是否是PPG设备的多通道模式
                    if (deviceType == "PPG" && chart.isMultiChannelMode()) {
                        // PPG设备：需要获取多通道数据
                        updatePPGData(chart)
                    } else {
                        // 单通道数据：检查是否有滤波器启用
                        try {
                            // 检查数据有效性
                            if (processedData.isEmpty()) {
                                Log.w("FullscreenChartActivity", "处理后数据为空，跳过处理")
                                return@runOnUiThread
                            }
                            
                            // 检查数据是否包含异常值
                            val hasInvalidValues = processedData.any { it.isNaN() || it.isInfinite() }
                            if (hasInvalidValues) {
                                Log.w("FullscreenChartActivity", "处理后数据包含异常值，跳过处理")
                                return@runOnUiThread
                            }
                            
                            // 检查是否有滤波器启用
                            val hasActiveFilters = filterManager?.let { manager ->
                                try {
                                    val field = manager.javaClass.getDeclaredField("isAnyFilterEnabled")
                                    field.isAccessible = true
                                    field.getBoolean(manager)
                                } catch (e: Exception) {
                                    false
                                }
                            } ?: false
                            
                            if (hasActiveFilters) {
                                // 有滤波器启用时，使用滤波器处理
                                filterManager?.processRealTimeData("channel_$channelIndex", processedData) { filteredData ->
                                    try {
                                        // 再次检查Activity状态
                                        if (isFinishing || isDestroyed) {
                                            Log.d("FullscreenChartActivity", "Activity正在销毁，跳过图表更新")
                                            return@processRealTimeData
                                        }
                                        
                                        // 检查滤波后数据有效性
                                        if (filteredData.isEmpty()) {
                                            Log.w("FullscreenChartActivity", "滤波后数据为空，跳过更新")
                                            return@processRealTimeData
                                        }
                                        
                                        chart.updateData(filteredData)
                                        Log.d("FullscreenChartActivity", "已更新滤波后的单通道数据")
                                    } catch (e: Exception) {
                                        Log.e("FullscreenChartActivity", "更新单通道数据失败: ${e.message}", e)
                                    }
                                }
                            } else {
                                // 没有滤波器启用时，直接更新图表
                                chart.updateData(processedData)
                                Log.d("FullscreenChartActivity", "已直接更新处理后数据（无滤波）")
                            }
                        } catch (e: Exception) {
                            Log.e("FullscreenChartActivity", "数据处理失败: ${e.message}", e)
                            // 出错时直接使用原始数据
                            try {
                                if (!isFinishing && !isDestroyed && processedData.isNotEmpty()) {
                                    chart.updateData(processedData)
                                    Log.d("FullscreenChartActivity", "已更新原始单通道数据")
                                }
                            } catch (e2: Exception) {
                                Log.e("FullscreenChartActivity", "更新原始数据也失败: ${e2.message}", e2)
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                Log.e("FullscreenChartActivity", "处理实时数据失败: ${e.message}", e)
            }
        }
    }
    
    override fun onRawDataAvailable(channelIndex: Int, rawData: List<Float>) {
        // 检查Activity是否还在运行或正在退出
        if (isFinishing || isDestroyed || isExiting) {
            return
        }

        // 检查资源是否可用
        if (fullscreenChartManager == null || binding == null) {
            return
        }

        // 如果是单图表模式，只更新对应的图表
        if (isSingleChart && channelIndex != chartIndex) {
            return
        }

        // 检查数据有效性
        if (rawData.isEmpty()) {
            return
        }

        runOnUiThread {
            try {
                // 再次检查Activity状态和退出标志
                if (isFinishing || isDestroyed || isExiting) {
                    Log.d("FullscreenChartActivity", "UI线程中Activity正在销毁，忽略原始数据回调")
                    return@runOnUiThread
                }

                // 检查资源是否仍然可用
                if (fullscreenChartManager == null || binding == null) {
                    return@runOnUiThread
                }
                
                
                // 检查图表管理器是否有效
                val chartManager = fullscreenChartManager
                if (chartManager == null) {
                    Log.w("FullscreenChartActivity", "图表管理器为空，忽略原始数据回调")
                    return@runOnUiThread
                }
                
                // 通过滤波器管理器处理数据
                val charts = chartManager.getCharts()
                if (charts.isNotEmpty()) {
                    val chart = charts.getOrNull(channelIndex.coerceAtMost(charts.size - 1))
                    if (chart == null) {
                        Log.e("FullscreenChartActivity", "通道${channelIndex}对应的图表为空，跳过数据处理")
                        return@runOnUiThread
                    }

                    // 再次检查Activity状态，防止在数据处理过程中Activity被销毁
                    if (isFinishing || isDestroyed || isExiting) {
                        Log.d("FullscreenChartActivity", "原始数据处理过程中Activity状态变化，停止处理")
                        return@runOnUiThread
                    }
                    
                    // 检查是否是PPG设备的多通道模式
                    if (deviceType == "PPG" && chart.isMultiChannelMode()) {
                        // PPG设备：需要获取多通道数据
                        updatePPGData(chart)
                    } else {
                        // 单通道数据：检查是否有滤波器启用
                        try {
                            // 检查数据有效性
                            if (rawData.isEmpty()) {
                                Log.w("FullscreenChartActivity", "原始数据为空，跳过处理")
                                return@runOnUiThread
                            }
                            
                            // 检查数据是否包含异常值
                            val hasInvalidValues = rawData.any { it.isNaN() || it.isInfinite() }
                            if (hasInvalidValues) {
                                Log.w("FullscreenChartActivity", "原始数据包含异常值，跳过处理")
                                return@runOnUiThread
                            }
                            
                            // 检查是否有滤波器启用
                            val hasActiveFilters = filterManager?.let { manager ->
                                // 通过反射或其他方式检查滤波器状态
                                try {
                                    val field = manager.javaClass.getDeclaredField("isAnyFilterEnabled")
                                    field.isAccessible = true
                                    field.getBoolean(manager)
                                } catch (e: Exception) {
                                    false // 如果无法检查，假设没有启用
                                }
                            } ?: false
                            
                            if (hasActiveFilters) {
                                // 有滤波器启用时，使用滤波器处理
                                filterManager?.processRealTimeData("channel_$channelIndex", rawData) { filteredData ->
                                    try {
                                        // 再次检查Activity状态
                                        if (isFinishing || isDestroyed) {
                                            Log.d("FullscreenChartActivity", "Activity正在销毁，跳过图表更新")
                                            return@processRealTimeData
                                        }
                                        
                                        // 检查滤波后数据有效性
                                        if (filteredData.isEmpty()) {
                                            Log.w("FullscreenChartActivity", "滤波后数据为空，跳过更新")
                                            return@processRealTimeData
                                        }
                                        
                                        chart.updateData(filteredData)
                                        Log.d("FullscreenChartActivity", "已更新滤波后的原始数据")
                                    } catch (e: Exception) {
                                        Log.e("FullscreenChartActivity", "更新原始数据失败: ${e.message}", e)
                                    }
                                }
                            } else {
                                // 没有滤波器启用时，直接更新图表
                                chart.updateData(rawData)
                                Log.d("FullscreenChartActivity", "已直接更新原始数据（无滤波）")
                            }
                        } catch (e: Exception) {
                            Log.e("FullscreenChartActivity", "数据处理失败: ${e.message}", e)
                            // 出错时直接使用原始数据
                            try {
                                if (!isFinishing && !isDestroyed && rawData.isNotEmpty()) {
                                    chart.updateData(rawData)
                                    Log.d("FullscreenChartActivity", "已更新原始数据")
                                }
                            } catch (e2: Exception) {
                                Log.e("FullscreenChartActivity", "更新原始数据也失败: ${e2.message}", e2)
                            }
                        }
                    }
                }
                
                // 尝试从DataManager获取最新的AdditionalData并更新生命体征显示
                updateVitalSignsFromDataManager()
            } catch (e: Exception) {
                Log.e("FullscreenChartActivity", "处理原始数据失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 从DataManager获取最新的生命体征数据并更新显示
     */
    private fun updateVitalSignsFromDataManager() {
        // 检查Activity状态
        if (isFinishing || isDestroyed) {
            Log.d("FullscreenChartActivity", "Activity正在销毁，跳过生命体征更新")
            return
        }
        
        try {
            val dataManager = mainDataManager
            if (dataManager != null) {
                // 获取最新的数据包
                val latestPackets = dataManager.getPacketBuffer()
                if (latestPackets.isNotEmpty()) {
                    // 获取最新的数据包中的AdditionalData
                    val latestPacket = latestPackets.last()
                    val additionalData = latestPacket.additionalData
                    
                    if (additionalData != null) {
                        updateVitalSignsDisplay(additionalData)
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("FullscreenChartActivity", "获取生命体征数据失败: ${e.message}")
        }
    }
    
    /**
     * 更新PPG多通道数据
     */
    private fun updatePPGData(chart: DynamicChartView) {
        try {
            // 检查Activity状态
            if (isFinishing || isDestroyed) {
                Log.d("FullscreenChartActivity", "Activity正在销毁，跳过PPG数据更新")
                return
            }
            
            // 检查图表是否有效
            if (chart == null) {
                Log.w("FullscreenChartActivity", "图表为空，跳过PPG数据更新")
                return
            }
            
            // 从主数据管理器获取PPG数据
            val dataManager = mainDataManager
            if (dataManager != null) {
                try {
                    val mappedPackets = dataManager.getMappedPacketBuffer()
                    if (mappedPackets.isNotEmpty()) {
                        val latestMappedPacket = mappedPackets.last()
                        val channelData = latestMappedPacket.getChannelData()
                        if (channelData != null && channelData.isNotEmpty()) {
                            // 验证数据格式
                            if (channelData.size >= 2 && channelData[0].isNotEmpty() && channelData[1].isNotEmpty()) {
                                chart.updateMultiChannelData(channelData)
                                Log.d("FullscreenChartActivity", "更新PPG多通道数据: ${channelData.size}通道")
                                return
                            } else {
                                Log.w("FullscreenChartActivity", "PPG数据格式不正确: ${channelData.map { it.size }}")
                            }
                        } else {
                            Log.w("FullscreenChartActivity", "PPG通道数据为空")
                        }
                    } else {
                        Log.w("FullscreenChartActivity", "映射数据包为空")
                    }
                } catch (e: Exception) {
                    Log.e("FullscreenChartActivity", "获取PPG数据失败: ${e.message}", e)
                }
            } else {
                Log.w("FullscreenChartActivity", "数据管理器为空")
            }
            
            // 如果无法获取数据，使用模拟数据
            try {
                val mockPPGData = listOf(
                    listOf(100f, 120f, 110f, 130f, 115f), // 红光PPG
                    listOf(200f, 220f, 210f, 230f, 215f)  // 红外光PPG
                )
                chart.updateMultiChannelData(mockPPGData)
                Log.d("FullscreenChartActivity", "使用模拟PPG数据")
            } catch (e: Exception) {
                Log.e("FullscreenChartActivity", "更新模拟PPG数据失败: ${e.message}", e)
            }
        } catch (e: Exception) {
            Log.e("FullscreenChartActivity", "更新PPG数据失败: ${e.message}", e)
        }
    }
    
    override fun onStreamingProgress(progress: Int, totalSamples: Int, processedSamples: Int) {
        // 检查Activity是否还在运行或正在退出
        if (isFinishing || isDestroyed || isExiting) {
            return
        }
        // 全屏模式下不需要显示进度
    }
    
    // NativeMethodCallback实现
    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>?
}
