<template>
  <div class="temperature-chart">
    <div class="chart-container">
      <div ref="chartRef" class="chart" style="width: 100%; height: 500px;"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

// Props
const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  },
  sensorColumns: {
    type: Array,
    default: () => []
  }
})

// 响应式数据
const chartRef = ref(null)
let chartInstance = null

// 暴露方法给父组件调用
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 暴露方法
defineExpose({
  resizeChart
})

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    updateChart()
  }
}

  // 更新图表数据
  const updateChart = () => {
    if (!chartInstance || !props.chartData || props.chartData.length === 0) {
      return
    }

    // 准备图表数据 - 按时间排序
    const sortedData = [...props.chartData].sort((a, b) => new Date(a.datetime) - new Date(b.datetime))
    const series = []

    // 为每个传感器创建数据系列
    props.sensorColumns.forEach(sensor => {
      // 过滤出有效的数据点
      const validDataPoints = sortedData
        .map(item => {
          const value = item[sensor.sensorName]
          return {
            datetime: item.datetime,
            value: value !== null && value !== undefined && !isNaN(value) ? parseFloat(value) : null
          }
        })
        .filter(point => point.value !== null)

      // 只有当传感器有有效数据时才添加到系列中
      if (validDataPoints.length > 0) {
        series.push({
          name: sensor.sensorName,
          type: 'line',
          data: validDataPoints.map(point => [point.datetime, point.value]),
          showSymbol: false,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 1
          },
          itemStyle: {
            borderWidth: 1
          }
        })
      }
    })



  // 图表配置
  const option = {
    title: {
      text: '温度监控趋势图',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#303133'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e4e7ed',
      borderWidth: 1,
      textStyle: {
        color: '#303133'
      },
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function (params) {
        // 格式化时间显示
        const formatTime = (timeStr) => {
          const date = new Date(timeStr)
          return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
        }
        let result = `<div style="font-weight: bold; margin-bottom: 8px; color: #303133;">${formatTime(params[0].axisValue)}</div>`
        params.forEach(param => {
          if (param.value !== null && param.value !== undefined) {
            // 数据格式为 [datetime, value]，所以取第二个元素作为温度值
            const temperature = Array.isArray(param.value) ? param.value[1] : param.value
            result += `<div style="margin: 5px 0; display: flex; align-items: center;">
              <span style="display: inline-block; width: 12px; height: 12px; background: ${param.color}; margin-right: 8px; border-radius: 2px;"></span>
              <span style="color: #606266;">${param.seriesName}: </span>
              <span style="font-weight: bold; color: #303133; margin-left: 4px;">${temperature.toFixed(2)}°C</span>
            </div>`
          }
        })
        return result
      }
    },
    legend: {
      data: series.map(s => s.name),
      top: 30,
      type: 'scroll',
      textStyle: {
        color: '#606266'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#606266',
        formatter: function (value) {
          // 格式化时间显示
          const date = new Date(value)
          return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
        },
        rotate: 45
      },
      axisTick: {
        lineStyle: {
          color: '#e4e7ed'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '温度 (°C)',
      nameLocation: 'middle',
      nameGap: 40,
      nameTextStyle: {
        color: '#606266'
      },
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#606266',
        formatter: '{value} °C'
      },
      axisTick: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
    },
    series: series,
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        type: 'slider',
        start: 0,
        end: 100,
        bottom: 10,
        height: 20,
        borderColor: '#e4e7ed',
        fillerColor: 'rgba(64, 158, 255, 0.1)',
        handleStyle: {
          color: '#409eff'
        }
      }
    ]
  }

  chartInstance.setOption(option, true)
}

// 监听数据变化
watch(
  () => [props.chartData, props.sensorColumns],
  () => {
    nextTick(() => {
      updateChart()
      // 延迟重新调整大小，确保DOM已更新
      setTimeout(() => {
        if (chartInstance) {
          chartInstance.resize()
        }
      }, 100)
    })
  },
  { deep: true }
)

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.temperature-chart {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 500px;
    flex: 1;
    display: flex;
    flex-direction: column;

    .chart {
      width: 100% !important;
      height: 100% !important;
      flex: 1;
    }
  }
}
</style>
