<template>
  <div ref="upfFlow" class="chart-container"></div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { listUPFData } from '@/api/perfManage/goldTarget';
import { parseSizeFromKbs } from '@/utils/parse-utils';
import * as echarts from 'echarts/core';
import {
  TooltipComponent,
  TooltipComponentOption,
  GridComponent,
  GridComponentOption,
  LegendComponent,
  LegendComponentOption,
} from 'echarts/components';
import { LineChart, LineSeriesOption } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { markRaw } from 'vue';
import useI18n from '@/hooks/useI18n';
import { parseDateToStr } from '@/utils/date-utils';

const { t } = useI18n();

echarts.use([
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
]);

type EChartsOption = echarts.ComposeOption<
  | TooltipComponentOption
  | GridComponentOption
  | LegendComponentOption
  | LineSeriesOption
>;
/**设置定时器ID */
let timeoutDuration = 5 * 1000; // 设置5s进行刷新请求
let loadId: any = null;

// 定时制图
function resetTimeout() {
  if (loadId) {
    clearInterval(loadId);
  }
  loadId = setInterval(() => {
    initPicture();
  }, timeoutDuration);
}

/**图DOM节点实例对象 */
const upfFlow = ref<HTMLElement | undefined>(undefined);

/**图实例对象 */
const upfFlowChart = ref<any>(null);

function fnDesign(container: HTMLElement | undefined, option: EChartsOption) {
  if (!container) {
    return;
  }
  if (!upfFlowChart.value) {
    upfFlowChart.value = markRaw(echarts.init(container, 'light'));
  }

  option && upfFlowChart.value.setOption(option);
  window.onresize = function () {
    // echarts 窗口缩放自适应 随着div--echarts-records的大小来适应
    upfFlowChart.value.resize();
  };
}

//渲染速率图
function initPicture() {
  if (loadId) {
    clearInterval(loadId);
  }
  let queryArr: any = [];
  const initTime: Date = new Date();
  const startTime: Date = new Date(initTime);
  startTime.setHours(0, 0, 0, 0); // 设置为今天的0点
  const endTime: Date = new Date(initTime);
  endTime.setHours(23, 59, 59, 59); // 设置为今天的12点
  queryArr = [parseDateToStr(startTime), parseDateToStr(endTime)];

  listUPFData(queryArr).then(res => {
    resetTimeout();

    let timeArr: any = [];
    let upValue: any = [];
    let downValue: any = [];

    res.upData.map((item: any) => {
      timeArr.push(item.timestamp);
      upValue.push(parseSizeFromKbs(item.value, item.granularity)[0]);
    });
    res.downData.map((item: any) => {
      downValue.push(parseSizeFromKbs(item.value, item.granularity)[0]);
    });

    var charts = {
      unit: '(Mbps)',
      names: [
        t('views.dashboard.overview.upfFlow.up'),
        t('views.dashboard.overview.upfFlow.down'),
      ],

      lineX: timeArr,
      value: [upValue, downValue],
    };

    var color = ['rgba(7,217,162', 'rgba(92, 123, 217'];
    var lineY: any = [];

    for (var i = 0; i < charts.names.length; i++) {
      var x = i;
      if (x > color.length - 1) {
        x = color.length - 1;
      }
      var data = {
        name: charts.names[i],
        type: 'line',
        color: color[x] + ')',
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: color[x] + ', .5)',
            },
            {
              offset: 1,
              color: color[x] + ', 0.5)',
            },
          ]),
          shadowColor: 'rgba(0, 0, 0, 0.1)',
          shadowBlur: 10,
        },
        symbol: 'circle',
        symbolSize: 5,
        formatter: '{b}',
        data: charts.value[i],
      };
      lineY.push(data);
    }

    const optionData: EChartsOption = {
      tooltip: {
        show: true, //是否显示提示框组件
        trigger: 'axis',
        //formatter:'{a0}:{c0}<br>{a1}:{c1}'
        formatter: function (param: any) {
          var tip = '';
          if (param !== null && param.length > 0) {
            tip += param[0].name + '<br />';
            for (var i = 0; i < param.length; i++) {
              tip +=
                param[i].marker +
                param[i].seriesName +
                ': ' +
                param[i].value +
                '<br />';
            }
          }
          return tip;
        },
      },
      legend: {
        data: charts.names,
        textStyle: {
          fontSize: 12,
          color: 'rgb(0,253,255,0.6)',
        },
        left: 'center',
      }, // 设置图例居中

      grid: {
        top: '14%',
        left: '4%',
        right: '4%',
        bottom: '12%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: charts.lineX,
        axisLabel: {
          formatter: function (params: any) {
            return params.split(' ')[1];
          },
          fontSize: 14,
        },
        axisLine: {
          lineStyle: {
            color: 'rgb(0,253,255,0.6)',
          },
        },
      },
      yAxis: [
        {
          name: charts.unit,
          type: 'value',
          //  splitNumber: 4,
          min: 0,
          //max: 300,
          axisLabel: {
            formatter: '{value}',
          },
          splitLine: {
            lineStyle: {
              color: 'rgb(23,255,243,0.3)',
            },
          },
          axisLine: {
            lineStyle: {
              color: 'rgb(0,253,255,0.6)',
            },
          },
        },
      ],
      series: lineY,
    };
    fnDesign(upfFlow.value, optionData);
  });
}

onMounted(() => {
  initPicture();
  resetTimeout();
});

/**组件实例被卸载之后调用 */
onUnmounted(() => {
  if (loadId) {
    clearInterval(loadId);
  }
});
</script>

<style lang="less" scoped>
.chart-container {
  /* 设置图表容器大小和位置 */
  width: 100%;
  height: 100%;
}
</style>
