<template>
  <div ref="chart" class="chart" :style="{ width: width + 'px', height: height + 'px' }"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'Graph',
  props: {
    // 图表宽度
    width: {
      type: Number,
      default: 500
    },
    // 图表高度
    height: {
      type: Number,
      default: 200
    },
    // 关系图数据
    graphData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chartInstance: null
    }
  },
  watch: {
    graphData: {
      handler(newVal) {
        if (this.chartInstance) {
          this.setOptions()
        }
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
  },
  methods: {
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chart)
      this.setOptions()
    },
    setOptions() {
      const options = {
        title: {},
        tooltip: {},
        legend: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            type: 'graph',
            layout: 'force',
            // 设置节点符号为矩形
            // symbol: 'rect',
            // symbolSize: (value) => {
            //   if (!value || !value.name) {
            //     return [80, 30] // 返回默认大小
            //   }
            //   // 根据节点名称长度或其他属性来确定大小
            //   const textSize = value.name.length * 10 // 假设每增加一个字符宽度增加10px
            //   return [textSize, 30]
            // },
            symbolSize: 50,
            roam: true,
            draggable: true,
            label: {
              show: true
            },
            edgeSymbol: ['circle', 'arrow'],
            edgeSymbolSize: [4, 10],
            edgeLabel: {
              show: true,
              formatter: '{c}',
              position: 'middle',
              textStyle: {
                fontSize: 14,
                color: '#333'
              }
            },
            // edgeLabel: {
            //   fontSize: 20
            // },
            data: this.graphData.data,
            links: this.graphData.links,
            categories: this.graphData.categories,
            force: {
              repulsion: 1500
            }
          }
        ]
      }
      this.chartInstance.setOption(options)
    }
  }
}
</script>

<style lang="scss" scoped>
.chart {
  background-color: aliceblue;
  border-radius: 10px;
}
</style>
