<template>
  <div ref="chartRef" style="width: 100%; height: 400px"></div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, defineProps, onUnmounted } from 'vue';
  import * as echarts from 'echarts';
  import type { EChartsOption } from 'echarts';
  import { useDisasterControlHook } from '@/views/disaster/disaster-control/src/hook';

  const { getSafetyLevel, getSafetyLevelDict } = useDisasterControlHook();

  // 定义 props 接收父组件传来的数据
  interface DataItem {
    count: number;
    safetyLevel: string;
  }

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

  // 图表容器的引用
  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  // 颜色配置（可根据视觉设计调整）
  const colorPalette = ['#5ab1ef', '#67e0e3', '#ffd53e', '#f0853a', '#c0343d'];

  // 处理数据并生成图表
  const renderChart = () => {
    if (!chartRef.value) return;

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

    // 初始化 ECharts 实例
    chartInstance = echarts.init(chartRef.value);

    // 转换数据为 ECharts 所需格式
    const seriesData = props.data.map((item) => ({
      value: item.count,
      name: getSafetyLevel(item.safetyLevel) || item.safetyLevel,
    }));

    // 配置项
    const option: EChartsOption = {
      title: {
        text: '影响安全评估分布',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      legend: {
        bottom: 0,
        left: 'center',
        data: seriesData.map((item) => item.name),
      },
      series: [
        {
          name: '安全等级分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: true,
            formatter: '{b}: {c} ({d}%)',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
            },
          },
          data: seriesData,
        },
      ],
      color: colorPalette,
    };

    // 应用配置
    chartInstance.setOption(option);

    // 初始渲染后立即 resize 一次，确保尺寸正确
    chartInstance.resize();
  };

  // 处理窗口尺寸变化
  const handleResize = () => {
    if (chartInstance) {
      chartInstance.resize({
        animation: {
          duration: 100,
        },
      });
    }
  };

  // 组件挂载后初始化图表
  onMounted(async () => {
    await getSafetyLevelDict();
    renderChart();
    window.addEventListener('resize', handleResize);
  });

  // 监听数据变化，重新渲染图表
  watch(
    () => props.data,
    () => {
      renderChart();
    },
    { deep: true },
  );

  // 组件卸载前清理
  onUnmounted(() => {
    // 移除 resize 监听
    window.removeEventListener('resize', handleResize);
    // 销毁图表实例
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
  });
</script>

<style scoped lang="scss"></style>
