<template>
  <div ref="chartRef" style="height: 216px"></div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
  import * as echarts from 'echarts';
  import { HandleTaskByMonthList } from '@/api/emergency-overview';

  const props = defineProps<{
    data: HandleTaskByMonthList[];
  }>();

  const chartRef = ref<HTMLDivElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  // 生成12个月的X轴标签
  const xAxisData = [
    '1\n月',
    '2\n月',
    '3\n月',
    '4\n月',
    '5\n月',
    '6\n月',
    '7\n月',
    '8\n月',
    '9\n月',
    '10\n月',
    '11\n月',
    '12\n月',
  ];

  // 将传入的数据映射为长度为12的数组，缺失的月份补0
  const formatData = (rawData: HandleTaskByMonthList[]): number[] => {
    const map = new Map<number, number>();
    if (!rawData || rawData.length === 0) {
      return Array(12).fill(0);
    }
    rawData.forEach((item) => {
      const month = item.month;
      if (month >= 1 && month <= 12) {
        map.set(month, item.count);
      }
    });
    // 生成12个月的数据，不存在的设为0
    return Array.from({ length: 12 }, (_, i) => map.get(i + 1) || 0);
  };

  // 初始化图表
  const initChart = () => {
    if (!chartRef.value) return;

    // 销毁旧实例
    if (chartInstance) {
      chartInstance.dispose();
    }

    chartInstance = echarts.init(chartRef.value);

    const seriesData = formatData(props.data);

    const option: echarts.EChartsOption = {
      grid: {
        top: 20,
        bottom: 40,
        left: 45,
        right: 30,
      },
      tooltip: {
        trigger: 'axis',
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '事件数',
          type: 'line',
          showSymbol: false,
          data: seriesData,
        },
      ],
    };

    chartInstance.setOption(option);
    window.addEventListener('resize', resizeChart);
  };

  // 调整图表大小
  const resizeChart = () => {
    chartInstance?.resize();
  };

  watch(
    () => props.data,
    () => {
      initChart();
    },
    { deep: true },
  );

  onMounted(() => {
    initChart();
  });

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