package com.example.cmake_project_test

import android.app.AlertDialog
import android.content.Context
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import android.widget.Switch
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 全屏模式滤波器管理器
 * 管理滤波器状态、UI交互和数据处理
 */
class FullscreenFilterManager(
    private val context: Context,
    private val scope: CoroutineScope,
    private val dataManager: DataManager?,
    private val chartManager: DynamicChartManager?,
    private val deviceType: String = "PW_ECG_SL" // 默认设备类型
) {
    
    // 滤波器状态数据类
    data class FilterState(
        var enabled: Boolean = false,
        var frequency: Double = 0.0
    )
    
    /**
     * 根据设备类型获取采样率
     */
    private fun getSampleRate(): Double {
        return when (deviceType) {
            "ECG_2LEAD", "ECG_12LEAD", "PW_ECG_SL", "EEG" -> 250.0
            "PPG" -> 50.0
            "STETHOSCOPE", "SNORE" -> 8000.0
            "RESPIRATION" -> 50.0
            else -> 250.0 // 默认采样率
        }
    }
    
    // 当前滤波器状态
    private val lowpassFilter = FilterState(false, 40.0)
    private val highpassFilter = FilterState(false, 1.0)
    private val notchFilter = FilterState(false, 50.0)
    
    // 是否有任何滤波器启用
    private var isAnyFilterEnabled = false
    
    // 内存管理：动态调整的缓冲区大小
    private var maxDataPointsPerBatch = 100 // 每次最多处理100个数据点
    private val dataBuffer = mutableListOf<Float>()
    private var maxBufferSize = 500 // 缓冲区最大大小（动态调整）

    // UI组件引用
    private var filterButton: Button? = null
    private var currentDialog: android.app.AlertDialog? = null

    // 原始数据和滤波后数据缓存 - 改进为带时间戳的缓存
    private val originalDataCache = mutableMapOf<String, CacheEntry>()
    private val filteredDataCache = mutableMapOf<String, CacheEntry>()

    // 缓存配置
    private val maxCacheEntries = 50 // 最大缓存条目数
    private val maxCacheDataSize = 10000 // 每个缓存条目的最大数据点数
    private val cacheExpirationTime = 5 * 60 * 1000L // 缓存过期时间：5分钟

    // 缓存条目类
    data class CacheEntry(
        val data: MutableList<Float>,
        val timestamp: Long = System.currentTimeMillis(),
        var accessCount: Int = 0
    )
    
    /**
     * 初始化UI组件
     */
    fun initializeUI(filterBtn: Button) {
        filterButton = filterBtn

        // 根据设备配置动态调整缓冲区大小
        optimizeBufferSizes()

        setupUIListeners()
        updateUIState()
    }

    /**
     * 根据设备配置和内存情况动态优化缓冲区大小
     */
    private fun optimizeBufferSizes() {
        try {
            val runtime = Runtime.getRuntime()
            val maxMemoryMB = runtime.maxMemory() / 1024 / 1024

            // 根据设备采样率调整批处理大小
            val sampleRate = getSampleRate()
            when {
                sampleRate >= 8000.0 -> { // 音频设备
                    maxDataPointsPerBatch = 50
                    maxBufferSize = 200
                }
                sampleRate >= 1000.0 -> { // 高速设备
                    maxDataPointsPerBatch = 100
                    maxBufferSize = 400
                }
                sampleRate >= 250.0 -> { // 中速设备（ECG等）
                    maxDataPointsPerBatch = 150
                    maxBufferSize = 600
                }
                else -> { // 低速设备
                    maxDataPointsPerBatch = 200
                    maxBufferSize = 800
                }
            }

            // 根据可用内存进一步调整
            when {
                maxMemoryMB < 128 -> { // 低内存设备
                    maxDataPointsPerBatch = (maxDataPointsPerBatch * 0.5).toInt()
                    maxBufferSize = (maxBufferSize * 0.5).toInt()
                }
                maxMemoryMB < 256 -> { // 中等内存设备
                    maxDataPointsPerBatch = (maxDataPointsPerBatch * 0.75).toInt()
                    maxBufferSize = (maxBufferSize * 0.75).toInt()
                }
                maxMemoryMB >= 512 -> { // 高内存设备
                    maxDataPointsPerBatch = (maxDataPointsPerBatch * 1.5).toInt()
                    maxBufferSize = (maxBufferSize * 1.5).toInt()
                }
            }

            // 确保最小值
            maxDataPointsPerBatch = maxOf(maxDataPointsPerBatch, 25)
            maxBufferSize = maxOf(maxBufferSize, 100)

            Log.d("FullscreenFilterManager", "缓冲区大小优化完成: 批处理=$maxDataPointsPerBatch, 缓冲区=$maxBufferSize, 内存=${maxMemoryMB}MB")

        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "缓冲区大小优化失败: ${e.message}")
            // 使用默认值
            maxDataPointsPerBatch = 100
            maxBufferSize = 500
        }
    }
    
    /**
     * 设置UI监听器
     */
    private fun setupUIListeners() {
        // 滤波器按键
        filterButton?.setOnClickListener {
            showFilterDialog()
        }
    }
    
    /**
     * 显示滤波器设置对话框
     */
    private fun showFilterDialog() {
        try {
            // Context在构造函数中传入，不会为null，但为了安全起见保留检查
            
            val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_filter_settings, null)
            
            // 获取对话框中的组件
            val lowpassSwitch = dialogView.findViewById<Switch>(R.id.lowpass_enable_switch)
            val highpassSwitch = dialogView.findViewById<Switch>(R.id.highpass_enable_switch)
            val notchSwitch = dialogView.findViewById<Switch>(R.id.notch_enable_switch)
            val lowpassFreqInput = dialogView.findViewById<EditText>(R.id.lowpass_frequency_input)
            val highpassFreqInput = dialogView.findViewById<EditText>(R.id.highpass_frequency_input)
            val notchFreqInput = dialogView.findViewById<EditText>(R.id.notch_frequency_input)
            val btnCancel = dialogView.findViewById<Button>(R.id.btn_cancel)
            val btnApply = dialogView.findViewById<Button>(R.id.btn_apply)
            
            // 检查组件是否获取成功
            if (lowpassSwitch == null || highpassSwitch == null || notchSwitch == null ||
                lowpassFreqInput == null || highpassFreqInput == null || notchFreqInput == null ||
                btnCancel == null || btnApply == null) {
                Log.e("FullscreenFilterManager", "对话框组件获取失败")
                return
            }
            
            // 设置当前状态
            setupDialogCurrentState(lowpassSwitch, highpassSwitch, notchSwitch,
                lowpassFreqInput, highpassFreqInput, notchFreqInput)
            
            // 创建对话框
            val dialog = AlertDialog.Builder(context)
                .setView(dialogView)
                .create()
            
            // 保存对话框引用
            currentDialog = dialog
            
            // 设置按钮监听器
            btnCancel.setOnClickListener {
                try {
                    dialog.dismiss()
                    currentDialog = null
                } catch (e: Exception) {
                    Log.e("FullscreenFilterManager", "关闭对话框失败: ${e.message}")
                }
            }
            
            btnApply.setOnClickListener {
                try {
                    applyFilterFromDialog(lowpassSwitch, highpassSwitch, notchSwitch,
                        lowpassFreqInput, highpassFreqInput, notchFreqInput)
                    dialog.dismiss()
                    currentDialog = null
                } catch (e: Exception) {
                    Log.e("FullscreenFilterManager", "应用滤波器设置失败: ${e.message}")
                }
            }
            
            // 设置对话框取消监听器
            dialog.setOnCancelListener {
                Log.d("FullscreenFilterManager", "对话框被取消")
                currentDialog = null
            }
            
            dialog.show()
            
        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "显示滤波器对话框失败: ${e.message}", e)
        }
    }
    
    /**
     * 设置对话框的当前状态
     */
    private fun setupDialogCurrentState(
        lowpassSwitch: Switch,
        highpassSwitch: Switch,
        notchSwitch: Switch,
        lowpassFreqInput: EditText,
        highpassFreqInput: EditText,
        notchFreqInput: EditText
    ) {
        // 设置开关状态
        lowpassSwitch.isChecked = lowpassFilter.enabled
        highpassSwitch.isChecked = highpassFilter.enabled
        notchSwitch.isChecked = notchFilter.enabled
        
        // 设置频率值
        lowpassFreqInput.setText(lowpassFilter.frequency.toInt().toString())
        highpassFreqInput.setText(highpassFilter.frequency.toInt().toString())
        notchFreqInput.setText(notchFilter.frequency.toInt().toString())
    }
    
    /**
     * 从对话框应用滤波器设置
     */
    private fun applyFilterFromDialog(
        lowpassSwitch: Switch,
        highpassSwitch: Switch,
        notchSwitch: Switch,
        lowpassFreqInput: EditText,
        highpassFreqInput: EditText,
        notchFreqInput: EditText
    ) {
        try {
            // 获取开关状态
            val lowpassEnabled = lowpassSwitch.isChecked
            val highpassEnabled = highpassSwitch.isChecked
            val notchEnabled = notchSwitch.isChecked
            
            // 获取频率值并验证
            val lowpassFreq = parseFrequency(lowpassFreqInput.text.toString(), 40.0)
            val highpassFreq = parseFrequency(highpassFreqInput.text.toString(), 1.0)
            val notchFreq = parseFrequency(notchFreqInput.text.toString(), 50.0)
            
            // 更新滤波器状态
            lowpassFilter.enabled = lowpassEnabled
            lowpassFilter.frequency = lowpassFreq
            highpassFilter.enabled = highpassEnabled
            highpassFilter.frequency = highpassFreq
            notchFilter.enabled = notchEnabled
            notchFilter.frequency = notchFreq
            
            // 检查是否有任何滤波器启用
            isAnyFilterEnabled = lowpassEnabled || highpassEnabled || notchEnabled
            
            // 应用滤波器
            applyCurrentFilter()
            updateUIState()
            
            Log.d("FullscreenFilterManager", "滤波器设置已应用: 低通=${lowpassEnabled}(${lowpassFreq}Hz), 高通=${highpassEnabled}(${highpassFreq}Hz), 陷波=${notchEnabled}(${notchFreq}Hz)")
            
        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "应用滤波器设置失败: ${e.message}", e)
        }
    }
    
    /**
     * 解析频率值
     */
    private fun parseFrequency(freqText: String, defaultValue: Double): Double {
        return try {
            val freq = freqText.toDouble()
            if (freq > 0 && freq <= 1000) freq else defaultValue
        } catch (e: Exception) {
            Log.w("FullscreenFilterManager", "频率解析失败: $freqText, 使用默认值: $defaultValue")
            defaultValue
        }
    }
    
    /**
     * 更新UI状态
     */
    private fun updateUIState() {
        // 更新滤波器按键状态
        if (isAnyFilterEnabled) {
            filterButton?.setBackgroundColor(0xFF4CAF50.toInt())
            val enabledFilters = mutableListOf<String>()
            if (lowpassFilter.enabled) enabledFilters.add("低通")
            if (highpassFilter.enabled) enabledFilters.add("高通")
            if (notchFilter.enabled) enabledFilters.add("陷波")
            filterButton?.text = "滤波器 ✓ (${enabledFilters.joinToString(",")})"
        } else {
            filterButton?.setBackgroundColor(0xFF666666.toInt())
            filterButton?.text = "滤波器"
        }
    }
    
    /**
     * 应用当前滤波器
     */
    private fun applyCurrentFilter() {
        scope.launch(Dispatchers.Main) {
            try {
                if (isAnyFilterEnabled) {
                    // 应用滤波器
                    dataManager?.setFilterSettings(createFilterSettings())
                    Log.d("FullscreenFilterManager", "应用叠加滤波器: 低通=${lowpassFilter.enabled}, 高通=${highpassFilter.enabled}, 陷波=${notchFilter.enabled}")
                } else {
                    // 关闭所有滤波器
                    dataManager?.setFilterSettings(FilterSettings())
                    Log.d("FullscreenFilterManager", "关闭所有滤波器")
                }
            } catch (e: Exception) {
                Log.e("FullscreenFilterManager", "应用滤波器失败: ${e.message}")
            }
        }
    }
    
    /**
     * 根据当前状态创建滤波器设置
     */
    private fun createFilterSettings(): FilterSettings {
        return FilterSettings(
            sampleRate = 1000.0,
            // 根据启用的滤波器设置参数
            generalLowPass = if (lowpassFilter.enabled) lowpassFilter.frequency else 100.0,
            generalHighPass = if (highpassFilter.enabled) highpassFilter.frequency else 0.1,
            generalNotchFreq = if (notchFilter.enabled) notchFilter.frequency else 50.0,
            generalNotchQ = if (notchFilter.enabled) 30.0 else 30.0
        )
    }
    
    /**
     * 处理实时数据并返回滤波后的数据（优化内存管理）
     */
    fun processRealTimeData(dataType: String, data: List<Float>, callback: (List<Float>) -> Unit) {
        try {
            // 检查数据有效性
            if (data.isEmpty()) {
                Log.w("FullscreenFilterManager", "数据为空，跳过处理")
                callback(emptyList())
                return
            }
            
            // 检查数据是否包含异常值
            val hasInvalidValues = data.any { it.isNaN() || it.isInfinite() }
            if (hasInvalidValues) {
                Log.w("FullscreenFilterManager", "数据包含异常值，使用原始数据")
                callback(data)
                return
            }
            
            if (!isAnyFilterEnabled) {
                // 无滤波时直接使用原始数据，不进行任何处理
                callback(data)
                return
            }
            
            // 内存管理：限制单次处理的数据量（仅在滤波时）
            val dataToProcess = if (data.size > maxDataPointsPerBatch) {
                data.takeLast(maxDataPointsPerBatch) // 只处理最新的数据点
            } else {
                data
            }
            
            // 应用滤波器处理数据
            scope.launch(Dispatchers.Default) {
                try {
                    // 定期清理内存
                    cleanupMemory()
                    
                    val filteredData = applyOverlayFiltersToData(dataToProcess)
                    scope.launch(Dispatchers.Main) {
                        try {
                            callback(filteredData)
                        } catch (e: Exception) {
                            Log.e("FullscreenFilterManager", "回调执行失败: ${e.message}", e)
                        }
                    }
                } catch (e: Exception) {
                    Log.e("FullscreenFilterManager", "数据处理失败: ${e.message}", e)
                    // 出错时使用原始数据
                    scope.launch(Dispatchers.Main) {
                        try {
                            callback(dataToProcess)
                        } catch (e2: Exception) {
                            Log.e("FullscreenFilterManager", "回调执行也失败: ${e2.message}", e2)
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "processRealTimeData异常: ${e.message}", e)
            try {
                callback(data)
            } catch (e2: Exception) {
                Log.e("FullscreenFilterManager", "最终回调也失败: ${e2.message}", e2)
            }
        }
    }
    
    /**
     * 处理实时数据（兼容旧接口）
     */
    fun processRealTimeData(dataType: String, data: List<Float>) {
        processRealTimeData(dataType, data) { filteredData ->
            updateChartWithData(filteredData)
        }
    }
    
    /**
     * 更新图表数据
     */
    private fun updateChartWithData(data: List<Float>) {
        try {
            val charts = chartManager?.getCharts()
            if (charts != null && charts.isNotEmpty()) {
                val chart = charts[0]
                chart.updateData(data)
            }
        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "更新图表数据失败: ${e.message}")
        }
    }
    
    /**
     * 对数据进行叠加滤波处理
     */
    private fun applyOverlayFiltersToData(data: List<Float>): List<Float> {
        if (data.isEmpty()) return data
        
        try {
            var result = data
            
            // 按顺序应用启用的滤波器
            // 1. 高通滤波（去除基线漂移）
            if (highpassFilter.enabled && highpassFilter.frequency > 0) {
                try {
                    result = applyHighPassFilter(result, highpassFilter.frequency)
                    Log.d("FullscreenFilterManager", "高通滤波完成: ${result.size}个数据点")
                } catch (e: Exception) {
                    Log.e("FullscreenFilterManager", "高通滤波失败: ${e.message}", e)
                    // 高通滤波失败时跳过，继续处理其他滤波器
                }
            }
            
            // 2. 低通滤波（去除高频噪声）
            if (lowpassFilter.enabled && lowpassFilter.frequency > 0) {
                try {
                    result = applyLowPassFilter(result, lowpassFilter.frequency)
                    Log.d("FullscreenFilterManager", "低通滤波完成: ${result.size}个数据点")
                } catch (e: Exception) {
                    Log.e("FullscreenFilterManager", "低通滤波失败: ${e.message}", e)
                    // 低通滤波失败时跳过，继续处理其他滤波器
                }
            }
            
            // 3. 陷波滤波（去除工频干扰）
            if (notchFilter.enabled && notchFilter.frequency > 0) {
                try {
                    result = applyNotchFilter(result, notchFilter.frequency)
                    Log.d("FullscreenFilterManager", "陷波滤波完成: ${result.size}个数据点")
                } catch (e: Exception) {
                    Log.e("FullscreenFilterManager", "陷波滤波失败: ${e.message}", e)
                    // 陷波滤波失败时跳过
                }
            }
            
            // 最终检查：确保结果数据有效
            if (result.isEmpty()) {
                Log.w("FullscreenFilterManager", "滤波后数据为空，返回原始数据")
                return data
            }
            
            // 检查是否有异常值
            val hasInvalidValues = result.any { it.isNaN() || it.isInfinite() }
            if (hasInvalidValues) {
                Log.w("FullscreenFilterManager", "滤波后数据包含异常值，返回原始数据")
                return data
            }
            
            return result
        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "滤波处理异常: ${e.message}", e)
            return data
        }
    }
    
    /**
     * 低通滤波（简单移动平均 - 更稳定的算法）
     */
    private fun applyLowPassFilter(data: List<Float>, cutoffFreq: Double): List<Float> {
        if (data.isEmpty()) return data
        
        val result = mutableListOf<Float>()
        val sampleRate = getSampleRate()
        
        // 计算窗口大小，限制在合理范围内
        val windowSize = (sampleRate / cutoffFreq).toInt().coerceIn(3, 15)
        
        // 使用简单的移动平均，避免复杂的边界处理
        for (i in data.indices) {
            val start = maxOf(0, i - windowSize / 2)
            val end = minOf(data.size, i + windowSize / 2 + 1)
            
            var sum = 0f
            var count = 0
            
            for (j in start until end) {
                val value = data[j]
                if (!value.isNaN() && !value.isInfinite()) {
                    sum += value
                    count++
                }
            }
            
            val average = if (count > 0) sum / count else data[i]
            result.add(average.coerceIn(-1000f, 1000f))
        }
        
        return result
    }
    
    /**
     * 高通滤波（简单差分滤波 - 更稳定的算法）
     */
    private fun applyHighPassFilter(data: List<Float>, cutoffFreq: Double): List<Float> {
        if (data.isEmpty()) return data
        
        val result = mutableListOf<Float>()
        
        // 使用简单的差分滤波，去除基线漂移
        // 计算移动平均作为基线
        val sampleRate = getSampleRate()
        val baselineWindow = (sampleRate / cutoffFreq).toInt().coerceIn(5, 25)
        
        for (i in data.indices) {
            val start = maxOf(0, i - baselineWindow / 2)
            val end = minOf(data.size, i + baselineWindow / 2 + 1)
            
            var sum = 0f
            var count = 0
            
            for (j in start until end) {
                val value = data[j]
                if (!value.isNaN() && !value.isInfinite()) {
                    sum += value
                    count++
                }
            }
            
            val baseline = if (count > 0) sum / count else 0f
            val highPassValue = data[i] - baseline
            
            result.add(highPassValue.coerceIn(-1000f, 1000f))
        }
        
        return result
    }
    
    /**
     * 陷波滤波（简单陷波滤波 - 更稳定的算法）
     */
    private fun applyNotchFilter(data: List<Float>, notchFreq: Double): List<Float> {
        if (data.isEmpty()) return data
        
        val result = mutableListOf<Float>()
        val sampleRate = getSampleRate()
        
        // 使用简单的陷波滤波：检测特定频率的周期性信号并去除
        val period = (sampleRate / notchFreq).toInt().coerceIn(2, 20)
        
        for (i in data.indices) {
            val currentValue = data[i]
            
            // 计算周围几个周期的平均值
            var sum = 0f
            var count = 0
            
            for (offset in -period..period) {
                val index = i + offset
                if (index >= 0 && index < data.size) {
                    val value = data[index]
                    if (!value.isNaN() && !value.isInfinite()) {
                        sum += value
                        count++
                    }
                }
            }
            
            val average = if (count > 0) sum / count else currentValue
            
            // 简单的陷波：如果当前值与平均值差异很大，则使用平均值
            val diff = kotlin.math.abs(currentValue - average)
            val threshold = kotlin.math.abs(average) * 0.1f // 10%的阈值
            
            val filteredValue = if (diff > threshold) {
                average * 0.8f + currentValue * 0.2f // 混合处理
            } else {
                currentValue
            }
            
            result.add(filteredValue.coerceIn(-1000f, 1000f))
        }
        
        return result
    }
    
    /**
     * 获取当前滤波器状态信息
     */
    fun getFilterStatus(): String {
        return if (isAnyFilterEnabled) {
            val enabledFilters = mutableListOf<String>()
            if (lowpassFilter.enabled) enabledFilters.add("低通(${lowpassFilter.frequency.toInt()}Hz)")
            if (highpassFilter.enabled) enabledFilters.add("高通(${highpassFilter.frequency.toInt()}Hz)")
            if (notchFilter.enabled) enabledFilters.add("陷波(${notchFilter.frequency.toInt()}Hz)")
            enabledFilters.joinToString(", ")
        } else {
            "无滤波"
        }
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            Log.d("FullscreenFilterManager", "=== cleanup 开始 ===")
            
            // 清理对话框
            try {
                Log.d("FullscreenFilterManager", "开始清理对话框")
                if (currentDialog != null) {
                    currentDialog?.dismiss()
                    currentDialog = null
                    Log.d("FullscreenFilterManager", "对话框清理完成")
                } else {
                    Log.d("FullscreenFilterManager", "对话框为空，无需清理")
                }
            } catch (e: Exception) {
                Log.e("FullscreenFilterManager", "关闭对话框失败: ${e.message}", e)
                Log.e("FullscreenFilterManager", "对话框异常堆栈: ${e.stackTraceToString()}")
            }
            
            // 清理UI组件引用
            Log.d("FullscreenFilterManager", "清理UI组件引用")
            filterButton = null
            
            // 清理数据缓存
            Log.d("FullscreenFilterManager", "清理数据缓存")
            try {
                originalDataCache.clear()
                Log.d("FullscreenFilterManager", "原始数据缓存清理完成")
            } catch (e: Exception) {
                Log.e("FullscreenFilterManager", "清理原始数据缓存失败: ${e.message}", e)
            }
            
            try {
                filteredDataCache.clear()
                Log.d("FullscreenFilterManager", "滤波数据缓存清理完成")
            } catch (e: Exception) {
                Log.e("FullscreenFilterManager", "清理滤波数据缓存失败: ${e.message}", e)
            }
            
            try {
                dataBuffer.clear()
                Log.d("FullscreenFilterManager", "数据缓冲区清理完成")
            } catch (e: Exception) {
                Log.e("FullscreenFilterManager", "清理数据缓冲区失败: ${e.message}", e)
            }
            
            // 注意：scope是lifecycleScope，会自动管理协程生命周期
            Log.d("FullscreenFilterManager", "=== cleanup 完成 ===")
            
        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "清理资源时发生异常: ${e.message}", e)
            Log.e("FullscreenFilterManager", "异常堆栈: ${e.stackTraceToString()}")
        }
    }
    
    /**
     * 添加原始数据到缓存
     */
    private fun addToOriginalCache(key: String, data: List<Float>) {
        try {
            // 限制数据大小
            val limitedData = if (data.size > maxCacheDataSize) {
                data.takeLast(maxCacheDataSize).toMutableList()
            } else {
                data.toMutableList()
            }

            originalDataCache[key] = CacheEntry(limitedData)
            cleanupCacheIfNeeded(originalDataCache, "原始数据")

        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "添加原始数据缓存失败: ${e.message}")
        }
    }

    /**
     * 添加滤波数据到缓存
     */
    private fun addToFilteredCache(key: String, data: List<Float>) {
        try {
            // 限制数据大小
            val limitedData = if (data.size > maxCacheDataSize) {
                data.takeLast(maxCacheDataSize).toMutableList()
            } else {
                data.toMutableList()
            }

            filteredDataCache[key] = CacheEntry(limitedData)
            cleanupCacheIfNeeded(filteredDataCache, "滤波数据")

        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "添加滤波数据缓存失败: ${e.message}")
        }
    }

    /**
     * 从原始数据缓存获取数据
     */
    private fun getFromOriginalCache(key: String): List<Float>? {
        val entry = originalDataCache[key]
        return entry?.let {
            it.accessCount++
            it.data
        }
    }

    /**
     * 从滤波数据缓存获取数据
     */
    private fun getFromFilteredCache(key: String): List<Float>? {
        val entry = filteredDataCache[key]
        return entry?.let {
            it.accessCount++
            it.data
        }
    }

    /**
     * 清理缓存（如果需要）
     */
    private fun cleanupCacheIfNeeded(cache: MutableMap<String, CacheEntry>, cacheName: String) {
        try {
            // 检查条目数量
            if (cache.size > maxCacheEntries) {
                // 按访问频率和时间排序，保留最常用的
                val sortedEntries = cache.entries.sortedWith(compareBy(
                    { -it.value.accessCount }, // 访问次数多的优先保留
                    { -it.value.timestamp }    // 最近访问的优先保留
                ))

                // 保留前80%的条目
                val keepCount = (maxCacheEntries * 0.8).toInt()
                val entriesToRemove = sortedEntries.drop(keepCount)

                entriesToRemove.forEach { (key, _) ->
                    cache.remove(key)
                }

                Log.d("FullscreenFilterManager", "${cacheName}缓存清理: 保留 $keepCount 条，移除 ${entriesToRemove.size} 条")
            }

            // 清理过期条目
            val currentTime = System.currentTimeMillis()
            val expiredKeys = cache.filter { (_, entry) ->
                currentTime - entry.timestamp > cacheExpirationTime
            }.keys.toList()

            expiredKeys.forEach { key ->
                cache.remove(key)
            }

            if (expiredKeys.isNotEmpty()) {
                Log.d("FullscreenFilterManager", "${cacheName}缓存清理: 移除 ${expiredKeys.size} 个过期条目")
            }

        } catch (e: Exception) {
            Log.e("FullscreenFilterManager", "${cacheName}缓存清理失败: ${e.message}")
        }
    }

    /**
     * 定期清理内存（防止长时间运行导致内存泄漏）
     */
    internal fun cleanupMemory() {
        try {
            // 清理数据缓冲区
            if (dataBuffer.size > maxBufferSize) {
                val excess = dataBuffer.size - maxBufferSize
                repeat(excess) {
                    if (dataBuffer.isNotEmpty()) {
                        dataBuffer.removeAt(0)
                    }
                }
                Log.d("FullscreenFilterManager", "清理了 $excess 个数据点")
            }

            // 智能清理缓存
            cleanupCacheIfNeeded(originalDataCache, "原始数据")
            cleanupCacheIfNeeded(filteredDataCache, "滤波数据")

            // 记录缓存状态
            Log.d("FullscreenFilterManager", "缓存状态: 原始数据${originalDataCache.size}条，滤波数据${filteredDataCache.size}条")

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