<!--
 * @Author: chris
 * @Date: 2025-08-18 09:36:11
 * @LastEditors: chris
 * @LastEditTime: 2025-08-21 11:10:48
-->
<script setup>
import { BarChart } from 'echarts/charts';
// 引入标题，提示框，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components';
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
    default: () => ({
      xAxisData: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      seriesData: [120, 200, 150, 80, 70, 110, 130]
    })
  }
});

const { proxy } = getCurrentInstance()
const barChartRef = ref(null)
let barChart = null

registerComponents()

onMounted(() => {
  initBarChart()
})

onUnmounted(() => {
  if (barChart) {
    barChart.dispose();
    barChart = null;
  }
});

watch(() => props.chartData, (newData) => {
  if (barChart) {
    barChart.setOption(createOption(newData));
  }
}, { deep: true });

function initBarChart() {
  if (barChartRef.value) {
    barChart = proxy.$echarts.init(barChartRef.value);
    barChart.setOption(createOption(props.chartData));
  }
}

function createOption (data) {
  const option = {
    tooltip: {
      show: true
    },
    xAxis: {
      type: 'category',
      data: data.xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: data.seriesData,
        type: 'bar',
      }
    ]
  };
  return option;
}

function registerComponents() {
  // 注册必须的组件
  proxy.$echarts.use([TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, BarChart, LabelLayout, UniversalTransition, CanvasRenderer]);
}

function calcBoxSize () {}
</script>

<template>
  <div class="statistics-chart">
    <div class="bar-chart" ref="barChartRef"></div>
  </div>
</template>

<style lang="scss" scoped>
.statistics-chart, .bar-chart {
  @apply h-100% w-100%;
}
</style>