<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 renderChart = () => {
  if (!chartRef.value) return
  if (!chartInstance) chartInstance = echarts.init(chartRef.value)

  const hasData = validData.value.length > 0

  chartInstance.setOption(
    {
      animation: false,
      color: ['#409EFF', '#F56C6C'],
      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) : '--'
            lines.push(
              `<div style="display:flex;align-items:center;gap:8px;min-width:180px;justify-content:space-between;">
                <span>${item.marker}${item.seriesName}</span>
                <strong>${val} ℃</strong>
              </div>`,
            )
          })
          return lines.join('')
        },
      },
      legend: {
        bottom: 4,
        itemWidth: 20,
        itemHeight: 10,
        textStyle: { color: '#475569', fontSize: 12 },
        data: ['实际温度 (℃)', '预测温度 (℃)'],
      },
      grid: { top: 16, left: 16, right: 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: {
        type: 'value',
        name: '温度 (℃)',
        nameTextStyle: { color: '#64748b', fontSize: 11 },
        axisLabel: { color: '#64748b', fontSize: 11 },
        splitLine: { lineStyle: { type: 'dashed', color: 'rgba(148,163,184,0.4)' } },
      },
      series: [
        {
          name: '实际温度 (℃)',
          type: 'line',
          smooth: false,
          symbol: 'none',
          lineStyle: { width: 2, type: 'solid' },
          data: actualSeries.value,
        },
        {
          name: '预测温度 (℃)',
          type: 'line',
          smooth: false,
          symbol: 'none',
          lineStyle: { width: 2, type: 'dashed' },
          data: predictedSeries.value,
        },
      ],
      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>
