<script setup lang="ts">
import { ECharts, EChartsOption, init } from 'echarts';
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';

const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  option: {
    type: Object,
    default: () => ({})
  }
});

const myChartsRef = ref();
let myChart;
let timer;

// 初始化echarts
const initChart = () => {
  if (myChart !== undefined) {
    myChart.dispose();
  }
  myChart = init(myChartsRef.value);
  // 拿到option配置项，渲染echarts
  myChart?.setOption(props.option, true);
  resizeChart()
};
// 重新渲染echarts
const resizeChart = () => {
  timer = setTimeout(() => {
    if (myChart) {
      myChart.resize();
    }
  }, 500);
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart);
  clearTimeout(timer);
  timer = null;
});

watch(() => props.option, () => {
  initChart();
}, {
  deep: true
}
);
</script>

<template>
  <div ref="myChartsRef" :style="{ height: height, width: width }" :option="option"></div>
</template>
