package com.example.cmake_project_test

import android.util.Log
import type.SensorData
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 * 数据管理类
 * 负责数据解析、缓冲管理和原生方法调用
 */
class DataManager(private val nativeCallback: NativeMethodCallback) {
    
    // 添加实时数据回调接口
    interface RealTimeDataCallback {
        fun onProcessedDataAvailable(channelIndex: Int, processedData: List<Float>)
        fun onStreamingProgress(progress: Int, totalSamples: Int, processedSamples: Int)
        fun onRawDataAvailable(channelIndex: Int, rawData: List<Float>) // 新增：原始数据回调
    }
    
    private var realTimeCallback: RealTimeDataCallback? = null
    
    fun setRealTimeCallback(callback: RealTimeDataCallback) {
        this.realTimeCallback = callback
    }
    
    private var parserHandle: Long = 0L
    private val rawStream = ByteArrayOutputStream(4096)
    private val packetBuffer = mutableListOf<SensorData>()
    private var totalPacketsParsed = 0L
    
    // 信号处理相关
    private var streamingSignalProcessor: StreamingSignalProcessor? = null
    private var streamingSignalProcessorInitialized = false
    private val processedPackets = mutableListOf<SensorData>()
    private val filterSettings = FilterSettings()
    
    // 通道映射相关
    private var dataMapper: DataMapper? = null
    private var dataMapperInitialized = false
    
    // 指标计算相关
    private var indicatorCalculator: IndicatorCalculator? = null
    private var indicatorCalculatorInitialized = false
    private val calculatedMetrics = mutableListOf<Map<String, Float>>()
    private var latestMetrics: Map<String, Float> = emptyMap()
    
    // 流式数据处理相关
    private val channelBuffers = mutableMapOf<Int, MutableList<Float>>() // 通道号 -> 数据缓冲区
    private val processedChannelBuffers = mutableMapOf<Int, MutableList<Float>>() // 处理后的通道数据
    private val processingWindowSize = 1000 // 优化：增大处理窗口大小，确保心率计算
    private val minSamplesForMetrics = 250 // 优化：250个样本（1秒@250Hz），适应十二导联心电
    private var currentDataType: type.SensorData.DataType? = null // 当前数据类型
    private var lastProcessTime = 0L // 上次处理时间
    private val processingInterval = 200L // 优化：200ms处理间隔，提高实时性
    private var totalProcessedSamples = 0L // 总处理样本数
    
    // 陷波滤波器状态
    var notchFilterEnabled = false
    
    /**
     * 确保解析器已创建
     */
    fun ensureParser() {
        if (parserHandle == 0L) {
            parserHandle = nativeCallback.createStreamParser()
        }
    }
    
    /**
     * 处理蓝牙通知数据块
     */
    fun onBleNotify(chunk: ByteArray) {
        if (chunk.isEmpty()) {
            Log.w("DataManager", "接收到空的蓝牙数据块")
            return
        }
        
        Log.d("DataManager", "接收到蓝牙数据: ${chunk.size} 字节")
        Log.d("DataManager", "数据前10字节: ${chunk.take(10).joinToString(", ") { "0x%02X".format(it) }}")
        
        ensureParser()
        rawStream.write(chunk)
        nativeCallback.streamParserAppend(parserHandle, chunk)

        // 拉取解析出的数据包
        val packets = nativeCallback.streamParserDrainPackets(parserHandle)
        Log.d("DataManager", "解析结果: ${if (packets != null) packets.size else 0} 个数据包")
        
        if (!packets.isNullOrEmpty()) {
            totalPacketsParsed += packets.size
            packetBuffer.addAll(packets)
            
            Log.d("DataManager", "解析出 ${packets.size} 个数据包")
            
            // 立即发送原始数据到图表显示
            sendRawDataToCharts(packets)
            
            // 应用流式数据处理
            processStreamingData(packets)
        } else {
            Log.w("DataManager", "没有解析出有效数据包")
        }
    }
    
    /**
     * 确保数据映射器已初始化
     */
    fun ensureDataMapper() {
        if (!dataMapperInitialized) {
            try {
                Log.d("DataManager", "开始创建数据映射器实例...")
                dataMapper = DataMapper()
                Log.d("DataManager", "数据映射器实例创建成功")
                
                Log.d("DataManager", "开始初始化数据映射器...")
                dataMapperInitialized = dataMapper?.initialize() ?: false
            if (dataMapperInitialized) {
                Log.d("DataManager", "数据映射器初始化成功")
            } else {
                Log.e("DataManager", "数据映射器初始化失败")
                }
            } catch (e: Exception) {
                Log.e("DataManager", "数据映射器初始化异常: ${e.message}", e)
                dataMapperInitialized = false
            }
        }
    }
    
    /**
     * 确保指标计算器已初始化
     */
    fun ensureIndicatorCalculator() {
        if (!indicatorCalculatorInitialized) {
            try {
                Log.d("DataManager", "开始创建指标计算器实例...")
                indicatorCalculator = IndicatorCalculator()
                Log.d("DataManager", "指标计算器实例创建成功")
                
                Log.d("DataManager", "开始初始化指标计算器...")
                indicatorCalculatorInitialized = indicatorCalculator?.initialize() ?: false
            if (indicatorCalculatorInitialized) {
                Log.d("DataManager", "指标计算器初始化成功")
            } else {
                Log.e("DataManager", "指标计算器初始化失败")
                }
            } catch (e: Exception) {
                Log.e("DataManager", "指标计算器初始化异常: ${e.message}", e)
                indicatorCalculatorInitialized = false
            }
        }
    }
    
    /**
     * 确保流式信号处理器已初始化
     */
    fun ensureStreamingSignalProcessor() {
        if (!streamingSignalProcessorInitialized) {
            try {
                Log.d("DataManager", "开始创建流式信号处理器实例...")
                streamingSignalProcessor = StreamingSignalProcessor()
                Log.d("DataManager", "流式信号处理器实例创建成功")
                
                Log.d("DataManager", "开始初始化流式信号处理器...")
                streamingSignalProcessorInitialized = streamingSignalProcessor?.initialize() ?: false
            if (streamingSignalProcessorInitialized) {
                Log.d("DataManager", "流式信号处理器初始化成功")
            } else {
                Log.e("DataManager", "流式信号处理器初始化失败")
                }
            } catch (e: Exception) {
                Log.e("DataManager", "流式信号处理器初始化异常: ${e.message}", e)
                streamingSignalProcessorInitialized = false
            }
        }
    }
    
    /**
     * 立即发送原始数据到图表显示
     */
    private fun sendRawDataToCharts(packets: List<SensorData>) {
        if (packets.isEmpty()) {
            Log.w("DataManager", "sendRawDataToCharts: 没有数据包")
            return
        }
        
        Log.d("DataManager", "立即发送原始数据到图表，处理 ${packets.size} 个数据包")
        
        // 直接处理原始数据包，不进行通道映射
        for ((packetIndex, packet) in packets.withIndex()) {
            Log.d("DataManager", "处理数据包 $packetIndex: 数据类型=${packet.getDataType()}")
            
            val channelData = packet.getChannelData()
            if (channelData != null) {
                Log.d("DataManager", "数据包 $packetIndex 有 ${channelData.size} 个通道")
                for ((channelIndex, channel) in channelData.withIndex()) {
                    Log.d("DataManager", "通道 $channelIndex 数据长度: ${channel.size}")
                    if (channel.isNotEmpty()) {
                        Log.d("DataManager", "通道 $channelIndex 前3个值: ${channel.take(3).joinToString(", ")}")
                        // 立即发送原始数据到图表
                        if (realTimeCallback != null) {
                            realTimeCallback!!.onRawDataAvailable(channelIndex, channel)
                            Log.d("DataManager", "已发送原始数据到通道 $channelIndex，数据长度: ${channel.size}")
                        } else {
                            Log.e("DataManager", "realTimeCallback 为空，无法发送数据")
                        }
                    } else {
                        Log.w("DataManager", "通道 $channelIndex 数据为空")
                    }
                }
            } else {
                Log.w("DataManager", "数据包 $packetIndex 没有通道数据")
            }
        }
    }
    
    /**
     * 流式数据处理 - 将数据包按通道合并并处理
     */
    private fun processStreamingData(packets: List<SensorData>) {
        if (packets.isEmpty()) return
        
        Log.d("DataManager", "开始流式数据处理，处理 ${packets.size} 个数据包")
        
            // 1. 通道映射
            ensureDataMapper()
        val mappedPackets = if (dataMapperInitialized && dataMapper != null) {
                try {
                val mapped = dataMapper!!.mapSensorDataList(packets)
                    Log.d("DataManager", "通道映射完成，映射了 ${mapped.size} 个数据包")
                    mapped
                } catch (e: Exception) {
                    Log.e("DataManager", "通道映射失败: ${e.message}")
                    packets
                }
            } else {
                Log.w("DataManager", "数据映射器未初始化，跳过通道映射")
                packets
            }
            
        // 2. 按通道合并数据
        for (packet in mappedPackets) {
            val dataType = packet.getDataType()
            if (currentDataType == null) {
                currentDataType = dataType
                Log.d("DataManager", "设置当前数据类型: $dataType")
            }
            
            val channelData = packet.getChannelData()
            if (channelData != null) {
                for ((channelIndex, channel) in channelData.withIndex()) {
                    if (!channelBuffers.containsKey(channelIndex)) {
                        channelBuffers[channelIndex] = mutableListOf()
                        processedChannelBuffers[channelIndex] = mutableListOf()
                    }
                    channelBuffers[channelIndex]!!.addAll(channel)
                }
            }
        }
        
        // 检查是否达到处理条件
        val totalSamples = channelBuffers.values.firstOrNull()?.size ?: 0
        if (totalSamples > 0) {
            Log.d("DataManager", "当前总样本数: $totalSamples, 需要样本数: $minSamplesForMetrics")
        }
        
        // 3. 检查处理条件：数据量足够且时间间隔合适
        val currentTime = System.currentTimeMillis()
        val shouldProcess = totalSamples >= minSamplesForMetrics && 
                           (currentTime - lastProcessTime) >= processingInterval
        
        if (shouldProcess) {
            Log.d("DataManager", "满足处理条件，开始流式信号处理和指标计算")
            processStreamingWindow()
            lastProcessTime = currentTime
        } else {
            Log.d("DataManager", "不满足处理条件 - 数据量: ${totalSamples}/${minSamplesForMetrics}, 时间间隔: ${currentTime - lastProcessTime}ms/${processingInterval}ms")
        }
        
        // 累积映射后的数据包列表（用于UI显示）
        // 注意：这里累积所有批次的映射后数据包，用于统计和显示
        this.processedPackets.addAll(mappedPackets)
        
        // 添加调试信息（在后台线程中执行，避免阻塞UI）
        Thread {
            try {
                Log.d("DataManager", "DEBUG: 当前批次映射结果 - 输入: ${packets.size}个数据包, 映射后: ${mappedPackets.size}个数据包")
                Log.d("DataManager", "DEBUG: 累积映射后数据包总数: ${this.processedPackets.size}")
                
                // 统计当前批次的通道数量分布
                val ecg12LeadPackets = mappedPackets.filter { it.getDataType() == type.SensorData.DataType.ECG_12LEAD }
                val packetsWith8Channels = ecg12LeadPackets.count { it.getChannelData()?.size == 8 }
                val packetsWith12Channels = ecg12LeadPackets.count { it.getChannelData()?.size == 12 }
                Log.d("DataManager", "DEBUG: 当前批次ECG_12LEAD统计 - 8通道: ${packetsWith8Channels}个, 12通道: ${packetsWith12Channels}个")
                
                // 统计累积的通道数量分布
                val totalEcg12LeadPackets = this.processedPackets.filter { it.getDataType() == type.SensorData.DataType.ECG_12LEAD }
                val totalPacketsWith8Channels = totalEcg12LeadPackets.count { it.getChannelData()?.size == 8 }
                val totalPacketsWith12Channels = totalEcg12LeadPackets.count { it.getChannelData()?.size == 12 }
                Log.d("DataManager", "DEBUG: 累积ECG_12LEAD统计 - 8通道: ${totalPacketsWith8Channels}个, 12通道: ${totalPacketsWith12Channels}个")
            } catch (e: Exception) {
                Log.e("DataManager", "后台统计调试信息时发生错误: ${e.message}", e)
            }
        }.start()
    }
    
    /**
     * 处理流式数据窗口
     */
    private fun processStreamingWindow() {
        ensureStreamingSignalProcessor()
        if (!streamingSignalProcessorInitialized || streamingSignalProcessor == null) {
            Log.w("DataManager", "流式处理器未初始化，跳过处理")
            return
        }
        
        try {
            Log.d("DataManager", "开始处理流式数据窗口")
            
            // 获取采样率
            val sampleRate = when (currentDataType) {
                type.SensorData.DataType.EEG -> 250.0
                type.SensorData.DataType.ECG_2LEAD, type.SensorData.DataType.ECG_12LEAD, type.SensorData.DataType.PW_ECG_SL -> 250.0
                type.SensorData.DataType.PPG -> 50.0
                type.SensorData.DataType.STETHOSCOPE -> 8000.0
                type.SensorData.DataType.SNORE -> 8000.0
                type.SensorData.DataType.RESPIRATION -> 50.0
                else -> 250.0
            }
            
            Log.d("DataManager", "使用采样率: ${sampleRate}Hz，数据类型: $currentDataType")
            
            // 处理所有通道的数据
            val processedChannels = mutableListOf<List<Float>>()
            var localProcessedSamples = 0L
            
            for ((channelIndex, channelData) in channelBuffers) {
                if (channelData.size >= minSamplesForMetrics) {
                    Log.d("DataManager", "处理通道 $channelIndex，数据长度: ${channelData.size}")
                    
                    // 应用专业ECG信号处理：高通(0.05Hz) → 低通(100Hz) → 陷波(可选)
                    val notchFreq = if (notchFilterEnabled) 50.0 else 0.0 // 根据用户设置决定是否启用陷波滤波
                    val processedData = streamingSignalProcessor!!.processStreamingDataWithParameters(
                        channelData,
                        250.0, // ECG采样率：250Hz
                        100.0, // 低通滤波截止频率：100Hz（平衡信号清晰度和噪声抑制）
                        notchFreq, // 陷波滤波频率：50Hz或0Hz（根据用户设置）
                        10.0   // 陷波滤波品质因数：10（避免过度滤波）
                    )
                    
                    if (processedData.isNotEmpty()) {
                        processedChannels.add(processedData)
                        processedChannelBuffers[channelIndex]?.addAll(processedData)
                        localProcessedSamples += processedData.size
                        Log.d("DataManager", "通道 $channelIndex 处理完成，处理后数据长度: ${processedData.size}")
                    } else {
                        Log.w("DataManager", "通道 $channelIndex 处理失败，返回空数据")
                        processedChannels.add(channelData) // 使用原始数据
                    }
                } else {
                    Log.w("DataManager", "通道 $channelIndex 数据不足，跳过处理")
                    processedChannels.add(channelData) // 使用原始数据
                }
            }
            
            Log.d("DataManager", "所有通道处理完成，总共处理了 $localProcessedSamples 个样本")
            
            // 计算指标（使用第一个处理后的通道）
            Log.d("DataManager", "准备计算指标，处理后通道数量: ${processedChannels.size}")
            if (processedChannels.isNotEmpty()) {
                Log.d("DataManager", "第一个通道数据长度: ${processedChannels[0].size}, 最小要求: $minSamplesForMetrics")
                
                if (processedChannels[0].size >= minSamplesForMetrics) {
                    ensureIndicatorCalculator()
                if (indicatorCalculatorInitialized && indicatorCalculator != null) {
                    try {
                        // 创建临时的SensorData用于指标计算
                        val tempSensorData = SensorData()
                        tempSensorData.setDataType(currentDataType!!)
                        tempSensorData.setTimestamp(System.currentTimeMillis())
                        tempSensorData.setPacketSn(0)
                        tempSensorData.setChannelData(processedChannels)
                        
                        val metrics = indicatorCalculator!!.processCompletePipeline(tempSensorData, sampleRate.toFloat())
                        if (metrics != null && metrics.isNotEmpty()) {
                            Log.d("DataManager", "指标计算成功，获得 ${metrics.size} 个指标")
                            
                            // 特别关注心率指标
                            val heartRate = metrics["heart_rate"]
                            if (heartRate != null) {
                                Log.d("DataManager", "心率计算结果: $heartRate bpm")
                            } else {
                                Log.w("DataManager", "心率计算结果为空")
                            }
                            
                            latestMetrics = metrics
                            calculatedMetrics.clear()
                            calculatedMetrics.add(metrics)
                            
                            // 记录处理统计
                            this.totalProcessedSamples += localProcessedSamples
                        } else {
                            Log.w("DataManager", "指标计算返回空结果")
                        }
                    } catch (e: Exception) {
                        Log.e("DataManager", "指标计算失败: ${e.message}")
                    }
                }
            }
            } else {
                Log.w("DataManager", "第一个通道数据长度不足，跳过指标计算")
            }
            
            // 清理缓冲区（保留最后一部分数据用于连续性）
            val keepSamples = minSamplesForMetrics / 2
            channelBuffers.forEach { (channel, buffer) ->
                if (buffer.size > keepSamples) {
                    val toRemove = buffer.size - keepSamples
                    repeat(toRemove) {
                        if (buffer.isNotEmpty()) {
                            buffer.removeAt(0)
                        }
                    }
                }
            }
            
            // 清理处理后的缓冲区
            processedChannelBuffers.forEach { (channel, buffer) ->
                if (buffer.size > keepSamples) {
                    val toRemove = buffer.size - keepSamples
                    repeat(toRemove) {
                        if (buffer.isNotEmpty()) {
                            buffer.removeAt(0)
                        }
                    }
                }
            }
            
            Log.d("DataManager", "流式数据处理完成，保留 ${keepSamples} 个样本用于连续性")
            
            // 实时回调处理后的数据
            realTimeCallback?.let { callback ->
                processedChannels.forEachIndexed { channelIndex, processedData ->
                    if (processedData.isNotEmpty()) {
                        callback.onProcessedDataAvailable(channelIndex, processedData)
                    }
                }
                
                // 回调进度信息
                val totalSamples = channelBuffers.values.firstOrNull()?.size ?: 0
                callback.onStreamingProgress(
                    progress = (totalSamples * 100 / minSamplesForMetrics).coerceAtMost(100),
                    totalSamples = totalSamples,
                    processedSamples = localProcessedSamples.toInt()
                )
            }
            
        } catch (e: Exception) {
            Log.e("DataManager", "流式数据处理异常: ${e.message}", e)
        }
    }
    
    /**
     * 处理文件数据
     */
    fun processFileData(fileData: ByteArray, progressCallback: ((Int) -> Unit)? = null) {
        Log.d("DataManager", "开始处理文件数据，数据大小: ${fileData.size} 字节")
        
        try {
            val chunkSize = 1024
            var processedBytes = 0
            
            for (i in fileData.indices step chunkSize) {
                val endIndex = minOf(i + chunkSize, fileData.size)
                val chunk = fileData.copyOfRange(i, endIndex)
                
                onBleNotify(chunk)
                processedBytes += chunk.size
                
                // 性能优化：减少进度更新频率
                if (processedBytes % (chunkSize * 10) == 0) {
                    val progress = (processedBytes * 100 / fileData.size).coerceAtMost(100)
                    progressCallback?.invoke(progress)
                }
            }
            
            Log.d("DataManager", "文件数据处理完成，总共处理了 $processedBytes 字节")
            
        } catch (e: Exception) {
            Log.e("DataManager", "处理文件数据时发生错误: ${e.message}", e)
        }
    }
    
    // Getter方法
    fun getPacketBufferSize(): Int = packetBuffer.size
    fun getProcessedPacketsSize(): Int = processedPackets.size
    fun getCalculatedMetricsSize(): Int = calculatedMetrics.size
    fun getRawStreamSize(): Int = rawStream.size()
    fun getTotalPacketsParsed(): Long = totalPacketsParsed
    fun getPacketBuffer(): List<SensorData> = packetBuffer
    fun getProcessedPackets(): List<SensorData> = processedPackets
    fun getCalculatedMetrics(): List<Map<String, Float>> = calculatedMetrics
    fun getLatestMetrics(): Map<String, Float> = latestMetrics
    fun getChannelBuffersStatus(): Map<Int, Int> = channelBuffers.mapValues { it.value.size }
    
    // 流式处理相关getter方法
    fun getProcessedChannelBuffersStatus(): Map<Int, Int> = processedChannelBuffers.mapValues { it.value.size }
    fun getProcessedChannelData(channelIndex: Int): List<Float> = processedChannelBuffers[channelIndex] ?: emptyList()
    fun getTotalProcessedSamples(): Long = totalProcessedSamples
    fun getCurrentDataType(): type.SensorData.DataType? = currentDataType
    fun getProcessingStatus(): Map<String, Any> {
        return mapOf(
            "totalSamples" to (channelBuffers.values.firstOrNull()?.size ?: 0),
            "minSamplesRequired" to minSamplesForMetrics,
            "timeSinceLastProcess" to (System.currentTimeMillis() - lastProcessTime),
            "processingInterval" to processingInterval,
            "currentDataType" to (currentDataType?.name ?: "Unknown"),
            "totalProcessedSamples" to totalProcessedSamples
        )
    }
    
    /**
     * 获取流式信号处理器状态
     */
    fun getStreamingSignalProcessorStatus(): Map<String, Int> {
        return if (streamingSignalProcessorInitialized && streamingSignalProcessor != null) {
            streamingSignalProcessor!!.getBufferStatus()
        } else {
            emptyMap()
        }
    }
    
    /**
     * 清理缓冲区
     */
    fun cleanupBuffer() {
        try {
            // 清理原始数据包缓冲区，保留最新的100个数据包
            val maxKeepPackets = 100
            if (packetBuffer.size > maxKeepPackets) {
                val toRemove = packetBuffer.size - maxKeepPackets
                repeat(toRemove) {
                    if (packetBuffer.isNotEmpty()) {
                        packetBuffer.removeAt(0)
                    }
                }
                Log.d("DataManager", "清理了 $toRemove 个旧数据包，保留 $maxKeepPackets 个最新数据包")
            }
            
            // 清理处理后数据包缓冲区，保留最新的50个数据包
            val maxKeepProcessedPackets = 50
            if (processedPackets.size > maxKeepProcessedPackets) {
                val toRemove = processedPackets.size - maxKeepProcessedPackets
                repeat(toRemove) {
                    if (processedPackets.isNotEmpty()) {
                        processedPackets.removeAt(0)
                    }
                }
                Log.d("DataManager", "清理了 $toRemove 个旧处理后数据包，保留 $maxKeepProcessedPackets 个最新数据包")
            }
            
        } catch (e: Exception) {
            Log.e("DataManager", "清理缓冲区时发生错误: ${e.message}")
        }
    }
    
    /**
     * 计算信号质量
     */
    fun calculateSignalQuality(packet: SensorData): Float {
        if (!streamingSignalProcessorInitialized || streamingSignalProcessor == null) return 0.0f
        
        try {
            // 获取第一个通道的数据进行质量评估
            val channelData = packet.getChannelData()
            if (channelData != null && channelData.isNotEmpty()) {
                val firstChannel = channelData[0]
                if (firstChannel != null) {
                    val signal = firstChannel.toFloatArray()
                    val quality = streamingSignalProcessor!!.calculateSignalQuality(signal)
                    
                    // 添加调试信息
                    Log.d("DataManager", "信号质量计算: 通道0, 数据长度=${signal.size}, 质量=$quality")
                    return quality
                }
            }
        } catch (e: Exception) {
            Log.e("DataManager", "计算信号质量时发生错误: ${e.message}")
        }
        
        return 0.0f
    }
    
    /**
     * 应用信号处理
     */
    fun applySignalProcessing(packets: List<SensorData>): List<SensorData> {
        Log.d("DataManager", "开始应用信号处理，处理 ${packets.size} 个数据包")
        
        ensureStreamingSignalProcessor()
        if (!streamingSignalProcessorInitialized || streamingSignalProcessor == null) {
            Log.w("DataManager", "流式信号处理器未初始化，跳过信号处理")
            return packets
        }
        
        val processedPackets = mutableListOf<SensorData>()
        
        for (packet in packets) {
            try {
                val processedPacket = processSinglePacket(packet)
                processedPackets.add(processedPacket)
            } catch (e: Exception) {
                Log.e("DataManager", "处理数据包时发生错误: ${e.message}")
                processedPackets.add(packet) // 处理失败时返回原始数据包
            }
        }
        
        Log.d("DataManager", "信号处理完成，处理了 ${processedPackets.size} 个数据包")
        return processedPackets
    }
    
    /**
     * 处理单个数据包
     */
    private fun processSinglePacket(packet: SensorData): SensorData {
        val channelData = packet.getChannelData()
        if (channelData == null || channelData.isEmpty()) {
            return packet
        }
        
        val processedChannels = mutableListOf<List<Float>>()
        
        for (channel in channelData) {
            val processedChannel = when (packet.getDataType()) {
                type.SensorData.DataType.EEG -> applyEEGFilters(channel)
                type.SensorData.DataType.ECG_2LEAD, type.SensorData.DataType.ECG_12LEAD -> applyECGFilters(channel)
                type.SensorData.DataType.PPG -> applyPPGFilters(channel)
                else -> channel // 其他类型暂时不处理
            }
            processedChannels.add(processedChannel)
        }
        
        // 创建处理后的数据包
        val processedPacket = SensorData()
        processedPacket.setDataType(packet.getDataType())
        processedPacket.setTimestamp(packet.getTimestamp())
        processedPacket.setPacketSn(packet.getPacketSn())
        processedPacket.setChannelData(processedChannels)
        
        return processedPacket
    }
    
    /**
     * 应用EEG滤波器
     */
    private fun applyEEGFilters(channel: List<Float>): List<Float> {
        val signal = channel.toFloatArray()
        
        try {
            if (streamingSignalProcessor != null) {
                // 1. 带通滤波 (1-40Hz，EEG主要频率范围)
                val bandpassFiltered = streamingSignalProcessor!!.bandpassFilter(
                signal, 
                filterSettings.sampleRate.toFloat(), 
                1.0f, 
                40.0f
            )
            
                if (bandpassFiltered != null) {
                    // 2. 幅度归一化
                    val normalized = streamingSignalProcessor!!.normalizeAmplitude(bandpassFiltered)
                    
                    if (normalized != null) {
                        return normalized.toList()
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("DataManager", "EEG滤波处理失败: ${e.message}")
        }
        
        return channel // 处理失败时返回原始数据
    }
    
    /**
     * 应用ECG滤波器
     */
    private fun applyECGFilters(channel: List<Float>): List<Float> {
        val signal = channel.toFloatArray()
        
        try {
            if (streamingSignalProcessor != null) {
            // 1. 高通滤波 (0.5Hz，去除基线漂移)
                val highpassFiltered = streamingSignalProcessor!!.highpassFilter(
                signal, 
                filterSettings.sampleRate.toFloat(), 
                0.5f
            )
            
                if (highpassFiltered != null) {
                // 2. 低通滤波 (40Hz，去除高频噪声)
                    val lowpassFiltered = streamingSignalProcessor!!.lowpassFilter(
                        highpassFiltered, 
                    filterSettings.sampleRate.toFloat(), 
                    40.0f
                )
                
                if (lowpassFiltered != null) {
                    // 3. 陷波滤波 (50Hz，去除工频干扰)
                        val notchFiltered = streamingSignalProcessor!!.notchFilter(
                        lowpassFiltered, 
                        filterSettings.sampleRate.toFloat(), 
                        50.0f
                    )
                    
                    if (notchFiltered != null) {
                        return notchFiltered.toList()
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("DataManager", "ECG滤波处理失败: ${e.message}")
        }
        
        return channel // 处理失败时返回原始数据
    }
    
    /**
     * 应用PPG滤波器
     */
    private fun applyPPGFilters(channel: List<Float>): List<Float> {
        val signal = channel.toFloatArray()
        
        try {
            if (streamingSignalProcessor != null) {
            // 1. 低通滤波 (8Hz，PPG主要频率范围)
                val filtered = streamingSignalProcessor!!.lowpassFilter(
                signal, 
                filterSettings.sampleRate.toFloat(), 
                8.0f
            )
            
            if (filtered != null) {
                // 2. 去运动伪影
                    val motionArtifactRemoved = streamingSignalProcessor!!.processRealtimeChunk(
                    filtered, 
                    filterSettings.sampleRate.toFloat()
                )
                
                if (motionArtifactRemoved != null) {
                    return motionArtifactRemoved.toList()
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("DataManager", "PPG滤波处理失败: ${e.message}")
        }
        
        return channel // 处理失败时返回原始数据
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            if (parserHandle != 0L) {
                nativeCallback.destroyStreamParser(parserHandle)
                parserHandle = 0L
            }
            
            // 清理缓冲区
            packetBuffer.clear()
            processedPackets.clear()
            calculatedMetrics.clear()
            channelBuffers.clear()
            processedChannelBuffers.clear()
            rawStream.reset()
            
            // 重置状态
            totalPacketsParsed = 0L
            currentDataType = null
            lastProcessTime = 0L
            totalProcessedSamples = 0L
            
            Log.d("DataManager", "资源清理完成")
        } catch (e: Exception) {
            Log.e("DataManager", "清理资源时发生错误: ${e.message}")
        }
    }
}
