<template>
  <div class="box">
    <div class="item-title">{{ props.title }}</div>
    <div ref="chartRef" class="item"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as echarts from 'echarts';
  import { ref, nextTick, unref, onMounted, markRaw, watch } from 'vue';
  import { EChartsOption } from 'echarts';
  import { DesktopComponent } from '/@/enums/desktop';
  const chartRef = ref<HTMLDivElement>();
  const props = withDefaults(
    defineProps<{
      type: DesktopComponent;
      w: number;
      h: number;
      title: string;
      echarts: null | EChartsOption;
    }>(),
    {
      type: DesktopComponent.DEFAULT,
      w: 0,
      h: 0,
      title: '',
      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,
    },
  );
  watch(
    () => props.w,
    (val) => {
      val && resizeChart();
    },
    {
      deep: true,
    },
  );
  watch(
    () => props.h,
    (val) => {
      val && resizeChart();
    },
    {
      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>
  .box {
    width: 100%;
    height: 100%;
    padding-top: 40px;

    .item-title {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 40px;
      line-height: 40px;
      color: #262626;
      font-size: 14px;
      padding-left: 16px;
    }

    .item-title::after {
      content: '';
      display: block;
      position: absolute;
      height: 1px;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: #f0f0f0;
    }

    .item {
      height: 100%;
      width: 100%;
      -webkit-tap-highlight-color: transparent;
      user-select: none;
      position: relative;
    }
  }
</style>
