<template>
  <el-card class="box-card">
    <el-empty v-if="noData" description="暂无数据"></el-empty>
    <div id="realtimeContainer"></div>
  </el-card>
</template>

<script setup>
import { computed, defineExpose, defineProps, onMounted, ref, watchEffect } from 'vue';
import { useStore } from 'vuex';
import { generateChartOption, generateDefaultYAxis, generateYAxis } from 'utils/statistical';
import * as echarts from 'echarts/core';
import { DataZoomComponent, GridComponent, LegendComponent, ToolboxComponent, TooltipComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

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

const store = useStore();
const props = defineProps({ searchHeight: Number });
const realtimeData = computed(() => store.state.statistics.realtimeData);
const isMounted = ref(false);
const noData = ref(true);
let myChart = null;

// 设置图表
onMounted(() => {
  isMounted.value = true;
});

watchEffect(() => {
  if (!realtimeData.value) return;
  const { data } = realtimeData.value;
  if (!data || !data.length || !isMounted.value) return;
  initChart(data);
});

// 初始化chart
function initChart(data) {
  const chartDom = document.getElementById('realtimeContainer');
  const canvasHeight = document.documentElement.clientHeight - props.searchHeight - 150;
  chartDom.style.height = `${canvasHeight}px`;
  myChart && myChart.dispose();
  myChart = echarts.init(chartDom);
  render(data, generateDefaultYAxis());

  myChart.on('legendselectchanged', event => {
    render(data, generateYAxis(event.selected));
  });
}

function render(data, yAxis) {
  // myChart && myChart.clear();
  if (!data || !data.length) {
    noData.value = true;
    return;
  }
  noData.value = false;

  if (!myChart) {
    initChart();
  }
  const option = generateChartOption(data, yAxis);
  option && myChart.setOption(option);
}

defineExpose({ render });
</script>
