<template>
  <div>
    <TopTitle title="应急管理" />
    <div class="counts">
      <div class="count-item top-item">
        <div class="count-value emergency-plan-count">{{ emergencyPlanCount }}</div>
        <div class="count-label">应急预案数</div>
      </div>
      <div class="count-item top-item">
        <div class="count-value emergency-exercise-count">{{ emergencyExerciseCount }}</div>
        <div class="count-label">本年应急演练数</div>
      </div>
      <div class="count-item bottom-item">
        <div class="count-value emergency-supplies-count">{{ emergencySuppliesCount }}</div>
        <div class="count-label">应急物资总数</div>
      </div>
      <div class="count-item bottom-item">
        <div class="count-value validity-period-ratio">{{ validityPeriodRatio }}</div>
        <div class="count-label">有效期内物资比例</div>
      </div>
      <div class="divider-horizontal"></div>
      <div class="divider-vertical"></div>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted, ref, watch } from 'vue';
  import TopTitle from './TopTitle.vue';
  import {
    getOverviewEmergencyPlan,
    getCompletedEmergencyDrillCountThisYear,
    getEmergencyManageInfo,
  } from '@/api/emergency-overview';
  import echarts from '@/utils/lib/echarts';
  import type { EChartsOption } from 'echarts';

  const emergencyPlanCount = ref<number>(0); // 生效应急预案数量
  const emergencyExerciseCount = ref<number>(0); // 本自然年已完成应急演练数量
  const emergencySuppliesCount = ref<number>(0); // 应急物资总数
  const validityPeriodRatio = ref<string>(''); // 有效期内物资比例
  const variousTypeSuppliesRatio = ref<{ suppliesTypeName: string; typeRatio: string }[]>([]); // 各类型物资占比

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

  // 颜色配置，可以根据需要自定义
  const colorPalette = ['#117af1', '#ff9237', '#ff6257', '#17cba5', '#5ab1ef', '#67e0e3', '#ffd53e', '#f0853a'];

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

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

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

    // 转换数据格式
    const chartData = variousTypeSuppliesRatio.value.map((item, index) => ({
      value: parseFloat(item.typeRatio) || 0,
      name: item.suppliesTypeName,
      itemStyle: {
        color: colorPalette[index % colorPalette.length],
      },
    }));

    // 动态生成 rich 样式，为每个数据项的 ratio 设置对应的颜色
    const richStyles: Record<string, any> = {
      name: {
        fontSize: 12,
        color: '#999',
        width: 90,
        align: 'left',
        lineHeight: 17,
        padding: [0, 0, 0, 4],
      },
    };

    // 为每个数据项创建对应的 ratio 样式
    variousTypeSuppliesRatio.value.forEach((_item, index) => {
      const color = colorPalette[index % colorPalette.length];
      richStyles[`ratio${index}`] = {
        fontSize: 12,
        fontFamily: 'DINAlternate',
        fontWeight: 'bold',
        color: color,
        width: 35,
        align: 'right',
        lineHeight: 14,
      };
    });

    const option: EChartsOption = {
      legend: {
        orient: 'vertical',
        left: 'right',
        top: 'center',
        align: 'left',
        itemWidth: 6,
        itemHeight: 6,
        itemGap: 10,
        icon: 'circle',
        formatter: (name: string) => {
          const itemIndex = variousTypeSuppliesRatio.value.findIndex((item) => item.suppliesTypeName === name);
          if (itemIndex === -1) return name;
          const item = variousTypeSuppliesRatio.value[itemIndex];
          const nameText = item.suppliesTypeName;
          const ratioText = item.typeRatio;
          return `{name|${nameText}} {ratio${itemIndex}|${ratioText}}`;
        },
        textStyle: {
          rich: richStyles,
        },
      },
      series: [
        {
          type: 'pie',
          radius: ['60%', '90%'],
          center: ['20%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 0,
          },
          label: {
            show: false,
          },
          emphasis: {
            scale: false,
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
          data: chartData,
        },
      ],
    };

    chartInstance.setOption(option);

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
  };

  const handleResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  onMounted(async () => {
    const emergencyPlanRes = await getOverviewEmergencyPlan();
    emergencyPlanCount.value = emergencyPlanRes.planInfoList.reduce((acc, curr) => acc + curr.count, 0);
    emergencyExerciseCount.value = await getCompletedEmergencyDrillCountThisYear();
    const emergencyManageRes = await getEmergencyManageInfo();
    emergencySuppliesCount.value = emergencyManageRes.emergencySuppliesCount;
    validityPeriodRatio.value = emergencyManageRes.validityPeriodRatio;
    variousTypeSuppliesRatio.value = emergencyManageRes.variousTypeSuppliesRatio;

    // 数据加载完成后初始化图表
    initChart();
  });

  // 监听数据变化
  watch(
    () => variousTypeSuppliesRatio.value,
    () => {
      initChart();
    },
    { deep: true },
  );

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    if (chartInstance) {
      chartInstance.dispose();
    }
  });
</script>

<style scoped lang="scss">
  .counts {
    width: 314px;
    height: 131px;
    margin: 20px 8px;
    position: relative;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    gap: 0;

    .count-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;
      position: relative;
    }
    .top-item {
      justify-content: flex-start;
    }
    .bottom-item {
      justify-content: flex-end;
    }

    .count-label {
      font-weight: 400;
      font-size: 12px;
      color: #999999;
      line-height: 17px;
    }

    .count-value {
      font-family: DINAlternate;
      font-weight: bold;
      font-size: 24px;
      line-height: 28px;
    }
    .emergency-plan-count {
      color: #117af1;
    }
    .emergency-exercise-count {
      color: #ff9237;
    }
    .emergency-supplies-count {
      color: #ff6257;
    }
    .validity-period-ratio {
      color: #17cba5;
    }

    .divider-horizontal {
      position: absolute;
      left: 0;
      right: 0;
      top: 50%;
      height: 1px;
      background-color: #e8e8e8;
      transform: translateY(-50%);
      z-index: 1;
    }

    .divider-vertical {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 50%;
      width: 1px;
      background-color: #e8e8e8;
      transform: translateX(-50%);
      z-index: 1;
    }
  }

  .chart {
    height: 100px;
    margin: 34px 24px 24px 20px;
  }
</style>
