<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import useCharts from "@/hooks/useEcharts";
import { todayTrafficCount } from "@/api/modules/index";
import type { EChartsOption } from "echarts";

// 图表 DOM ref 和 ECharts 实例
const chartRef = ref<HTMLElement | null>(null);
let chart: ReturnType<typeof useCharts> | null = null;

// 车流数据
const trafficData = reactive({
  total: 0,
  car: { value: 0, percentage: 0, name: "小型车" },
  truck: { value: 0, percentage: 0, name: "货车" },
  bus: { value: 0, percentage: 0, name: "客车" },
});

// 图表初始配置
const chartOptions: EChartsOption = {
  tooltip: { trigger: "item", formatter: "{b}: {c} ({d}%)" },
  legend: { show: false },
  series: [
    {
      name: "车流量分布",
      type: "pie",
      radius: ["65%", "80%"],
      center: ["50%", "50%"],
      data: [], // 初始化为空，稍后更新
    },
  ],
};

// 初始化图表 + 获取数据
onMounted(async () => {
  if (chartRef.value) {
    chart = useCharts(chartRef.value);
    chart.setOption(chartOptions); // 初始化
  }
  await loadTrafficData();
});

// 获取接口数据并更新图表
async function loadTrafficData() {
  try {
    const res = await todayTrafficCount(); // 假设返回 car、truck、bus 数值
    trafficData.total = res.total;
    trafficData.car.value = res.car;
    trafficData.truck.value = res.truck;
    trafficData.bus.value = res.bus;

    const newChartData = [
      { value: res.car, name: "小型车" },
      { value: res.truck, name: "货车" },
      { value: res.bus, name: "客车" },
    ];

    if (chart) {
      chart.setOption({
        series: [
          {
            data: newChartData,
          },
        ],
      });
    }
  } catch (error) {
    console.error("获取车流量数据失败:", error);
  }
}
</script>

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