package com.example.cmake_project_test

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.util.Log
import type.SensorData

/**
 * 动态图表管理器
 * 负责根据设备类型动态创建和管理图表
 */
class DynamicChartManager(
    private val context: Context,
    private val chartsContainer: LinearLayout,
    private val chartTitle: TextView?
) {
    
    // 全屏按钮点击监听器
    private var onChartFullscreenClickListener: ((chartIndex: Int, chart: DynamicChartView) -> Unit)? = null
    
    private val charts = mutableListOf<DynamicChartView>()
    private var currentDeviceType: SensorData.DataType? = null
    private var currentChannelCount = 0
    
    /**
     * 设备配置信息
     */
    data class DeviceConfig(
        val deviceName: String,
        val channelCount: Int,
        val sampleRate: Float,
        val timeWindow: Float,
        val maxDataPoints: Int,
        val channelNames: List<String>
    )
    
    /**
     * 根据设备类型获取配置
     */
    private fun getDeviceConfig(dataType: SensorData.DataType): DeviceConfig {
        return when (dataType) {
            SensorData.DataType.EEG -> DeviceConfig(
                deviceName = "脑电设备",
                channelCount = 8, // 6个EEG + 2个EOG
                sampleRate = 250f,
                timeWindow = 2.5f,
                maxDataPoints = 625, // 250Hz * 2.5s = 625个点
                channelNames = listOf("Fp1", "Fp2", "F3", "F4", "C3", "C4", "EOG1", "EOG2")
            )
            
            SensorData.DataType.ECG_2LEAD -> DeviceConfig(
                deviceName = "双导联心电",
                channelCount = 6, // ECG1, ECG2, EMG1, EMG2, 呼吸温度, 呼吸阻抗
                sampleRate = 250f,
                timeWindow = 2.5f,
                maxDataPoints = 625, // 250Hz * 2.5s = 625个点
                channelNames = listOf("ECG1", "ECG2", "EMG1", "EMG2", "呼吸温度", "呼吸阻抗")
            )
            
            SensorData.DataType.ECG_12LEAD -> DeviceConfig(
                deviceName = "12导联心电",
                channelCount = 12, // 映射后12个通道：I, II, III, aVR, aVL, aVF, V1, V2, V3, V4, V5, V6
                sampleRate = 250f,
                timeWindow = 2.5f,
                maxDataPoints = 625, // 250Hz * 2.5s = 625个点
                channelNames = listOf("I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6")
            )
            
            SensorData.DataType.PW_ECG_SL -> DeviceConfig(
                deviceName = "单导联心电",
                channelCount = 1,
                sampleRate = 250f,
                timeWindow = 2.5f,
                maxDataPoints = 625, // 250Hz * 2.5s = 625个点
                channelNames = listOf("单导联ECG")
            )
            
            SensorData.DataType.PPG -> DeviceConfig(
                deviceName = "血氧设备",
                channelCount = 1, // 两个通道合并为一张图
                sampleRate = 100f,
                timeWindow = 2.5f,
                maxDataPoints = 250, // 100Hz * 2.5s = 250个点
                channelNames = listOf("PPG信号") // 合并通道名称
            )
            
            SensorData.DataType.RESPIRATION -> DeviceConfig(
                deviceName = "呼吸设备",
                channelCount = 1,
                sampleRate = 100f,
                timeWindow = 2.5f,
                maxDataPoints = 250, // 100Hz * 2.5s = 250个点
                channelNames = listOf("呼吸气流")
            )
            
            SensorData.DataType.SNORE -> DeviceConfig(
                deviceName = "鼾声设备",
                channelCount = 1,
                sampleRate = 1000f,
                timeWindow = 2.5f,
                maxDataPoints = 2500, // 1000Hz * 2.5s = 2500个点
                channelNames = listOf("鼾声")
            )
            
            SensorData.DataType.STETHOSCOPE -> DeviceConfig(
                deviceName = "数字听诊器",
                channelCount = 2,
                sampleRate = 1000f,
                timeWindow = 2.5f,
                maxDataPoints = 2500, // 1000Hz * 2.5s = 2500个点
                channelNames = listOf("听诊通道1", "听诊通道2")
            )
            
            else -> DeviceConfig(
                deviceName = "未知设备",
                channelCount = 1,
                sampleRate = 250f,
                timeWindow = 2.5f,
                maxDataPoints = 625, // 250Hz * 2.5s = 625个点
                channelNames = listOf("通道")
            )
        }
    }
    
    /**
     * 根据设备类型创建图表
     */
    fun createChartsForDevice(dataType: SensorData.DataType) {
        val config = getDeviceConfig(dataType)

        Log.d("DynamicChartManager", "=== 开始创建图表 ===")
        Log.d("DynamicChartManager", "设备类型: $dataType")
        Log.d("DynamicChartManager", "设备名称: ${config.deviceName}")
        Log.d("DynamicChartManager", "通道数量: ${config.channelCount}")
        Log.d("DynamicChartManager", "当前设备类型: $currentDeviceType")
        Log.d("DynamicChartManager", "当前通道数: $currentChannelCount")

        // 如果设备类型没有变化，不需要重新创建
        if (currentDeviceType == dataType && currentChannelCount == config.channelCount) {
            Log.d("DynamicChartManager", "设备类型未变化，跳过创建")
            return
        }

        Log.d("DynamicChartManager", "为设备 ${config.deviceName} 创建 ${config.channelCount} 个图表")

        // 清除现有图表
        clearAllCharts()

        // 更新标题（如果存在）
        chartTitle?.text = "${config.deviceName}实时监测"

        // 特殊处理PPG设备：创建多通道单图表
        if (dataType == type.SensorData.DataType.PPG) {
            val chartView = DynamicChartView(context)

            // 设置为多通道模式，原始有两个通道
            chartView.setMultiChannelMode(2)

            // 设置图表配置
            chartView.setChartConfig(
                title = "红光PPG/红外光PPG",
                channelIdx = 1,
                device = config.deviceName,
                maxPoints = config.maxDataPoints,
                sampleRateHz = config.sampleRate,
                timeWindowSec = config.timeWindow
            )

            // 设置布局参数
            val layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                marginStart = 8
                marginEnd = 8
                topMargin = 4
                bottomMargin = 4
            }

            chartsContainer.addView(chartView, layoutParams)
            charts.add(chartView)
            
            // 设置全屏按钮点击监听器
            chartView.setOnFullscreenClickListener {
                onChartFullscreenClickListener?.invoke(0, chartView)
            }

            currentDeviceType = dataType
            currentChannelCount = config.channelCount
            return
        }

        // 创建新图表
        for (i in 0 until config.channelCount) {
            val chartView = DynamicChartView(context)

            // 设置图表配置
            val channelName = if (i < config.channelNames.size) config.channelNames[i] else "通道"
            chartView.setChartConfig(
                title = channelName,
                channelIdx = i + 1,
                device = config.deviceName,
                maxPoints = config.maxDataPoints,
                sampleRateHz = config.sampleRate,
                timeWindowSec = config.timeWindow
            )
            
            // 设置布局参数
            val layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                marginStart = 8
                marginEnd = 8
                topMargin = 4
                bottomMargin = 4
            }
            
            // 添加分隔线（除了最后一个图表）
            if (i < config.channelCount - 1) {
                val separator = View(context).apply {
                    setBackgroundColor(android.graphics.Color.parseColor("#CCCCCC"))
                }
                val separatorParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    2
                ).apply {
                    marginStart = 8
                    marginEnd = 8
                    topMargin = 4
                    bottomMargin = 4
                }
                chartsContainer.addView(separator, separatorParams)
            }
            
            chartsContainer.addView(chartView, layoutParams)
            charts.add(chartView)
            
            // 设置全屏按钮点击监听器
            val chartIndex = i
            chartView.setOnFullscreenClickListener {
                onChartFullscreenClickListener?.invoke(chartIndex, chartView)
            }
        }
        
        currentDeviceType = dataType
        currentChannelCount = config.channelCount
        
        Log.d("DynamicChartManager", "=== 图表创建完成 ===")
        Log.d("DynamicChartManager", "成功创建 ${charts.size} 个图表")
        Log.d("DynamicChartManager", "图表容器子视图数量: ${chartsContainer.childCount}")
    }
    
    /**
     * 更新图表数据
     */
    fun updateChartsData(channelData: List<List<Float>>) {
        Log.d("DynamicChartManager", "=== 开始更新图表数据 ===")
        Log.d("DynamicChartManager", "图表数量: ${charts.size}")
        Log.d("DynamicChartManager", "数据通道数: ${channelData.size}")
        
        if (charts.isEmpty() || channelData.isEmpty()) {
            Log.w("DynamicChartManager", "图表为空或数据为空，跳过更新")
            return
        }

        // 性能优化：减少日志输出
        val dataChannels = channelData.size
        val chartCount = charts.size
        
        Log.d("DynamicChartManager", "数据通道: $dataChannels, 图表数量: $chartCount")

        // 特殊处理PPG设备的多通道数据
        if (currentDeviceType == type.SensorData.DataType.PPG && chartCount == 1) {
            Log.d("DynamicChartManager", "PPG多通道数据更新: 通道数=${channelData.size}, 数据点=${channelData.map { it.size }}")
            // PPG设备只有一个图表，但有两个通道的数据
            val chart = charts[0]
            chart.updateMultiChannelData(channelData)
            return
        }

        // 更新每个图表的数据 - 并行处理
        for (i in 0 until minOf(dataChannels, chartCount)) {
            val chart = charts[i]
            val data = channelData[i]
            chart.updateData(data)
        }

        // 如果数据通道少于图表，清空多余的图表
        if (dataChannels < chartCount) {
            for (i in dataChannels until chartCount) {
                charts[i].clearData()
            }
        }
    }
    
    /**
     * 清空所有图表
     */
    fun clearAllCharts() {
        try {
            Log.d("DynamicChartManager", "=== 开始清空所有图表 ===")
            Log.d("DynamicChartManager", "当前图表数量: ${charts.size}")
            Log.d("DynamicChartManager", "容器子视图数量: ${chartsContainer.childCount}")
            
            if (charts.isEmpty()) {
                Log.d("DynamicChartManager", "图表列表为空，跳过清理")
                return
            }
            
            // 清理图表数据
            charts.forEachIndexed { index, chart ->
                try {
                    Log.d("DynamicChartManager", "清理图表 $index")
                    Log.d("DynamicChartManager", "图表类型: ${chart.javaClass.simpleName}")
                    
                    // 清理图表数据
                    chart.clearData()
                    Log.d("DynamicChartManager", "图表 $index 数据清理完成")
                    
                    // 清理触摸事件处理器
                    chart.cleanupTouchHandlers()
                    Log.d("DynamicChartManager", "图表 $index 触摸处理器清理完成")
                    
                } catch (e: Exception) {
                    Log.e("DynamicChartManager", "清理图表 $index 失败: ${e.message}", e)
                    Log.e("DynamicChartManager", "异常堆栈: ${e.stackTraceToString()}")
                }
            }
            
            // 清空图表列表
            charts.clear()
            Log.d("DynamicChartManager", "图表列表已清空")
            
            // 移除所有子视图
            chartsContainer.removeAllViews()
            Log.d("DynamicChartManager", "容器子视图已移除")
            
            // 重置状态
            currentDeviceType = null
            currentChannelCount = 0
            Log.d("DynamicChartManager", "状态已重置")
            
            Log.d("DynamicChartManager", "=== 清空所有图表完成 ===")
            
        } catch (e: Exception) {
            Log.e("DynamicChartManager", "清空图表时发生异常: ${e.message}", e)
            Log.e("DynamicChartManager", "异常堆栈: ${e.stackTraceToString()}")
        }
    }
    
    /**
     * 重置所有图表视口
     */
    fun resetAllCharts() {
        charts.forEach { chart ->
            chart.resetViewport()
        }
    }
    
    /**
     * 获取当前图表列表
     */
    fun getCharts(): List<DynamicChartView> = charts.toList()
    
    /**
     * 获取当前设备类型
     */
    fun getCurrentDeviceType(): SensorData.DataType? = currentDeviceType
    
    /**
     * 获取当前通道数量
     */
    fun getCurrentChannelCount(): Int = currentChannelCount
    
    /**
     * 获取当前设备配置
     */
    fun getCurrentDeviceConfig(): DeviceConfig? {
        return currentDeviceType?.let { getDeviceConfig(it) }
    }
    
    /**
     * 设置图表全屏按钮点击监听器
     */
    fun setOnChartFullscreenClickListener(listener: (chartIndex: Int, chart: DynamicChartView) -> Unit) {
        onChartFullscreenClickListener = listener
    }
}
