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

const props = defineProps({
  chartData: {
    type: Array,
    default: () => [],
  },
  height: {
    type: String,
    default: '360px',
  },
})

const chartRef = ref(null)
let chartInstance = null

const validData = computed(() =>
  Array.isArray(props.chartData) ? props.chartData.filter((d) => d != null) : [],
)

const xLabels = computed(() => validData.value.map((d) => d.time || String(d.index ?? '')))
const actualSeries = computed(() => validData.value.map((d) => d.actual ?? null))
const predictedSeries = computed(() => validData.value.map((d) => d.predicted ?? null))
const currentSeries = computed(() => validData.value.map((d) => d.current ?? null))
const voltageSeries = computed(() => validData.value.map((d) => d.voltage ?? null))

const hasCurrentVoltage = computed(() =>
  validData.value.some((d) => d.current != null || d.voltage != null),
)

const renderChart = () => {
  if (!chartRef.value) return
  if (!chartInstance) chartInstance = echarts.init(chartRef.value)

  const hasData = validData.value.length > 0

  const yAxes = [
    {
      type: 'value',
      name: '温度 (℃)',
      position: 'left',
      nameTextStyle: { color: '#64748b', fontSize: 11 },
      axisLabel: { color: '#64748b', fontSize: 11 },
      axisLine: { show: true, lineStyle: { color: '#409EFF' } },
      splitLine: { lineStyle: { type: 'dashed', color: 'rgba(148,163,184,0.4)' } },
    },
  ]

  if (hasCurrentVoltage.value) {
    yAxes.push({
      type: 'value',
      name: '电流 (A) / 电压 (V)',
      position: 'right',
      nameTextStyle: { color: '#64748b', fontSize: 11 },
      axisLabel: { color: '#64748b', fontSize: 11 },
      axisLine: { show: true, lineStyle: { color: '#E6A23C' } },
      splitLine: { show: false },
    })
  }

  const series = [
    {
      name: '实际温度 (℃)',
      type: 'line',
      yAxisIndex: 0,
      smooth: false,
      symbol: 'none',
      lineStyle: { width: 2, type: 'solid' },
      data: actualSeries.value,
    },
    {
      name: '预测温度 (℃)',
      type: 'line',
      yAxisIndex: 0,
      smooth: false,
      symbol: 'none',
      lineStyle: { width: 2, type: 'dashed' },
      data: predictedSeries.value,
    },
  ]

  if (hasCurrentVoltage.value) {
    series.push(
      {
        name: '电流 (A)',
        type: 'line',
        yAxisIndex: 1,
        smooth: false,
        symbol: 'none',
        lineStyle: { width: 1.5, type: 'solid' },
        data: currentSeries.value,
      },
      {
        name: '电压 (V)',
        type: 'line',
        yAxisIndex: 1,
        smooth: false,
        symbol: 'none',
        lineStyle: { width: 1.5, type: 'dotted' },
        data: voltageSeries.value,
      },
    )
  }

  const legendData = hasCurrentVoltage.value
    ? ['实际温度 (℃)', '预测温度 (℃)', '电流 (A)', '电压 (V)']
    : ['实际温度 (℃)', '预测温度 (℃)']

  chartInstance.setOption(
    {
      animation: false,
      color: ['#409EFF', '#F56C6C', '#E6A23C', '#67C23A'],
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255,255,255,0.96)',
        borderColor: '#e2e8f0',
        borderWidth: 1,
        textStyle: { color: '#334155' },
        extraCssText: 'box-shadow: 0 8px 24px rgba(15,23,42,0.14); border-radius: 10px;',
        formatter(params) {
          if (!params?.length) return ''
          const lines = [
            `<div style="margin-bottom:6px;font-weight:600;font-size:12px;">${params[0].axisValue}</div>`,
          ]
          params.forEach((item) => {
            const val = item.data != null ? Number(item.data).toFixed(4) : '--'
            const unit = item.seriesName.includes('℃') ? ' ℃' :
                         item.seriesName.includes('(A)') ? ' A' :
                         item.seriesName.includes('(V)') ? ' V' : ''
            lines.push(
              `<div style="display:flex;align-items:center;gap:8px;min-width:200px;justify-content:space-between;">
                <span>${item.marker}${item.seriesName}</span>
                <strong>${val}${unit}</strong>
              </div>`,
            )
          })
          return lines.join('')
        },
      },
      legend: {
        bottom: 4,
        itemWidth: 20,
        itemHeight: 10,
        textStyle: { color: '#475569', fontSize: 12 },
        data: legendData,
      },
      grid: { top: 16, left: 16, right: hasCurrentVoltage.value ? 80 : 20, bottom: 52, containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xLabels.value,
        axisLabel: {
          color: '#64748b',
          fontSize: 11,
          rotate: 35,
          interval: Math.max(0, Math.floor(xLabels.value.length / 12) - 1),
          hideOverlap: true,
        },
        axisLine: { lineStyle: { color: '#cbd5e1' } },
      },
      yAxis: yAxes,
      series,
      graphic: hasData
        ? []
        : [
            {
              type: 'text',
              left: 'center',
              top: 'middle',
              style: { text: '暂无评估数据', fill: '#94a3b8', fontSize: 14 },
            },
          ],
      dataZoom: hasData
        ? [
            { type: 'inside', start: 0, end: 100 },
            { type: 'slider', start: 0, end: 100, height: 20, bottom: 28 },
          ]
        : [],
    },
    true,
  )
}

const resizeChart = () => chartInstance?.resize()

watch(() => props.chartData, async () => { await nextTick(); renderChart() }, { deep: true })

onMounted(async () => {
  await nextTick()
  renderChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  chartInstance?.dispose()
  chartInstance = null
})
</script>

<template>
  <div ref="chartRef" :style="{ width: '100%', height: props.height }" />
</template>

