<template>
  <div class="metric-chart-wrap">
    <div ref="chartHost" class="metric-comparison-chart"></div>
    <el-empty v-if="!series.length" description="选择测试记录后查看指标对比" :image-size="70" />
  </div>
</template>

<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import * as echarts from "echarts";
import type { JsonMap } from "../../types/model-management";

const props = defineProps<{ series: Array<{ name: string; metrics: JsonMap }> }>();
const chartHost = ref<HTMLElement>();
let chart: echarts.ECharts | undefined;
let resizeObserver: ResizeObserver | undefined;

function render() {
  if (!chartHost.value || !props.series.length) {
    chart?.clear();
    return;
  }
  if (!chart) chart = echarts.init(chartHost.value);
  const metricKeys = [...new Set(props.series.flatMap((item) => Object.keys(item.metrics).filter((key) =>
    typeof item.metrics[key] === "number" && !["sample_count", "result_count"].includes(key)
  )))].slice(0, 8);
  chart.setOption({
    animationDuration: 350,
    color: ["#1f5d8f", "#16a085", "#d97706", "#b23a48", "#64748b", "#0f766e"],
    tooltip: { trigger: "axis" },
    legend: { top: 4, right: 8, textStyle: { color: "#475569", fontSize: 11 } },
    grid: { left: 48, right: 22, top: 48, bottom: 58 },
    xAxis: { type: "category", data: metricKeys, axisLabel: { rotate: 22, color: "#64748b", fontSize: 10 } },
    yAxis: { type: "value", axisLabel: { color: "#64748b" }, splitLine: { lineStyle: { color: "#e5edf5" } } },
    series: props.series.map((item) => ({
      name: item.name,
      type: "bar",
      barMaxWidth: 28,
      data: metricKeys.map((key) => Number(item.metrics[key] || 0))
    }))
  });
}

watch(() => props.series, () => nextTick(render), { deep: true });
onMounted(() => {
  render();
  if (chartHost.value) {
    resizeObserver = new ResizeObserver(() => chart?.resize());
    resizeObserver.observe(chartHost.value);
  }
});
onBeforeUnmount(() => { resizeObserver?.disconnect(); chart?.dispose(); });
</script>
