<template>
  <div ref="chartRef" class="line-box"></div>
</template>
<script lang="ts" setup>
  import * as echarts from 'echarts';
  import { ref, nextTick, unref, onMounted, markRaw, watch } from 'vue';
  const chartRef = ref<HTMLDivElement>();
  const props = withDefaults(
    defineProps<{
      echarts: any;
    }>(),
    {
      echarts: null,
    },
  );
  const myEcharts = ref<any>();
  onMounted(async () => {
    await nextTick();
    myEcharts.value = markRaw(echarts.init(unref(chartRef) as HTMLDivElement));
    initChart();
    setTimeout(() => {
      resizeChart();
    }, 1);
  });
  watch(
    () => props.echarts,
    (val) => {
      val && initChart();
    },
    {
      deep: true,
    },
  );
  /**
   * 初始化echart
   * @param clearCaching 是否清除缓存
   */
  const initChart = (clearCaching = false) => {
    if (myEcharts.value) myEcharts.value.setOption(props.echarts, clearCaching);
  };

  /**
   * 重置echart
   */
  const resizeChart = () => {
    if (props.echarts) {
      if (myEcharts.value) myEcharts.value.resize();
    }
  };
</script>
<style lang="less" scoped>
  .line-box {
    height: 100%;
    width: 100%;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
    position: relative;
  }
</style>
