<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import * as echarts from 'echarts';

const chartRef = ref(null);
let chart = null;

const setOption = (option) => {
  if (!chart) return;
  chart.setOption(option);
};

const init = () => {
  if (!chartRef.value) return;

  const { width, height } = chartRef.value.getBoundingClientRect();
  if (width === 0 || height === 0) return;

  if (!chart) {
    chart = echarts.init(chartRef.value, null, { renderer: 'canvas' });
  }

  if (optionCache.value) {
    chart.setOption(optionCache.value, true);
  }
};

const optionCache = ref(null);

const setData = (opt) => {
  optionCache.value = opt;
  init();
};

onMounted(() => {
  nextTick(() => {
    init();
  });

  // 监听大小变化
  const ro = new ResizeObserver(() => {
    if (chart) chart.resize();
  });
  ro.observe(chartRef.value);
});

onBeforeUnmount(() => {
  if (chart) chart.dispose();
});

defineExpose({
  setData
});
</script>

<style>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
