<template>
  <div ref="chartRef" class="h-full w-full" />
</template>
<script setup>
import echarts from "@/plugins/echarts";
import { ref, defineExpose, onMounted } from "vue";
import { onUnmounted } from "vue";
console.log(echarts);
let chart = undefined;
let resizeObserve = null;
const isEmpty = ref(false);
const chartRef = ref();
const isInit = ref(false);
const tasks = ref([]);

const init = () => {
  const el = chartRef.value;
  if (!el) return;
  chart = echarts.init(chartRef.value);
  isInit.value = true;
  if (tasks.value.length) {
    tasks.value.forEach(task => {
      chart[task.task] && chart[task.task](task.params);
    });
  }
};
const clear = () => {

  if (!isInit.value) {
    tasks.value.push({
      task: "clear"
    });
    init();
  } else {
    chart?.clear();
  }
};
const setOption = opt => {
  console.log("setOption");
  if (!isInit.value) {
    tasks.value.push({
      task: "setOption",
      params: opt
    });
    init();
  } else {
    clear();
    chart?.setOption(opt);
  }
};
defineExpose({
  chart,
  clear,
  setOption
});
onMounted(() => {
  init();

  resizeObserve && resizeObserve.disconnect();
  resizeObserve = new ResizeObserver(entries => {
    chart?.resize();
  });
  resizeObserve.observe(chartRef.value);
});
onUnmounted(() => {
  chart.dispose();
  resizeObserve && resizeObserve.disconnect();
});
</script>
<style lang=""></style>
