<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';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { cloneDeep } from 'lodash-es';
  const { t } = useI18n();
  const chartRef = ref<HTMLDivElement>();
  const props = withDefaults(
    defineProps<{
      echarts: any;
      config: any;
      refreshkey: any;
    }>(),
    {
      echarts: null,
      config: null,
    },
  );
  const myEcharts = ref<any>();
  onMounted(async () => {
    await nextTick();
    myEcharts.value = markRaw(echarts.init(unref(chartRef) as HTMLDivElement));
    initChart(true);
    setTimeout(() => {
      resizeChart();
    }, 1);
  });
  watch(
    () => [props.echarts, props.refreshkey],
    () => {
      myEcharts.value = markRaw(echarts.init(unref(chartRef) as HTMLDivElement));
      initChart(true);
    },
    {
      deep: true,
    },
  );
  watch(
    () => [props.config.width, props.config.height],
    () => {
      setTimeout(() => {
        resizeChart();
      }, 1);
    },
    {
      deep: true,
    },
  );
  /**
   * 初始化echart
   * @param clearCaching 是否清除缓存
   */
  const initChart = (clearCaching = false) => {
    let echartsConfig = cloneDeep(props.echarts);
    if (echartsConfig && echartsConfig.series && echartsConfig.series.length > 0) {
      let gradualStartColor = props.config.line.gradualStartColor;
      let gradualEndColor = props.config.line.gradualEndColor;
      echartsConfig.series.forEach((element, index) => {
        if (element.gradualStartColor) {
          gradualStartColor = element.gradualStartColor;
          gradualEndColor = element.gradualEndColor;
        }
        if (gradualStartColor && gradualEndColor) {
          element.color = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: gradualStartColor,
            },
            {
              offset: 1,
              color: gradualEndColor,
            },
          ]);
        } else {
          element.color = props.echarts.color[index];
        }
      });
    }
    myEcharts.value.showLoading({
      text: t('加载中'),
      color: '#5e95ff',
      textColor: 'rgba(255, 255, 255, 0.6)',
      maskColor: 'rgba(255, 255, 255, 0.2)',
      zlevel: 0,
    });
    setTimeout(() => {
      myEcharts.value.hideLoading();
      if (myEcharts.value) myEcharts.value.setOption(echartsConfig, clearCaching);
    }, 100);
  };

  /**
   * 重置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;
    background: none !important;
  }
</style>
