<template>
  <div style="position:relative;">
    <div :id="topoId" ref="container" class="container" />
    <el-card class="legend">
      <div >
        <h2 style="margin-top:0">图例</h2>
        <div class="listwrap">
          <span class="value">
            <el-progress :percentage="100" :color="'#5B8FF9'" :show-text="false" />
          </span>
          <span class="lable">0.6 <= 成功率 <=1 </span>
        </div>
        <div class="listwrap">
          <span class="value">
            <el-progress :percentage="100" :color="'#F46649'" :show-text="false" />
          </span>
          <span class="lable">0.1 <= 成功率 <= 0.5</span>
        </div>
        <div class="listwrap">
          <span class="value">
            <el-progress :percentage="100" :color="'#A7A7A7'" :show-text="false" />
          </span>
          <span class="lable">成功率: 0</span>
        </div>

      </div>
    </el-card>
  </div>
</template>

<script>
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,
      max_depth: 0
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.initGraph(this.graphData, this.topoId)
    })
  },
  destroy() {
    if (screenfull.isEnabled) {
      screenfull.off('change', this.change)
    }
  },
  methods: {
    init() {
      if (screenfull.isEnabled) {
        screenfull.on('change', this.change)		// 开启监听
      }
    },
    change() {
      this.isFull = screenfull.isFullscreen // 更新全屏状态
    },
    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};
    },
    initGraph(data, id) {
      function replaceIds(obj) {
        if (typeof obj === 'object' && obj!== null) {
          // if (obj.unique_id) {
          //   let arr = obj.unique_id.split('-')
          //   if (arr.length == 3) { // 设置展开还是收起状态
          //     obj.collapsed = true
          //   }
          // }
          if (obj.hasOwnProperty('id') && obj.hasOwnProperty('unique_id') ) {
            let temp = ''
            temp = obj.id
            obj.id = obj.unique_id
            obj.unique_id = temp
          }
          if (obj.hasOwnProperty('children') && obj.children !== null) {
            obj.children && obj.children.forEach(child => {
              replaceIds(child)
            });
          }
        }
        return obj
      }
      data = replaceIds(data)
      let graph = null
      const container = document.getElementById(id)
      const width = container.scrollWidth
      const height = container.scrollHeight || 500

      // 默认配置
      const defaultConfig = {
        width,
        height,
        modes: {
          default: ['zoom-canvas', 'drag-canvas']
        },
        fitView: true,
        fitViewPadding: [50, 50],
        fitCenter: true,
        maxZoom: 2, // 默认值是10
        minZoom: 0.02, // 默认值是0.02
        animate: true,
        defaultNode: {
          type: 'flow-rect'
        },
        defaultEdge: {
          type: 'cubic-horizontal',
          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]
              }
            })

            // percentage triangle
            const symbol = variableUp ? 'triangle' : 'triangle-down'
            const triangle = group.addShape('marker', {
              attrs: {
                ...textConfig,
                x: percentText.getBBox().minX - 10,
                y: rectBBox.maxY - 12 - 6,
                symbol,
                r: 6,
                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',
        {
          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')
          // outDiv.style.padding = '0px 0px 20px 0px';
          const nodeName = e.item.getModel().name
          const item = e.item.getModel()
          outDiv.innerHTML = `
            <div style="margin-bottom:8px">
              <span style='display:inline-block;width:120px;text-align:right;'>节点类型：</span>
              <span style='display:inline-block;'>${item.span_type}</span>
            </div>
            <div style="margin-bottom:8px">
              <span style='display:inline-block;width:120px;text-align:right;'>所属服务：</span>
              <span style='display:inline-block;'>${item.service_name}</span>
            </div>
            <div style="margin-bottom:8px">
              <span style='display:inline-block;width:120px;text-align:right;'>Span名称：</span>
              <span style='display:inline-block;'>${item.span_name}</span>
            </div>
            <div style="margin-bottom:8px">
              <span style='display:inline-block;width:120px;text-align:right;'>Span类型：</span>
              <span style='display:inline-block;'>${item.span_kind}</span>
            </div>
            <div style="margin-bottom:8px">
              <span style='display:inline-block;width:120px;text-align:right;'>中位时延：</span>
              <span style='display:inline-block;'>${item.label}</span>
            </div>
            <div style="margin-bottom:8px">
              <span style='display:inline-block;width:120px;text-align:right;'>成功率：</span>
              <span style='display:inline-block;'>${item.variableValue}</span>
            </div>
           `
          return outDiv
        },
        shouldBegin: (e) => {
          if (e.target.get('name') === 'name-shape' || e.target.get('name') === 'mask-label-shape') return true
          return false
        }
      })
      graph = new G6.TreeGraph({
        container: id,
        ...defaultConfig,
        ...config,
        plugins: [tooltip]
      })

      if (typeof onInit === 'function') {
        onInit(graph)
      }
      const tempData = this.addCollapsedToThirdLevel(data)
      graph.data(tempData)
      graph.render()
      // 让画布内容适应视口
      graph.fitView()

      // 添加点击事件
      graph.on('node:click', (evt) => {
        const itemData = evt.item._cfg.model
        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
            })
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  width:100%;
  // height: calc( 100vh - 182px);
  background: #fff;
  // margin-top:90px;
}
.legend{
  position: absolute;
  left:0px;
  bottom:30px;
  // z-index: 1001;
  transition: all .3s;
  // padding: 16px;
}
.full{
  width:32px;
  height:32px;
  position: absolute;
  top:5px;
  right:0px;
  display: block;
  i{
    font-size: 16px;
    color:#999;
  }
}
.listwrap{
  color:#666;
  span{
    display: inline-block;
    padding:4px;
  }
  .value{
    width:80px;
    box-sizing: border-box;
    padding-right: 10px;
  }
}
</style>
