<template>
  <div style="position:relative;">
    <div :id="topoId" class="container" />
    <el-card class="legend">
      <div >
        <h2 style="margin-top:0">图例</h2>
        <!-- <div class="listwrap">
          <span class="value" style="color:#31a354">24.88%</span>
          <span class="lable">延迟占比</span>
        </div> -->
        <div class="listwrap">
          <span class="value">
            <el-progress :percentage="100" status="success" :show-text="false" />
          </span>
          <span class="lable">请求正常</span>
        </div>
        <div class="listwrap">
          <span class="value">
            <el-progress :percentage="100" status="warning" :show-text="false" />
          </span>
          <span class="lable">高延迟</span>
        </div>
        <div class="listwrap">
          <span class="value">
            <el-progress :percentage="100" status="exception" :show-text="false" />
          </span>
          <span class="lable">存在异常</span>
        </div>
      </div>
    </el-card>
    <el-dialog
      :visible.sync="networkOpen"
      :fullscreen="true"
      center
      :close-on-press-escape="false"
      :append-to-body="true"
      @before-close="beforecloseNetwork"
      @close="closeNetwork"
    >
      <div v-if="flag" id="networkContainer" style="width:100%;height:100vh" />
    </el-dialog>
  </div>
</template>

<script>
import { networkSpans } from '@/api/trace'
import screenfull from 'screenfull'
import G6 from '@antv/g6'
import insertCss from 'insert-css'

// 我们用 insert-css 演示引入自定义样式
// 推荐将样式添加到自己的样式文件中
// 若拷贝官方代码，别忘了 npm install insert-css
insertCss(`
  .g6-component-tooltip {
    background-color: rgba(0,0,0, 0.65);
    padding: 10px;
    box-shadow: rgb(174, 174, 174) 0px 0px 10px;
    width: fit-content;
    color: #fff;
    border-radius:4px;
  }
`)

const colors = {
  B: '#5B8FF9', // 蓝色
  R: '#F46649', // 红色
  Y: '#EEBC20', // 黄色
  G: '#5BD8A6', // 绿色
  DI: '#A7A7A7' // 灰色
}
//  组件props
const props = {
  config: {
    padding: [20, 50],
    defaultLevel: 3,
    defaultZoom: 0.8,
    modes: { default: ['zoom-canvas', 'drag-canvas'] }
  }
}

export default {
  props: {
    // 数据
    graphData: {
      type: Object,
      default() {
        return {}
      }
    },
    topoId: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      isFull: false,
      Visible: false,
      networkQuery: {
        span_id: '07fe3536fd3d424b',
        parent_span_id: '88a432e4c06ea0fd'
      },
      networkOpen: false,
      topoData: {},
      firstNode: {},
      lastNode: {},
      apis: require('../../../assets/apis.jpg'),
      apm: require('../../../assets/apm.jpg'),
      iconDown: require('../../../assets/icon_down.png'),
      flag: false,
      globalGraph: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (JSON.stringify(this.graphData) != '{}') {
        this.initGraph(this.graphData, this.topoId)
      }
    })
  },
  destroy() {
    if (screenfull.isEnabled) {
      screenfull.off('change', this.change)
    }
  },
  methods: {
    closeNetwork() {
      this.networkOpen = false
      this.flag = false
    },
    beforecloseNetwork() {
      this.networkOpen = false
      this.flag = false
    },
    init() {
      if (screenfull.isEnabled) {
        screenfull.on('change', this.change)		// 开启监听
      }
    },
    change() {
      this.isFull = screenfull.isFullscreen // 更新全屏状态
    },
    buildNestedTree(list) {
      const tree = [] // 存储树形结构的数组
      const lookup = {} // 用于快速查找节点的对象

      // 遍历列表，为每个节点在lookup中创建一个引用
      list.forEach((item, index) => {
        lookup[item.id] = item
      })

      // 函数用于递归构建嵌套树形结构
      function addChild(parentId) {
        const parent = lookup[parentId]
        if (parent && parent.childs && parent.childs.length > 0) {
          parent.children = parent.childs.map(childId => {
            const child = lookup[childId]
            if (child) {
              addChild(child.id) // 递归添加子节点
              return child
            }
            return null
          }).filter(Boolean) // 过滤掉空值
        } else {
          parent.children = [] // 如果没有子节点，则设置为一个空数组
        }
      }

      // 从根节点开始构建树形结构
      list.forEach(item => {
        if (item.parent_id === -1) {
          addChild(item.id)
          tree.push(item)
        }
      })

      return tree
    },
    addDataToTree(tree, newData) {
      tree.forEach((v) => {
        if (v.children != undefined && v.children.length == 0) {
          v.children.push({ ...newData })
        } else {
          this.addDataToTree(v.children, newData)
        }
      })
      return tree
    },
    clearObject() {
      // 使用 Object.keys 遍历对象的属性并逐个删除
      Object.keys(this.topoData).forEach(key => {
        this.$delete(this.topoData, key)
      })
    },
    handleData(data) {
      data.forEach((v, k) => {
        v.id = v.id.toString()
        v.type = 'flow-circle'
        v.size = [60]
        v.name = (v.flat_duration.toFixed(2)).toString() + 'ms'
        v.collapsed = false
        v.label = (v.flat_duration.toFixed(2)).toString() + 'ms'
        v.currency = 'ms'
        v.rate = ''
        v.status = 'G'
        v.variableValue = ''
        // 数形结构时打开
        // if (v.children != undefined && v.children.length > 0) {
        //     v.children = this.handleData(v.children)
        //   }
      })
      return data
    },
    initGraph(data, id) {
      const _this = this
      let graph = null
      const container = document.getElementById(id)
      const width = container.scrollWidth
      const height = container.scrollHeight || 700
      // 默认配置
      const defaultConfig = {
        width,
        height,
        modes: {
          default: ['zoom-canvas', 'drag-canvas']
          //  default: ['drag-canvas', 'zoom-canvas', 'drag-node', 'lasso-select'],
        },
        fitView: true,
        maxZoom: 2, // 默认值是10
        minZoom: 0.02, // 默认值是0.02
        animate: true,
        defaultNode: {
          type: 'flow-rect'
        },
        defaultEdge: {
          // type: 'cubic-horizontal',
          type: 'flow-cubic',
          style: {
            stroke: '#CED4D9'
          }
        },
        layout: {
          type: 'indented',
          direction: 'LR',
          dropCap: false,
          indent: 300,
          getHeight: () => {
            return 60
          }

        }
      }

      /**
       * 自定义节点
       */
      G6.registerNode(
        'flow-rect',
        {
          shapeType: 'flow-rect',
          draw(cfg, group) {
            const {
              name = '',
              // variableName,
              variableValue,
              // variableUp,
              label,
              collapsed,
              currency,
              status,
              rate
            } = cfg

            const grey = '#CED4D9'
            const rectConfig = {
              width: 202,
              height: 60,
              lineWidth: 1,
              fontSize: 12,
              fill: '#fff',
              radius: 4,
              stroke: grey,
              opacity: 1
            }

            const nodeOrigin = {
              x: -rectConfig.width / 2,
              y: -rectConfig.height / 2
            }

            const textConfig = {
              textAlign: 'left',
              textBaseline: 'bottom'
            }

            const rect = group.addShape('rect', {
              attrs: {
                x: nodeOrigin.x,
                y: nodeOrigin.y,
                ...rectConfig
              }
            })

            const rectBBox = rect.getBBox()

            // label title
            group.addShape('text', {
              attrs: {
                ...textConfig,
                x: 12 + nodeOrigin.x,
                y: 20 + nodeOrigin.y,
                text: name.length > 28 ? name.substr(0, 28) + '...' : name,
                fontSize: 12,
                opacity: 0.85,
                fill: '#000',
                cursor: 'pointer'
              },
              // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
              name: 'name-shape'
            })

            // price
            const price = group.addShape('text', {
              attrs: {
                ...textConfig,
                x: 12 + nodeOrigin.x,
                y: rectBBox.maxY - 12,
                text: label,
                fontSize: 16,
                fill: '#000',
                opacity: 0.85
              }
            })

            // label currency   换成ms
            group.addShape('text', {
              attrs: {
                ...textConfig,
                x: price.getBBox().maxX + 5,
                y: rectBBox.maxY - 12,
                text: currency,
                fontSize: 12,
                fill: '#000',
                opacity: 0.75
              }
            })

            // percentage
            const percentText = group.addShape('text', {
              attrs: {
                ...textConfig,
                x: rectBBox.maxX - 8,
                y: rectBBox.maxY - 12,
                text: `${((variableValue || 0) * 100).toFixed(2)}%`,
                fontSize: 12,
                textAlign: 'right',
                fill: colors[status]
              }
            })

            // bottom line background
            const bottomBackRect = group.addShape('rect', {
              attrs: {
                x: nodeOrigin.x,
                y: rectBBox.maxY - 4,
                width: rectConfig.width,
                height: 4,
                radius: [0, 0, rectConfig.radius, rectConfig.radius],
                fill: '#E0DFE3'
              }
            })
            // bottom percent
            const bottomRect = group.addShape('rect', {
              attrs: {
                x: nodeOrigin.x,
                y: rectBBox.maxY - 4,
                width: rate < 1 ? rate * rectBBox.width : rectBBox.width - 1,
                height: 4,
                radius: rate < 1 ? [0, 0, 0, rectConfig.radius] : [0, 0, rectConfig.radius, rectConfig.radius],
                fill: colors[status]
              }
            })

            // collapse rect
            if (cfg.children && cfg.children.length) {
              group.addShape('rect', {
                attrs: {
                  x: rectConfig.width / 2 - 8,
                  y: -8,
                  width: 16,
                  height: 16,
                  stroke: 'rgba(0, 0, 0, 0.25)',
                  cursor: 'pointer',
                  fill: '#fff'
                },
                // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                name: 'collapse-back',
                modelId: cfg.id
              })
              // collpase text
              group.addShape('text', {
                attrs: {
                  x: rectConfig.width / 2,
                  y: -1,
                  textAlign: 'center',
                  textBaseline: 'middle',
                  text: collapsed ? '+' : '-',
                  fontSize: 16,
                  cursor: 'pointer',
                  fill: 'rgba(0, 0, 0, 0.25)'
                },
                // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                name: 'collapse-text',
                modelId: cfg.id
              })
            }

            this.drawLinkPoints(cfg, group)
            return rect
          },
          update(cfg, item) {
            const { level, status, name } = cfg
            const group = item.getContainer()
            let mask = group.find(ele => ele.get('name') === 'mask-shape')
            let maskLabel = group.find(ele => ele.get('name') === 'mask-label-shape')
            if (level === 0) {
              group.get('children').forEach(child => {
                if (child.get('name')?.includes('collapse')) return
                child.hide()
              })
              if (!mask) {
                mask = group.addShape('rect', {
                  attrs: {
                    x: -101,
                    y: -30,
                    width: 202,
                    height: 60,
                    opacity: 0,
                    fill: colors[status]
                  },
                  // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                  name: 'mask-shape'
                })
                maskLabel = group.addShape('text', {
                  attrs: {
                    fill: '#fff',
                    fontSize: 20,
                    x: 0,
                    y: 10,
                    text: name.length > 28 ? name.substr(0, 16) + '...' : name,
                    textAlign: 'center',
                    opacity: 0
                  },
                  // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                  name: 'mask-label-shape'
                })
                const collapseRect = group.find(ele => ele.get('name') === 'collapse-back')
                const collapseText = group.find(ele => ele.get('name') === 'collapse-text')
                collapseRect?.toFront()
                collapseText?.toFront()
              } else {
                mask.show()
                maskLabel.show()
              }
              mask.animate({ opacity: 1 }, 200)
              maskLabel.animate({ opacity: 1 }, 200)
              return mask
            } else {
              group.get('children').forEach(child => {
                if (child.get('name')?.includes('collapse')) return
                child.show()
              })
              mask?.animate({ opacity: 0 }, {
                duration: 200,
                callback: () => mask.hide()
              })
              maskLabel?.animate({ opacity: 0 }, {
                duration: 200,
                callback: () => maskLabel.hide()
              })
            }
            this.updateLinkPoints(cfg, group)
          },
          setState(name, value, item) {
            if (name === 'collapse') {
              const group = item.getContainer()
              const collapseText = group.find((e) => e.get('name') === 'collapse-text')
              if (collapseText) {
                if (!value) {
                  collapseText.attr({
                    text: '-'
                  })
                } else {
                  collapseText.attr({
                    text: '+'
                  })
                }
              }
            }
          },
          getAnchorPoints() {
            return [
              [0, 0.5],
              [1, 0.5]
            ]
          }
        },
        'rect'
      )

      G6.registerEdge(
        'flow-cubic',
        {
          afterDraw(cfg, group) {
            // nginx那，否则和生产这边不统一，不去掉的话这边访问不了 原因，所以暂时先把图标隐藏掉
            // const sourceNode = cfg.sourceNode._cfg.model
            // const sourceNodeServiceName = sourceNode.service_name
            // const targetNode = cfg.targetNode._cfg.model
            // const targetNodeServiceName = targetNode.service_name
            // if (sourceNodeServiceName != targetNodeServiceName) {
            //   // 获取图形组中的第一个图形，在这里就是边的路径图形
            //   const shape = group.get('children')[0]
            //   // 获取路径图形的中点坐标
            //   const midPoint = shape.getPoint(0.5)
            //   const iconDown = _this.iconDown

            //   const visible = !(cfg.sourceNode._cfg.model.span_id == 'UNKNOWN SPAN ID' || cfg.targetNode._cfg.model.span_id == '')
            //   group.addShape('image', {
            //     attrs: {
            //       x: midPoint.x - 8,
            //       y: midPoint.y - 8,
            //       height: 16,
            //       width: 16,
            //       img: iconDown,
            //       cursor: 'pointer'
            //     },
            //     visible,
            //     name: 'name-edge-button'
            //   })
            // }
          },
          update: undefined
        },
        'single-line'
      )

      if (!data) {
        return
      }
      const { onInit, config } = props
      const tooltip = new G6.Tooltip({
        // offsetX and offsetY include the padding of the parent container
        offsetX: 20,
        offsetY: 30,
        // the types of items that allow the tooltip show up
        // 允许出现 tooltip 的 item 类型
        itemTypes: ['node'],
        // custom the tooltip's content
        // 自定义 tooltip 内容
        getContent: (e) => {
          const outDiv = document.createElement('div')
          // outDiv.style.padding = '0px 0px 20px 0px';
          const nodeName = e.item.getModel().name
          let formatedNodeName = ''
          if (nodeName != undefined) {
            for (let i = 0; i < nodeName.length; i++) {
              formatedNodeName = `${formatedNodeName}${nodeName[i]}`
              // if (i !== 0 && i % 20 === 0) formatedNodeName = `${formatedNodeName}<br/>`;
            }
            outDiv.innerHTML = `${formatedNodeName}`
            return outDiv
          }
        }
      })

      graph = new G6.TreeGraph({
        container: id,
        ...defaultConfig,
        ...config,
        plugins: [tooltip]
      })
      this.globalGraph = graph
      if (typeof onInit === 'function') {
        onInit(graph)
      }
      const tempData = this.addCollapsedToThirdLevel(data)
      graph.data(tempData)
      graph.render()
      // 让画布内容适应视口
      graph.fitView()
      // 添加点击事件
      graph.on('node:click', (evt) => {
        const item = evt.item

        const itemData = evt.item._cfg.model
        this.$emit('changeState', itemData)
      })
      // 点击线   edge:click
      graph.on('name-edge-button:click', (evt) => {
        this.networkQuery.parent_span_id = ''
        this.networkQuery.span_id = ''
        let topoData = {}
        const itemData = evt.item._cfg.model
        const { source, target } = itemData
        // source 是前面一个节点的span_id
        // target 是后面一个节点的span_id

        const firstNode = evt.item._cfg.sourceNode._cfg.model
        const newFirstNode = Object.assign({}, firstNode)
        newFirstNode.children = []
        const lastNode = evt.item._cfg.targetNode._cfg.model
        const newLastNode = Object.assign({}, lastNode)
        newLastNode.children = []
        this.flag = false
        if (source != '') {
          this.networkQuery.parent_span_id = source
          this.networkQuery.span_id = target
          networkSpans(this.networkQuery).then(res => {
            if (res.OPT_STATUS.length != 0) {
              const optList = this.handleData(res.OPT_STATUS)
              const newOptList = this.buildNestedTree(optList)

              newFirstNode.children = newOptList

              const firstList = [newFirstNode]

              const resultList = this.addDataToTree(firstList, newLastNode)

              topoData = resultList[0]

              this.networkOpen = true
              this.flag = true
              setTimeout(() => {
                this.initGraphNetwork(topoData, 'networkContainer')
              }, 300)
            } else {
              this.$message('暂无数据')
            }
          })
        }
      })

      const handleCollapse = (e) => {
        const target = e.target
        const id = target.get('modelId')
        const item = graph.findById(id)
        const nodeModel = item.getModel()
        nodeModel.collapsed = !nodeModel.collapsed
        graph.layout()
        graph.setItemState(item, 'collapse', nodeModel.collapsed)
      }
      graph.on('collapse-text:click', (e) => {
        e.stopPropagation()
        e.preventDefault()
        handleCollapse(e)
      })
      graph.on('collapse-back:click', (e) => {
        e.stopPropagation()
        e.preventDefault()
        handleCollapse(e)
      })
      let currentLevel = 1
      const briefZoomThreshold = Math.max(graph.getZoom(), 0.5)
      changeNodeColor()
      graph.on('viewportchange', e => {
        if (e.action !== 'zoom') return
        changeNodeColor()
      })
      if (typeof window !== 'undefined') {
        window.onresize = () => {
          if (!graph || graph.get('destroyed')) return
          if (!container || !container.scrollWidth || !container.scrollHeight) return
          graph.changeSize(container.scrollWidth, container.scrollHeight)
        }
      }

      function changeNodeColor() {
        const currentZoom = graph.getZoom()
        let toLevel = currentLevel
        if (currentZoom < briefZoomThreshold) {
          toLevel = 0
        } else {
          toLevel = 1
        }
        if (toLevel !== currentLevel) {
          currentLevel = toLevel
          graph.getNodes().forEach(node => {
            graph.updateItem(node, {
              level: toLevel
            })
          })
        }
      }
    },
    initGraphNetwork(data, id) {
      let graph = null
      const container = document.getElementById(id)
      // const container = this.$refs['container'];
      const width = container.scrollWidth
      const height = container.scrollHeight || 700
      // 默认配置
      const defaultConfig = {
        width,
        height,
        modes: {
          default: ['zoom-canvas', 'drag-canvas']
        },
        fitView: true,
        animate: true,
        defaultNode: {
          type: 'flow-rect'
        },
        defaultEdge: {
          type: 'cubic-horizontal',
          style: {
            stroke: '#CED4D9'
          },
          labelCfg: {
            autoRotate: true
          }
        },
        layout: {
          type: 'indented',
          direction: 'LR',
          dropCap: false,
          indent: 300,
          getHeight: () => {
            return 60
          }
        }
      }

      /**
       * 自定义节点
       */
      G6.registerNode(
        'flow-rect',
        {
          shapeType: 'flow-rect',
          draw(cfg, group) {
            const {
              name = '',
              variableValue,
              label,
              collapsed,
              currency,
              status,
              rate
            } = cfg
            const grey = '#CED4D9'
            const rectConfig = {
              width: 202,
              height: 60,
              lineWidth: 1,
              fontSize: 12,
              fill: '#fff',
              radius: 4,
              stroke: grey,
              opacity: 1
            }

            const nodeOrigin = {
              x: -rectConfig.width / 2,
              y: -rectConfig.height / 2
            }

            const textConfig = {
              textAlign: 'left',
              textBaseline: 'bottom'
            }

            const rect = group.addShape('rect', {
              attrs: {
                x: nodeOrigin.x,
                y: nodeOrigin.y,
                ...rectConfig
              }
            })

            const rectBBox = rect.getBBox()

            // label title
            group.addShape('text', {
              attrs: {
                ...textConfig,
                x: 12 + nodeOrigin.x,
                y: 20 + nodeOrigin.y,
                text: name.length > 28 ? name.substr(0, 28) + '...' : name,
                fontSize: 12,
                opacity: 0.85,
                fill: '#000',
                cursor: 'pointer'
              },
              // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
              name: 'name-shape'
            })

            // price
            const price = group.addShape('text', {
              attrs: {
                ...textConfig,
                x: 12 + nodeOrigin.x,
                y: rectBBox.maxY - 12,
                text: label,
                fontSize: 16,
                fill: '#000',
                opacity: 0.85
              }
            })

            // label currency   换成ms
            group.addShape('text', {
              attrs: {
                ...textConfig,
                x: price.getBBox().maxX + 5,
                y: rectBBox.maxY - 12,
                text: currency,
                fontSize: 12,
                fill: '#000',
                opacity: 0.75
              }
            })

            // percentage
            const percentText = group.addShape('text', {
              attrs: {
                ...textConfig,
                x: rectBBox.maxX - 8,
                y: rectBBox.maxY - 12,
                text: `${((variableValue || 0) * 100).toFixed(2)}%`,
                fontSize: 12,
                textAlign: 'right',
                fill: colors[status]
              }
            })

            // bottom line background
            const bottomBackRect = group.addShape('rect', {
              attrs: {
                x: nodeOrigin.x,
                y: rectBBox.maxY - 4,
                width: rectConfig.width,
                height: 4,
                radius: [0, 0, rectConfig.radius, rectConfig.radius],
                fill: '#E0DFE3'
              }
            })

            // bottom percent
            const bottomRect = group.addShape('rect', {
              attrs: {
                x: nodeOrigin.x,
                y: rectBBox.maxY - 4,
                width: rate < 1 ? rate * rectBBox.width : rectBBox.width - 1,
                height: 4,
                radius: rate < 1 ? [0, 0, 0, rectConfig.radius] : [0, 0, rectConfig.radius, rectConfig.radius],
                fill: colors[status]
              }
            })

            // collapse rect
            if (cfg.children && cfg.children.length) {
              group.addShape('rect', {
                attrs: {
                  x: rectConfig.width / 2 - 8,
                  y: -8,
                  width: 16,
                  height: 16,
                  stroke: 'rgba(0, 0, 0, 0.25)',
                  cursor: 'pointer',
                  fill: '#fff'
                },
                // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                name: 'collapse-back',
                modelId: cfg.id
              })
              // collpase text
              group.addShape('text', {
                attrs: {
                  x: rectConfig.width / 2,
                  y: -1,
                  textAlign: 'center',
                  textBaseline: 'middle',
                  text: collapsed ? '+' : '-',
                  fontSize: 16,
                  cursor: 'pointer',
                  fill: 'rgba(0, 0, 0, 0.25)'
                },
                // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                name: 'collapse-text',
                modelId: cfg.id
              })
            }

            this.drawLinkPoints(cfg, group)
            return rect
          },
          update(cfg, item) {
            const { level, status, name } = cfg
            const group = item.getContainer()
            let mask = group.find(ele => ele.get('name') === 'mask-shape')
            let maskLabel = group.find(ele => ele.get('name') === 'mask-label-shape')
            if (level === 0) {
              group.get('children').forEach(child => {
                if (child.get('name')?.includes('collapse')) return
                child.hide()
              })
              if (!mask) {
                mask = group.addShape('rect', {
                  attrs: {
                    x: -101,
                    y: -30,
                    width: 202,
                    height: 60,
                    opacity: 0,
                    fill: colors[status]
                  },
                  // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                  name: 'mask-shape'
                })
                maskLabel = group.addShape('text', {
                  attrs: {
                    fill: '#fff',
                    fontSize: 20,
                    x: 0,
                    y: 10,
                    text: name.length > 28 ? name.substr(0, 16) + '...' : name,
                    textAlign: 'center',
                    opacity: 0
                  },
                  // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                  name: 'mask-label-shape'
                })
                const collapseRect = group.find(ele => ele.get('name') === 'collapse-back')
                const collapseText = group.find(ele => ele.get('name') === 'collapse-text')
                collapseRect?.toFront()
                collapseText?.toFront()
              } else {
                mask.show()
                maskLabel.show()
              }
              mask.animate({ opacity: 1 }, 200)
              maskLabel.animate({ opacity: 1 }, 200)
              return mask
            } else {
              group.get('children').forEach(child => {
                if (child.get('name')?.includes('collapse')) return
                child.show()
              })
              mask?.animate({ opacity: 0 }, {
                duration: 200,
                callback: () => mask.hide()
              })
              maskLabel?.animate({ opacity: 0 }, {
                duration: 200,
                callback: () => maskLabel.hide()
              })
            }
            this.updateLinkPoints(cfg, group)
          },
          setState(name, value, item) {
            if (name === 'collapse') {
              const group = item.getContainer()
              const collapseText = group.find((e) => e.get('name') === 'collapse-text')
              if (collapseText) {
                if (!value) {
                  collapseText.attr({
                    text: '-'
                  })
                } else {
                  collapseText.attr({
                    text: '+'
                  })
                }
              }
            }
          },
          getAnchorPoints() {
            return [
              [0, 0.5],
              [1, 0.5]
            ]
          }
        },
        'rect'
      )

      G6.registerNode(
        'flow-circle',
        {
          shapeType: 'flow-circle',
          draw(cfg, group) {
            const {
              span_name,
              label,
              span_category
            } = cfg
            const radius = (60 / 2) - 2
            const circleBoxlenght = cfg.size
            const circle = group.addShape('circle', {
              attrs: {
                x: 0,
                y: 0,
                r: radius,
                fill: '#F0F4FE',
                stroke: '#6B94F7',
                lineWidth: 2
              },
              name: 'circle-shape'
            })

            group.addShape('text', {
              attrs: {
                x: 0,
                y: 0,
                text: label,
                fill: '#333',
                fontSize: 12,
                textAlign: 'center', // 文本居中
                textBaseline: 'middle' // 文本垂直居中
                // fill: cfg.color, // 节点颜色
              },
              name: 'label-shape'
            })

            group.addShape('text', {
              attrs: {
                x: 0,
                y: radius + 20,
                text: span_name,
                fill: '#333',
                fontSize: 12,
                textAlign: 'center' // 文本居中
              },
              name: 'span-name-shape'
            })
            group.addShape('text', {
              attrs: {
                x: 0,
                y: radius + 40,
                text: span_category,
                fill: '#333',
                fontSize: 12,
                textAlign: 'center' // 文本居中
              },
              name: 'span-category-shape'
            })

            return circle // 返回创建的圆形
          }
        },
        'circle'
      )

      G6.registerEdge(
        'flow-cubic',
        {
          getControlPoints(cfg) {
            let controlPoints = cfg.controlPoints // 指定controlPoints
            if (!controlPoints || !controlPoints.length) {
              const { startPoint, endPoint, sourceNode, targetNode } = cfg
              const { x: startX, y: startY, coefficientX, coefficientY } = sourceNode
                ? sourceNode.getModel()
                : startPoint
              const { x: endX, y: endY } = targetNode ? targetNode.getModel() : endPoint
              let curveStart = (endX - startX) * coefficientX
              let curveEnd = (endY - startY) * coefficientY
              curveStart = curveStart > 40 ? 40 : curveStart
              curveEnd = curveEnd < -30 ? curveEnd : -30
              controlPoints = [
                { x: startPoint.x + curveStart, y: startPoint.y },
                { x: endPoint.x + curveEnd, y: endPoint.y }
              ]
            }
            return controlPoints
          },
          getPath(points) {
            const path = []
            path.push(['M', points[0].x, points[0].y])
            path.push([
              'C',
              points[1].x,
              points[1].y,
              points[2].x,
              points[2].y,
              points[3].x,
              points[3].y
            ])
            return path
          }
        },
        'single-line'
      )

      if (!data) {
        return
      }
      const { onInit, config } = props
      const tooltip = new G6.Tooltip({
        // offsetX and offsetY include the padding of the parent container
        offsetX: 20,
        offsetY: 30,
        // the types of items that allow the tooltip show up
        // 允许出现 tooltip 的 item 类型
        itemTypes: ['node'],
        // custom the tooltip's content
        // 自定义 tooltip 内容
        getContent: (e) => {
          const outDiv = document.createElement('div')
          const nodeName = e.item.getModel().name
          const item = e.item.getModel()
          const detail = item.detail
          if (item.detail != undefined) {
            let html = ''
            for (const key in detail) {
              html += `<div class='nodeDetail' style='height:20px;line-height:20px;'>
                  <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>${key}：</span>
                  <span class='value' style='display: inline-block;vertical-align: middle;'>${detail[key]}</span>
                </div>`
            }
            outDiv.innerHTML = `<div style='margin:-9px;position:relative'>
              <div style='padding:10px;'>
                <div class='nodeDetail' style='height:20px;line-height:20px;'>
                  <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>SpanID：</span>
                  <span class='value' style='display: inline-block;vertical-align: middle;'>${item.span_id}</span>
                </div>
                <div class='nodeDetail' style='height:20px;line-height:20px;'>
                  <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>SpanName：</span>
                  <span class='value' style='display: inline-block;vertical-align: middle;'>${item.span_name}</span>
                </div>
                <div class='nodeDetail' style='height:20px;line-height:20px;'>
                  <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>SpanCategory：</span>
                  <span class='value' style='display: inline-block;vertical-align: middle;'>${item.span_category}</span>
                </div>
                <div class='nodeDetail' style='height:20px;line-height:20px;'>
                  <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>Duration：</span>
                  <span class='value' style='display: inline-block;vertical-align: middle;'>${item.duration}</span>
                </div>
                <div class='nodeDetail' style='height:20px;line-height:20px;'>
                  <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>FlatDuration：</span>
                  <span class='value' style='display: inline-block;vertical-align: middle;'>${item.flat_duration}</span>
                </div>
                ${html}
              </div>
              <div style='position:absolute;bottom:10px;right:10px;width:80px;height:80px;z-index: -1;backdrop-filter: blur(10px);background-image:url("${item.span_category == 'apm' ? this.apm : this.apis}");background-size:cover;background-repeat:no-repeat;background-position: center;'>
              </div>
            </div>
            `
            return outDiv
          } else {
            let formatedNodeName = ''
            for (let i = 0; i < nodeName.length; i++) {
              formatedNodeName = `${formatedNodeName}${nodeName[i]}`
              // if (i !== 0 && i % 20 === 0) formatedNodeName = `${formatedNodeName}<br/>`;
            }
            outDiv.innerHTML = `${formatedNodeName}`
            return outDiv
          }
        }
      })

      graph = new G6.TreeGraph({
        container: id,
        ...defaultConfig,
        ...config,
        plugins: [tooltip]
      })

      if (typeof onInit === 'function') {
        onInit(graph)
      }
      graph.data(data)
      graph.render()
      // 让画布内容适应视口
      graph.fitView()
      // 添加点击事件
      graph.on('node:click', (evt) => {
        const itemData = evt.item._cfg.model
        // const { level, id } = itemData
        this.$emit('changeState', itemData)
      })

      const handleCollapse = (e) => {
        const target = e.target
        const id = target.get('modelId')
        const item = graph.findById(id)
        const nodeModel = item.getModel()
        nodeModel.collapsed = !nodeModel.collapsed
        graph.layout()
        graph.setItemState(item, 'collapse', nodeModel.collapsed)
      }
      graph.on('collapse-text:click', (e) => {
        e.stopPropagation()
        e.preventDefault()
        handleCollapse(e)
      })
      graph.on('collapse-back:click', (e) => {
        e.stopPropagation()
        e.preventDefault()
        handleCollapse(e)
      })
      let currentLevel = 1
      const briefZoomThreshold = Math.max(graph.getZoom(), 0.5)
      changeNodeColor()
      graph.on('viewportchange', e => {
        if (e.action !== 'zoom') return
        changeNodeColor()
      })
      if (typeof window !== 'undefined') {
        window.onresize = () => {
          if (!graph || graph.get('destroyed')) return
          if (!container || !container.scrollWidth || !container.scrollHeight) return
          graph.changeSize(container.scrollWidth, container.scrollHeight)
        }
      }
      function changeNodeColor () {
        const currentZoom = graph.getZoom()
        let toLevel = currentLevel
        if (currentZoom < briefZoomThreshold) {
          toLevel = 0
        } else {
          toLevel = 1
        }
        if (toLevel !== currentLevel) {
          currentLevel = toLevel
          graph.getNodes().forEach(node => {
            graph.updateItem(node, {
              level: toLevel
            })
          })
        }
      }
    },
    addCollapsedToThirdLevel(data, level = 1) {
      if (level === 3) {
        return {
          ...data,
          collapsed: true,
          children: data.children && data.children.map(child => ({...child}))
        };
      }

      if (data.children && data.children.length > 0) {
        return {
          ...data,
          children: data.children.map(child => this.addCollapsedToThirdLevel(child, level + 1))
        };
      }

      return {...data};
    },

    clearGraph() {
      this.globalGraph.clear()
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  width:100%;
  height: calc( 100vh - 182px);
  background: #fff;
}
.full{
  width:32px;
  height:32px;
  position: absolute;
  top:5px;
  right:0px;
  display: block;
  i{
    font-size: 16px;
    color:#999;
  }
}
.nodeDetail{
  margin:4px;
  .label,.value{
    display: inline-block;
  }
  .label{
    display: inline-block;
    width: 120px; /* 限制容器宽度 */
    white-space: nowrap; /* 不换行 */
    overflow: hidden; /* 隐藏溢出内容 */
    text-overflow: ellipsis; /* 使用省略号表示截断 */
    text-align: right;
  }
}
.legend{
  position: absolute;
  left:0px;
  bottom:30px;
  // z-index: 1001;
  transition: all .3s;
}
.listwrap{
  color:#666;
  span{
    display: inline-block;
    padding:4px;
  }
  .value{
    width:80px;
    box-sizing: border-box;
    padding-right: 10px;
  }
}
</style>
