<!--
 * 动态增加图节点
  -->
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import * as echarts from 'echarts';
type EChartsOption = echarts.EChartsOption;
type ECharts = echarts.ECharts;

interface StateType {
  data: NonNullable<echarts.GraphSeriesOption['data']>;
  edges: NonNullable<echarts.GraphSeriesOption['edges']>;
  timer: null | NodeJS.Timeout;
}

defineExpose({
  reset,
});

const chartGraphDynamicRef = ref<any>(null);
const state = reactive<StateType>({
  data: [],
  edges: [],
  timer: null,
});
onMounted(() => {
  getChart();
});

var graphDynamicChart: ECharts;
function getChart() {
  if (graphDynamicChart != null && graphDynamicChart != undefined) {
    graphDynamicChart.dispose();
  }
  graphDynamicChart = echarts.init(chartGraphDynamicRef.value);
  let option: EChartsOption;

  state.data = [
    {
      fixed: true,
      x: graphDynamicChart.getWidth() / 2,
      y: graphDynamicChart.getHeight() / 2,
      symbolSize: 18,
      id: '0',
      name: '原点',
      itemStyle: {
        color: '#FEB139',
      },
    },
  ];
  state.edges = [];

  option = {
    series: [
      {
        type: 'graph',
        roam: true,
        layout: 'force',
        animation: false,
        data: state.data,
        force: {
          // initLayout: 'circular'
          // gravity: 0
          repulsion: 100,
          edgeLength: 5,
        },
        edges: state.edges,
      },
    ],
  };

  run();
  option && graphDynamicChart.setOption(option);
}

function run() {
  if (state.timer) {
    clearTimer();
  }
  state.timer = setInterval(function () {
    state.data.push({
      id: state.data.length + '',
      itemStyle: {
        color: '#8bc24c',
      },
    });
    let source = Math.round((state.data.length - 1) * Math.random());
    let target = Math.round((state.data.length - 1) * Math.random());

    // 把不相同的两点连接起来
    if (source !== target) {
      state.edges.push({
        source: source,
        target: target,
      });
    }
    graphDynamicChart.setOption({
      series: [
        {
          data: state.data,
          edges: state.edges,
        },
      ],
    });
  }, 1000);
}

function clearTimer() {
  clearInterval(Number(state.timer));
}

function reset() {
  getChart();
}
</script>
<template>
  <div class="fit" ref="chartGraphDynamicRef"></div>
</template>

<style lang="scss" scoped></style>
