<script setup lang="ts">
/**
 * @Name: column-chart.vue
 * @Description:
 * @Author: Cheney
 */

import { PropType, ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  rowData: {
    type: Array as PropType<{ [key: string]: number }[]>,
    required: true,
  },
});

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

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  // 清理 ResizeObserver
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
  if (chart) {
    chart.dispose()
    chart = null
  }
})

watch(
    () => props.rowData,
    () => {
      updateChart();
    },
    { immediate: true, deep: true }
);

function updateChart() {
  if (!chart || !props.rowData || props.rowData.length === 0) return;

  const data = props.rowData[0];
  const dates = Object.keys(data);
  const values = Object.values(data);

  const option: echarts.EChartsOption = {
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45,
        interval: 0,
      },
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: values,
        type: 'line',
      },
    ],
    tooltip: {
      trigger: 'axis',
    },
  };
  chart.setOption(option);
}

function initChart() {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value);
    updateChart();

    // 创建 ResizeObserver
    resizeObserver = new ResizeObserver(() => {
      chart?.resize()
    })

    // 观察 chartRef 元素
    resizeObserver.observe(chartRef.value)
  }
}
</script>

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

<style scoped></style>
