<!-- 积分消耗图表，负责展示账户时间范围内的积分变化。 -->
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import { GridComponent, TooltipComponent } from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([LineChart, GridComponent, TooltipComponent, CanvasRenderer]);
const props = defineProps<{ labels: string[]; values: number[] }>();
const element = ref<HTMLDivElement>();
let chart: echarts.ECharts | undefined, observer: ResizeObserver | undefined;

/** 从全局设计令牌读取 ECharts Canvas 可使用的实际颜色值。 */
function themeColor(name: string) {
  return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}

/** 根据当前消费数据渲染积分变化图表。 */
function render() {
  const labelInterval = props.labels.length > 12 ? Math.ceil(props.labels.length / 6) - 1 : 0;
  chart?.setOption({
    color: [themeColor("--web-chart-primary")],
    tooltip: {
      trigger: "axis",
      backgroundColor: themeColor("--web-chart-tooltip-bg"),
      borderColor: themeColor("--web-chart-tooltip-line"),
      textStyle: { color: themeColor("--web-chart-tooltip-text") },
    },
    grid: { left: 42, right: 18, top: 36, bottom: 28 },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: props.labels,
      axisLine: { lineStyle: { color: themeColor("--web-chart-axis-line") } },
      axisLabel: { color: themeColor("--web-chart-axis-text"), interval: labelInterval },
    },
    yAxis: {
      type: "value",
      minInterval: 1,
      name: "积分",
      nameTextStyle: { color: themeColor("--web-chart-axis-text") },
      axisLabel: { color: themeColor("--web-chart-axis-text") },
      splitLine: { lineStyle: { color: themeColor("--web-chart-split-line") } },
    },
    series: [
      { type: "line", smooth: true, symbol: "circle", symbolSize: 5, lineStyle: { width: 2 }, data: props.values },
    ],
  });
}
onMounted(() => {
  if (element.value) {
    chart = echarts.init(element.value);
    render();
    observer = new ResizeObserver(() => chart?.resize());
    observer.observe(element.value);
  }
});
watch(() => [props.labels, props.values], render, { deep: true });
onBeforeUnmount(() => {
  observer?.disconnect();
  chart?.dispose();
});
</script>
<template>
  <div
    ref="element"
    class="consumption-chart"
  />
</template>
<style scoped>
.consumption-chart {
  width: 100%;
  height: 210px;
}
</style>
