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

<script setup>
import * as echarts from 'echarts';
import { queryGlobalCfg } from '@/api/configure/configuration/globalCfg.js';

const props = defineProps({
  defaultOption: Object
});

const { defaultOption } = toRefs(props);


const chart = ref(null);
const option = ref(null);
const resizeTime = ref(true);
const chartRef = ref();

onMounted(async () => {
  if (defaultOption.value) {
    setData(defaultOption.value);
  }
  nextTick(() => {
    const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        resize();
      }
    });
    resizeObserver.observe(chartRef.value);
  });
  window.addEventListener('resize', resize);
});

const setData = (e) => {
  option.value = e;
  initChart(e);
};
const initChart = (option) => {
  if (!chart.value) {
    chart.value = echarts.init(chartRef.value, 'macarons');
  }
  chart.value.setOption(option, true);
};
const resize = () => {
  if (resizeTime.value) {
    resizeTime.value = false;
    if (option.value && chartRef.value) {
      chartRef.value.resize();
    }
    setTimeout(() => {
      resizeTime.value = true;
    }, 16);
  }
};
onBeforeUnmount(() => {
  if (!chart.value) {
    return;
  }
  chart.value.dispose();
  chart.value = null;
  window.removeEventListener('resize', resize);
});
defineExpose({
  setData
});
</script>
