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

const props = defineProps({
  records: {
    type: Array,
    default: () => [],
  },
  totalCount: {
    type: Number,
    default: null,
  },
})

const chartRef = ref(null)
let chartInstance = null

const chartData = computed(() => {
  const source = Array.isArray(props.records) ? props.records : []

  return source
    .map((item, idx) => ({
      idx,
      time: item.time || `第${idx + 1}条`,
      current: Number(item.current),
      voltage: Number(item.voltage),
      actual_temperature: Number(item.actual_temperature),
    }))
    .filter((item) => {
      return (
        Number.isFinite(item.current) ||
        Number.isFinite(item.voltage) ||
        Number.isFinite(item.actual_temperature)
      )
    })
})

const stats = computed(() => {
  const temps = chartData.value
    .map((item) => item.actual_temperature)
    .filter((value) => Number.isFinite(value))

  return {
    count: chartData.value.length,
    max: temps.length ? Math.max(...temps) : 0,
    min: temps.length ? Math.min(...temps) : 0,
  }
})

const formatValue = (value) => {
  return Number.isFinite(value) ? Number(value).toFixed(2) : '--'
}

const getSeriesData = (key) => {
  return chartData.value.map((item) => (Number.isFinite(item[key]) ? item[key] : null))
}

const renderChart = () => {
  if (!chartRef.value) {
    return
  }

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  const hasData = chartData.value.length > 0

  chartInstance.setOption(
    {
      animation: true,
      color: ['#409EFF', '#67C23A', '#FF6B6B'],
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255,255,255,0.96)',
        borderColor: '#e2e8f0',
        borderWidth: 1,
        textStyle: {
          color: '#334155',
        },
        extraCssText: 'box-shadow: 0 10px 30px rgba(15,23,42,0.16); border-radius: 12px;',
        formatter(params) {
          if (!params?.length) {
            return ''
          }

          const unitMap = { '电流(A)': ' A', '电压(V)': ' V', '温度(℃)': ' ℃' }
          const lines = [`<div style="margin-bottom:6px;font-weight:600;">${params[0].axisValue}</div>`]
          params.forEach((item) => {
            const val = Number.isFinite(item.data) ? Number(item.data).toFixed(2) : '--'
            const unit = unitMap[item.seriesName] ?? ''
            lines.push(
              `<div style="display:flex;align-items:center;gap:6px;min-width:160px;justify-content:space-between;">
                <span>${item.marker}${item.seriesName}</span>
                <strong>${val}${unit}</strong>
              </div>`,
            )
          })
          return lines.join('')
        },
      },
      legend: {
        bottom: 0,
        itemWidth: 18,
        itemHeight: 10,
        textStyle: {
          color: '#475569',
        },
        data: ['电流(A)', '电压(V)', '温度(℃)'],
      },
      grid: {
        top: 48,
        left: 24,
        right: 60,
        bottom: 56,
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: chartData.value.map((item) => item.time),
        axisLabel: {
          color: '#64748b',
          rotate: 35,
        },
        axisLine: {
          lineStyle: {
            color: '#94a3b8',
          },
        },
      },
      yAxis: [
        {
          type: 'value',
          name: '温度 (℃)',
          position: 'left',
          nameTextStyle: { color: '#64748b', fontSize: 11 },
          axisLabel: { color: '#64748b', formatter: '{value} ℃' },
          splitLine: {
            lineStyle: { type: 'dashed', color: 'rgba(148, 163, 184, 0.45)' },
          },
        },
        {
          type: 'value',
          name: '电流 / 电压',
          position: 'right',
          nameTextStyle: { color: '#64748b', fontSize: 11 },
          axisLabel: { color: '#64748b' },
          splitLine: { show: false },
        },
      ],
      series: [
        {
          name: '电流(A)',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 7,
          yAxisIndex: 1,
          data: getSeriesData('current'),
        },
        {
          name: '电压(V)',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 7,
          yAxisIndex: 1,
          data: getSeriesData('voltage'),
        },
        {
          name: '温度(℃)',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 7,
          yAxisIndex: 0,
          data: getSeriesData('actual_temperature'),
        },
      ],
      graphic: hasData
        ? []
        : [
            {
              type: 'text',
              left: 'center',
              top: 'middle',
              style: {
                text: '暂无足够数据生成曲线',
                fill: '#64748b',
                fontSize: 14,
              },
            },
          ],
    },
    true,
  )
}

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

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

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

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

<template>
  <div class="curve-box">
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-label">总条数</div>
        <div class="stat-value">{{ props.totalCount ?? stats.count }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">最高温度</div>
        <div class="stat-value">{{ formatValue(stats.max) }} °C</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">最低温度</div>
        <div class="stat-value">{{ formatValue(stats.min) }} °C</div>
      </div>
    </div>

    <div ref="chartRef" class="echarts-box" />
  </div>
</template>

<style lang="scss" scoped>
.curve-box {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.stat-card {
  padding: 14px 16px;
  border-radius: 14px;
  background: #f3f6fb;
}

.stat-label {
  font-size: 13px;
  color: #64748b;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 18px;
  font-weight: 700;
  color: #0f172a;
}

.echarts-box {
  flex: 1;
  min-height: 360px;
  border-radius: 14px;
  border: 1px solid rgba(15, 23, 42, 0.1);
  background: linear-gradient(180deg, #ffffff, #f8fafc);
}
</style>
