package com.example.cmake_project_test

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ScaleGestureDetector
import kotlin.math.max
import kotlin.math.min

/**
 * 可调节的通用生理信号图表视图
 * 支持多种设备类型和通道数量的动态显示，具有缩放、平移、时间窗口调节等功能
 */
class DynamicChartView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint().apply {
        color = Color.BLUE
        strokeWidth = 2f
        style = Paint.Style.STROKE
        isAntiAlias = false // 关闭抗锯齿，提高绘制性能
    }

    private val gridPaint = Paint().apply {
        color = Color.LTGRAY
        strokeWidth = 1f
        style = Paint.Style.STROKE
        alpha = 80
    }

    private val textPaint = Paint().apply {
        color = Color.BLACK
        textSize = 20f
        isAntiAlias = true
    }

    private val controlPaint = Paint().apply {
        color = Color.RED
        strokeWidth = 3f
        style = Paint.Style.STROKE
        isAntiAlias = true
    }

    private val path = Path()
    private var dataPoints = mutableListOf<Float>()
    private var maxDataPoints = 1000 // 默认数据点数量
    private var minValue = Float.MAX_VALUE
    private var maxValue = Float.MIN_VALUE
    private var isDataAvailable = false
    
    // 累积数据点计数器
    private var totalDataPointsReceived = 0L
    
    // 全屏模式和自定义Y轴范围
    private var isFullscreenMode = false
    private var customMinValue: Float? = null
    private var customMaxValue: Float? = null
    
    // 全屏按钮
    private var fullscreenButtonRect = RectF()
    private var showFullscreenButton = true
    private var onFullscreenClickListener: (() -> Unit)? = null

    // 图表配置
    private var chartTitle = "通道"
    private var channelIndex = 0
    private var deviceType = "未知设备"
    private var sampleRate = 250f // 默认采样率
    private var timeWindow = 4f // 默认时间窗口（秒）

    // 简化的数据管理：直接显示新数据
    private val dataBuffer = mutableListOf<Float>()

    // 多通道数据支持（用于PPG等设备）
    private val multiChannelDataPoints = mutableListOf<MutableList<Float>>()
    private val multiChannelDataBuffers = mutableListOf<MutableList<Float>>()
    private var isMultiChannelMode = false
    private val channelColors = listOf(Color.RED, Color.BLUE) // 通道颜色

    // 交互控制参数
    private var scaleFactor = 1.0f
    private var translateX = 0f
    private var translateY = 0f
    private var viewportStart = 0f
    private var viewportEnd = 1.0f
    private var isDragging = false
    private var lastTouchX = 0f
    private var lastTouchY = 0f
    
    // 手势检测器
    private val scaleGestureDetector = ScaleGestureDetector(context, ScaleListener())
    
    // 控制按钮区域
    private val controlButtonRect = RectF()

    /**
     * 设置图表配置
     */
    fun setChartConfig(
        title: String,
        channelIdx: Int,
        device: String,
        maxPoints: Int,
        sampleRateHz: Float,
        timeWindowSec: Float
    ) {
        chartTitle = title
        channelIndex = channelIdx
        deviceType = device
        maxDataPoints = optimizeMaxDataPoints(maxPoints, sampleRateHz)
        sampleRate = sampleRateHz
        timeWindow = timeWindowSec
        resetViewport()
        invalidate()
    }

    /**
     * 根据设备类型和内存情况优化最大数据点数量
     */
    private fun optimizeMaxDataPoints(baseMaxPoints: Int, sampleRate: Float): Int {
        try {
            val runtime = Runtime.getRuntime()
            val maxMemoryMB = runtime.maxMemory() / 1024 / 1024

            var optimizedPoints = baseMaxPoints

            // 根据采样率调整
            optimizedPoints = when {
                sampleRate >= 8000f -> (baseMaxPoints * 0.3).toInt() // 音频设备减少到30%
                sampleRate >= 1000f -> (baseMaxPoints * 0.5).toInt() // 高速设备减少到50%
                sampleRate >= 250f -> baseMaxPoints // ECG等保持不变
                else -> (baseMaxPoints * 1.2).toInt() // 低速设备可以稍微增加
            }

            // 根据内存情况调整
            optimizedPoints = when {
                maxMemoryMB < 128 -> (optimizedPoints * 0.5).toInt() // 低内存设备
                maxMemoryMB < 256 -> (optimizedPoints * 0.75).toInt() // 中等内存设备
                maxMemoryMB >= 512 -> (optimizedPoints * 1.25).toInt() // 高内存设备
                else -> optimizedPoints
            }

            // 确保在合理范围内
            optimizedPoints = optimizedPoints.coerceIn(500, 10000)

            Log.d("DynamicChartView", "数据点限制优化: 原始=$baseMaxPoints, 优化后=$optimizedPoints, 采样率=${sampleRate}Hz, 内存=${maxMemoryMB}MB")
            return optimizedPoints

        } catch (e: Exception) {
            Log.e("DynamicChartView", "数据点限制优化失败: ${e.message}")
            return baseMaxPoints
        }
    }
    
    /**
     * 设置全屏模式
     */
    fun setFullscreenMode(isFullscreen: Boolean) {
        isFullscreenMode = isFullscreen
        // 全屏模式下隐藏全屏按钮
        showFullscreenButton = !isFullscreen
        invalidate()
    }
    
    /**
     * 设置自定义Y轴范围
     */
    fun setCustomYRange(min: Float, max: Float) {
        customMinValue = min
        customMaxValue = max
        invalidate()
    }
    
    /**
     * 清除自定义Y轴范围，恢复自动计算
     */
    fun clearCustomYRange() {
        customMinValue = null
        customMaxValue = null
        invalidate()
    }
    
    /**
     * 设置全屏按钮点击监听器
     */
    fun setOnFullscreenClickListener(listener: () -> Unit) {
        onFullscreenClickListener = listener
    }
    
    /**
     * 设置是否显示全屏按钮
     */
    fun setShowFullscreenButton(show: Boolean) {
        showFullscreenButton = show
        invalidate()
    }

    /**
     * 设置多通道模式（用于PPG等设备）
     */
    fun setMultiChannelMode(channelCount: Int) {
        isMultiChannelMode = true
        multiChannelDataPoints.clear()
        multiChannelDataBuffers.clear()

        // 初始化每个通道的数据结构
        for (i in 0 until channelCount) {
            multiChannelDataPoints.add(mutableListOf())
            multiChannelDataBuffers.add(mutableListOf())
        }
    }

    fun updateData(newData: List<Float>) {
        if (newData.isEmpty()) return

        isDataAvailable = true
        
        // 更新累积数据点计数器
        totalDataPointsReceived += newData.size

        // 直接添加新数据，来多少显示多少
        dataPoints.addAll(newData)

        // 限制数据点数量，保持滚动显示
        if (dataPoints.size > maxDataPoints) {
            val excessData = dataPoints.size - maxDataPoints
            dataPoints = dataPoints.takeLast(maxDataPoints).toMutableList()
            Log.d("DynamicChartView", "清理了 $excessData 个数据点，当前数据点: ${dataPoints.size}")
        }

        // 定期检查内存使用情况
        checkMemoryUsage()

        // 更新数据范围
        updateDataRange(newData)

        // 立即重绘
        invalidate()
    }

    /**
     * 检查内存使用情况，必要时进行清理
     */
    private fun checkMemoryUsage() {
        try {
            // 每1000个数据点检查一次内存使用情况
            if (totalDataPointsReceived % 1000 == 0L) {
                val runtime = Runtime.getRuntime()
                val usedMemory = runtime.totalMemory() - runtime.freeMemory()
                val maxMemory = runtime.maxMemory()
                val memoryUsagePercent = (usedMemory.toDouble() / maxMemory.toDouble()) * 100

                Log.d("DynamicChartView", "内存使用情况: ${usedMemory / 1024 / 1024}MB/${maxMemory / 1024 / 1024}MB (${String.format("%.1f", memoryUsagePercent)}%)")

                // 如果内存使用超过80%，强制清理
                if (memoryUsagePercent > 80.0) {
                    Log.w("DynamicChartView", "内存使用过高 (${String.format("%.1f", memoryUsagePercent)}%)，执行紧急清理")
                    emergencyCleanup()
                }
            }
        } catch (e: Exception) {
            Log.e("DynamicChartView", "检查内存使用情况失败: ${e.message}")
        }
    }

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

            // 强制清理数据点，只保留最新的50%数据
            val keepSize = (dataPoints.size * 0.5).toInt()
            if (keepSize > 0 && dataPoints.size > keepSize) {
                dataPoints = dataPoints.takeLast(keepSize).toMutableList()
                Log.d("DynamicChartView", "紧急清理数据点，保留 $keepSize 个数据点")
            }

            // 清理多通道数据
            multiChannelDataPoints.forEachIndexed { index, channelData ->
                val keepChannelSize = (channelData.size * 0.5).toInt()
                if (keepChannelSize > 0 && channelData.size > keepChannelSize) {
                    multiChannelDataPoints[index] = channelData.takeLast(keepChannelSize).toMutableList()
                }
            }

            // 重新计算数据范围
            updateDataRange(dataPoints)

            // 强制垃圾回收
            System.gc()

            Log.d("DynamicChartView", "=== 紧急内存清理完成 ===")

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

    /**
     * 获取当前数据点数量
     */
    fun getDataPointCount(): Int {
        return if (isMultiChannelMode) {
            multiChannelDataPoints.sumOf { it.size }
        } else {
            dataPoints.size
        }
    }

    /**
     * 裁剪数据到指定大小
     */
    fun trimDataToSize(maxSize: Int) {
        try {
            if (isMultiChannelMode) {
                // 多通道模式
                multiChannelDataPoints.forEachIndexed { index, channelData ->
                    if (channelData.size > maxSize) {
                        multiChannelDataPoints[index] = channelData.takeLast(maxSize).toMutableList()
                    }
                }
                // 重新计算数据范围
                updateMultiChannelDataRange()
            } else {
                // 单通道模式
                if (dataPoints.size > maxSize) {
                    dataPoints = dataPoints.takeLast(maxSize).toMutableList()
                    // 重新计算数据范围
                    updateDataRange(dataPoints)
                }
            }

            // 重绘
            invalidate()
            Log.d("DynamicChartView", "数据已裁剪到 $maxSize 个点")

        } catch (e: Exception) {
            Log.e("DynamicChartView", "裁剪数据失败: ${e.message}")
        }
    }

    /**
     * 更新多通道数据（用于PPG等设备）
     */
    fun updateMultiChannelData(channelData: List<List<Float>>) {
        if (channelData.isEmpty() || !isMultiChannelMode) {
            Log.d("DynamicChartView", "跳过多通道更新: channelData.isEmpty=${channelData.isEmpty()}, isMultiChannelMode=$isMultiChannelMode")
            return
        }

        Log.d("DynamicChartView", "多通道数据更新: 通道数=${channelData.size}, 每个通道数据点=${channelData.map { it.size }}")
        isDataAvailable = true
        
        // 更新累积数据点计数器（使用第一个通道的数据点数量）
        if (channelData.isNotEmpty()) {
            totalDataPointsReceived += channelData[0].size
        }

        // 直接添加新数据，来多少显示多少
        for (channelIndex in channelData.indices) {
            if (channelIndex >= multiChannelDataPoints.size) {
                Log.w("DynamicChartView", "通道索引超出范围: $channelIndex >= ${multiChannelDataPoints.size}")
                continue
            }

            val channelDataPoints = multiChannelDataPoints[channelIndex]
            channelDataPoints.addAll(channelData[channelIndex])

            // 限制数据点数量，保持滚动显示
            if (channelDataPoints.size > maxDataPoints) {
                multiChannelDataPoints[channelIndex] = channelDataPoints.takeLast(maxDataPoints).toMutableList()
            }

            Log.d("DynamicChartView", "通道$channelIndex 添加了${channelData[channelIndex].size}个数据点")
        }

        // 更新数据范围 - 计算所有通道的数据范围
        updateMultiChannelDataRange()

        Log.d("DynamicChartView", "多通道数据处理完成: 通道数据点=${multiChannelDataPoints.map { it.size }}, 范围=${minValue}-${maxValue}")

        // 检查内存使用情况
        checkMemoryUsage()

        // 立即重绘
        invalidate()
    }
    
    private fun updateDataRange(newData: List<Float>) {
        // 如果设置了自定义Y轴范围，使用自定义范围
        if (customMinValue != null && customMaxValue != null) {
            minValue = customMinValue!!
            maxValue = customMaxValue!!
            return
        }
        
        // 使用全部数据点计算范围，提供更准确的范围
        if (dataPoints.isEmpty()) return

        // 计算全部数据点的范围
        minValue = dataPoints.minOrNull() ?: 0f
        maxValue = dataPoints.maxOrNull() ?: 0f

        // 确保有足够的显示范围
        val range = maxValue - minValue
        if (range < 0.1f) {
            val center = (maxValue + minValue) / 2
            minValue = center - 0.05f
            maxValue = center + 0.05f
        } else {
            val margin = range * 0.1f
            minValue -= margin
            maxValue += margin
        }
    }

    /**
     * 更新多通道数据范围
     */
    private fun updateMultiChannelDataRange() {
        // 如果设置了自定义Y轴范围，使用自定义范围
        if (customMinValue != null && customMaxValue != null) {
            minValue = customMinValue!!
            maxValue = customMaxValue!!
            Log.d("DynamicChartView", "使用自定义Y轴范围: ${minValue}-${maxValue}")
            return
        }
        
        if (multiChannelDataPoints.isEmpty()) {
            Log.w("DynamicChartView", "多通道数据点为空，无法计算范围")
            return
        }

        // 计算所有通道的最小值和最大值
        var globalMin = Float.MAX_VALUE
        var globalMax = Float.MIN_VALUE
        var hasValidData = false

        for (channelIndex in multiChannelDataPoints.indices) {
            val channelData = multiChannelDataPoints[channelIndex]
            if (channelData.isNotEmpty()) {
                val channelMin = channelData.minOrNull() ?: 0f
                val channelMax = channelData.maxOrNull() ?: 0f
                globalMin = minOf(globalMin, channelMin)
                globalMax = maxOf(globalMax, channelMax)
                hasValidData = true
                Log.d("DynamicChartView", "通道$channelIndex: 范围=${channelMin}-${channelMax}, 数据点=${channelData.size}")
            }
        }

        if (!hasValidData) {
            Log.w("DynamicChartView", "没有有效的多通道数据")
            return
        }

        minValue = globalMin
        maxValue = globalMax

        Log.d("DynamicChartView", "多通道全局范围: ${minValue}-${maxValue}")

        // 确保有足够的显示范围
        val range = maxValue - minValue
        if (range < 0.1f) {
            val center = (maxValue + minValue) / 2
            minValue = center - 0.05f
            maxValue = center + 0.05f
        } else {
            val margin = range * 0.1f
            minValue -= margin
            maxValue += margin
        }

        Log.d("DynamicChartView", "多通道显示范围: ${minValue}-${maxValue}")
    }
    
    fun clearData() {
        try {
            Log.d("DynamicChartView", "=== 开始清理图表数据 ===")
            
            // 清理单通道数据
            dataPoints.clear()
            dataBuffer.clear()
            Log.d("DynamicChartView", "单通道数据已清理")
            
            // 清除多通道数据
            multiChannelDataPoints.forEachIndexed { index, channelData ->
                try {
                    channelData.clear()
                } catch (e: Exception) {
                    Log.e("DynamicChartView", "清理多通道数据 $index 失败: ${e.message}", e)
                }
            }
            multiChannelDataBuffers.forEachIndexed { index, channelBuffer ->
                try {
                    channelBuffer.clear()
                } catch (e: Exception) {
                    Log.e("DynamicChartView", "清理多通道缓冲区 $index 失败: ${e.message}", e)
                }
            }
            Log.d("DynamicChartView", "多通道数据已清理")
            
            // 重置状态
            isDataAvailable = false
            totalDataPointsReceived = 0L // 重置累积数据点计数器
            Log.d("DynamicChartView", "数据状态已重置")

            // 重置视口
            resetViewport()
            Log.d("DynamicChartView", "视口已重置")
            
            // 重绘
            invalidate()
            Log.d("DynamicChartView", "=== 图表数据清理完成 ===")
            
        } catch (e: Exception) {
            Log.e("DynamicChartView", "清理图表数据时发生异常: ${e.message}", e)
            Log.e("DynamicChartView", "异常堆栈: ${e.stackTraceToString()}")
        }
    }
    
    /**
     * 清理触摸事件处理器
     */
    fun cleanupTouchHandlers() {
        try {
            Log.d("DynamicChartView", "=== 开始清理触摸事件处理器 ===")
            
            // 重置触摸状态
            isDragging = false
            lastTouchX = 0f
            lastTouchY = 0f
            
            // 清理全屏按钮监听器
            onFullscreenClickListener = null
            
            Log.d("DynamicChartView", "=== 触摸事件处理器清理完成 ===")
            
        } catch (e: Exception) {
            Log.e("DynamicChartView", "清理触摸事件处理器时发生异常: ${e.message}", e)
            Log.e("DynamicChartView", "异常堆栈: ${e.stackTraceToString()}")
        }
    }
    
    /**
     * 当视图从窗口分离时调用
     */
    override fun onDetachedFromWindow() {
        try {
            Log.d("DynamicChartView", "=== onDetachedFromWindow 开始 ===")
            
            // 清理触摸事件处理器
            cleanupTouchHandlers()
            
            // 清理数据
            clearData()
            
            Log.d("DynamicChartView", "=== onDetachedFromWindow 完成 ===")
            
        } catch (e: Exception) {
            Log.e("DynamicChartView", "onDetachedFromWindow 异常: ${e.message}", e)
            Log.e("DynamicChartView", "异常堆栈: ${e.stackTraceToString()}")
        } finally {
            super.onDetachedFromWindow()
        }
    }

    /**
     * 重置视口到默认状态
     */
    fun resetViewport() {
        scaleFactor = 1.0f
        translateX = 0f
        translateY = 0f
        viewportStart = 0f
        viewportEnd = 1.0f
        invalidate()
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        scaleGestureDetector.onTouchEvent(event)
        
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                val x = event.x
                val y = event.y

                // 检查是否点击了全屏按钮
                if (showFullscreenButton && fullscreenButtonRect.contains(x, y)) {
                    onFullscreenClickListener?.invoke()
                    return true
                }

                // 开始拖拽
                isDragging = true
                lastTouchX = x
                lastTouchY = y
                return true
            }
            
            MotionEvent.ACTION_MOVE -> {
                if (isDragging) {
                    val deltaX = event.x - lastTouchX
                    val deltaY = event.y - lastTouchY
                    
                    translateX += deltaX
                    translateY += deltaY
                    
                    // 限制平移范围
                    val maxTranslate = width * 0.5f
                    translateX = translateX.coerceIn(-maxTranslate, maxTranslate)
                    translateY = translateY.coerceIn(-maxTranslate, maxTranslate)
                    
                    lastTouchX = event.x
                    lastTouchY = event.y
                    invalidate()
                    return true
                }
            }
            
            MotionEvent.ACTION_UP -> {
                isDragging = false
                return true
            }
        }
        
        return super.onTouchEvent(event)
    }

    private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
        override fun onScale(detector: ScaleGestureDetector): Boolean {
            scaleFactor *= detector.scaleFactor
            scaleFactor = scaleFactor.coerceIn(0.2f, 5.0f)
            invalidate()
            return true
        }
    }

    override fun onDraw(canvas: Canvas) {
        try {
            super.onDraw(canvas)
            
            val width = width.toFloat()
            val height = height.toFloat()
            
            // 应用变换
            canvas.save()
            canvas.translate(translateX, translateY)
            canvas.scale(scaleFactor, scaleFactor, width / 2, height / 2)
            
            // 绘制网格
            drawGrid(canvas, width, height)
            
            // 绘制标题和通道信息
            drawTitle(canvas, width, height)
            
            // 绘制数据统计
            drawStats(canvas, width, height)
            
            // 绘制全屏按钮
            if (showFullscreenButton) {
                drawFullscreenButton(canvas, width, height)
            }

            // 如果没有数据，显示默认内容
            if (!isDataAvailable) {
                drawDefaultContent(canvas, width, height)
            } else {
                // 绘制曲线 - 检查单通道或多通道数据
                val hasDataToDraw = if (isMultiChannelMode) {
                    multiChannelDataPoints.any { it.size > 1 }
                } else {
                    dataPoints.size > 1
                }

                if (hasDataToDraw) {
                    drawCurve(canvas, width, height)
                }
            }
            
            // 恢复画布状态
            canvas.restore()
        } catch (e: Exception) {
            Log.e("DynamicChartView", "绘制时发生异常: ${e.message}", e)
            // 确保画布状态被恢复
            try {
                canvas.restore()
            } catch (e2: Exception) {
                Log.e("DynamicChartView", "恢复画布状态失败: ${e2.message}", e2)
            }
        }
    }

    private fun drawGrid(canvas: Canvas, width: Float, height: Float) {
        val padding = if (isFullscreenMode) 20f else 60f
        val drawWidth = width - 2 * padding
        val drawHeight = height - 2 * padding
        
        // 绘制水平网格线和刻度
        val gridLines = 5
        for (i in 0..gridLines) {
            val y = padding + (drawHeight * i / gridLines)
            canvas.drawLine(padding, y, width - padding, y, gridPaint)
            
            // 只在全屏模式下绘制Y轴刻度值
            if (isFullscreenMode) {
                val value = maxValue - (maxValue - minValue) * i / gridLines
                val valueText = String.format("%.1f", value)
                canvas.drawText(valueText, 5f, y + 5f, textPaint)
            }
        }
        
        // 绘制垂直网格线和刻度
        for (i in 0..gridLines) {
            val x = padding + (drawWidth * i / gridLines)
            canvas.drawLine(x, padding, x, height - padding, gridPaint)
            
            // 只在全屏模式下绘制X轴刻度值（累积数据点索引）
            if (isFullscreenMode) {
                val dataPointIndex = if (isMultiChannelMode) {
                    // 多通道模式：使用累积数据点计数器
                    val stepSize = totalDataPointsReceived.toFloat() / gridLines
                    (stepSize * i).toInt()
                } else {
                    // 单通道模式：使用累积数据点计数器
                    val stepSize = totalDataPointsReceived.toFloat() / gridLines
                    (stepSize * i).toInt()
                }
                val indexText = dataPointIndex.toString()
                canvas.drawText(indexText, x - 10f, height - 10f, textPaint)
            }
        }
    }

    private fun drawTitle(canvas: Canvas, width: Float, height: Float) {
        val title = "$chartTitle $channelIndex"
        canvas.drawText(title, 10f, 25f, textPaint)
        
        val deviceInfo = "$deviceType (${sampleRate.toInt()}Hz)"
        canvas.drawText(deviceInfo, 10f, 50f, textPaint)
        
        // 显示当前缩放和时间窗口信息
        val scaleInfo = "缩放: ${String.format("%.1f", scaleFactor)}x"
        canvas.drawText(scaleInfo, width - 150f, 25f, textPaint)
        
        val timeInfo = "时间窗口: ${timeWindow.toInt()}秒"
        canvas.drawText(timeInfo, width - 150f, 50f, textPaint)
    }

    private fun drawStats(canvas: Canvas, width: Float, height: Float) {
        val totalDataPoints = if (isMultiChannelMode) {
            multiChannelDataPoints.sumOf { it.size }
        } else {
            dataPoints.size
        }

        val statsText = if (isMultiChannelMode) {
            "显示数据点: ${totalDataPoints} (${multiChannelDataPoints.size}通道) | 累积: ${totalDataPointsReceived}"
        } else {
            "显示数据点: ${totalDataPoints} | 累积: ${totalDataPointsReceived}"
        }
        canvas.drawText(statsText, 10f, height - 35f, textPaint)

        if (totalDataPoints > 0) {
            val rangeText = if (customMinValue != null && customMaxValue != null) {
                "Y轴范围: ${String.format("%.0f", minValue)} - ${String.format("%.0f", maxValue)} (固定)"
            } else {
                "Y轴范围: ${String.format("%.2f", minValue)} - ${String.format("%.2f", maxValue)} (自动)"
            }
            canvas.drawText(rangeText, 10f, height - 15f, textPaint)
        }
    }

    private fun drawDefaultContent(canvas: Canvas, width: Float, height: Float) {
        val centerX = width / 2
        val centerY = height / 2
        
        val hintPaint = Paint().apply {
            color = Color.GRAY
            textSize = 16f
            textAlign = Paint.Align.CENTER
            isAntiAlias = true
        }
        
        canvas.drawText("等待数据...", centerX, centerY - 20f, hintPaint)
        canvas.drawText("请先连接蓝牙设备", centerX, centerY + 20f, hintPaint)
        canvas.drawText("然后点击'启动程序'显示数据", centerX, centerY + 60f, hintPaint)
    }
    
    private fun drawFullscreenButton(canvas: Canvas, width: Float, height: Float) {
        val buttonSize = 40f
        val margin = 10f
        val buttonX = width - buttonSize - margin
        val buttonY = margin
        
        // 设置按钮区域
        fullscreenButtonRect.set(buttonX, buttonY, buttonX + buttonSize, buttonY + buttonSize)
        
        // 绘制按钮背景
        val buttonPaint = Paint().apply {
            color = Color.parseColor("#4CAF50")
            style = Paint.Style.FILL
            isAntiAlias = true
        }
        canvas.drawRoundRect(fullscreenButtonRect, 8f, 8f, buttonPaint)
        
        // 绘制按钮边框
        val borderPaint = Paint().apply {
            color = Color.WHITE
            style = Paint.Style.STROKE
            strokeWidth = 2f
            isAntiAlias = true
        }
        canvas.drawRoundRect(fullscreenButtonRect, 8f, 8f, borderPaint)
        
        // 绘制全屏图标（简单的矩形）
        val iconPaint = Paint().apply {
            color = Color.WHITE
            style = Paint.Style.STROKE
            strokeWidth = 2f
            isAntiAlias = true
        }
        
        val iconMargin = 8f
        val iconRect = RectF(
            buttonX + iconMargin,
            buttonY + iconMargin,
            buttonX + buttonSize - iconMargin,
            buttonY + buttonSize - iconMargin
        )
        canvas.drawRect(iconRect, iconPaint)
        
        // 绘制全屏文字
        val textPaint = Paint().apply {
            color = Color.WHITE
            textSize = 10f
            textAlign = Paint.Align.CENTER
            isAntiAlias = true
        }
        canvas.drawText("全屏", buttonX + buttonSize/2, buttonY + buttonSize/2 + 3f, textPaint)
    }

    private fun drawCurve(canvas: Canvas, width: Float, height: Float) {
        val padding = if (isFullscreenMode) 20f else 60f
        val drawWidth = width - 2 * padding
        val drawHeight = height - 2 * padding

        if (isMultiChannelMode && multiChannelDataPoints.isNotEmpty()) {
            Log.d("DynamicChartView", "多通道绘制: 通道数=${multiChannelDataPoints.size}, 数据点=${multiChannelDataPoints.map { it.size }}")
            // 多通道绘制模式
            for (channelIndex in multiChannelDataPoints.indices) {
                val channelData = multiChannelDataPoints[channelIndex]
                if (channelData.isEmpty()) {
                    Log.d("DynamicChartView", "通道$channelIndex 数据为空，跳过绘制")
                    continue
                }

                path.reset()

                // 设置通道颜色
                val channelPaint = Paint(paint).apply {
                    color = channelColors.getOrElse(channelIndex) { Color.GRAY }
                    strokeWidth = 2f
                }

                val xStep = if (channelData.size > 1) drawWidth / (channelData.size - 1) else drawWidth

                for (i in channelData.indices) {
                    val x = padding + i * xStep
                    val normalizedValue = (channelData[i] - minValue) / (maxValue - minValue)
                    val y = padding + (0.1f + normalizedValue * 0.8f) * drawHeight

                    if (i == 0) {
                        path.moveTo(x, y)
                    } else {
                        path.lineTo(x, y)
                    }
                }

                canvas.drawPath(path, channelPaint)
            }
        } else {
            // 单通道绘制模式
            if (dataPoints.isEmpty()) return

            path.reset()
            val xStep = if (dataPoints.size > 1) drawWidth / (dataPoints.size - 1) else drawWidth

            for (i in dataPoints.indices) {
                val x = padding + i * xStep
                val normalizedValue = (dataPoints[i] - minValue) / (maxValue - minValue)
                val y = padding + (0.1f + normalizedValue * 0.8f) * drawHeight

                if (i == 0) {
                    path.moveTo(x, y)
                } else {
                    path.lineTo(x, y)
                }
            }

            canvas.drawPath(path, paint)
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        
        val desiredHeight = 200 // 每个图表的高度
        val height = resolveSize(desiredHeight, heightMeasureSpec)
        setMeasuredDimension(widthMeasureSpec, height)
    }
    
    /**
     * 获取当前图表数据
     */
    fun getCurrentData(): List<Float> {
        return dataPoints.toList()
    }
    
    /**
     * 获取数据统计信息
     */
    fun getDataStats(): Map<String, Any> {
        val totalDataPoints = if (isMultiChannelMode) {
            multiChannelDataPoints.sumOf { it.size }
        } else {
            dataPoints.size
        }

        return mapOf(
            "dataPoints" to totalDataPoints,
            "multiChannelMode" to isMultiChannelMode,
            "channelCount" to if (isMultiChannelMode) multiChannelDataPoints.size else 1,
            "minValue" to minValue,
            "maxValue" to maxValue,
            "range" to (maxValue - minValue),
            "isDataAvailable" to isDataAvailable,
            "scaleFactor" to scaleFactor,
            "timeWindow" to timeWindow
        )
    }
    
    /**
     * 获取是否是多通道模式
     */
    fun isMultiChannelMode(): Boolean = isMultiChannelMode
}
