<script>
export default {
  inheritAttrs: false
}
</script>

<script setup>
import { StepEdge, EdgeLabelRenderer, getSmoothStepPath, useVueFlow, useEdge, MarkerType } from '@vue-flow/core'
import { Plus } from '@element-plus/icons-vue'
import { nanoid } from 'nanoid'

const props = defineProps({
  id: { type: String, required: true },
  sourceX: { type: Number, required: true },
  sourceY: { type: Number, required: true },
  targetX: { type: Number, required: true },
  targetY: { type: Number, required: true },
  sourcePosition: { type: String, required: true },
  targetPosition: { type: String, required: true },
  data: { type: Object, required: false },
  markerEnd: { type: String, required: false },
  style: { type: Object, required: false },
  selected: { type: Boolean, required: false },
  disabled: { type: Boolean, required: false }
})

const path = computed(() => getSmoothStepPath(props))

const { addNodes, addEdges, removeEdges } = useVueFlow()

const { edge } = useEdge()
function addNodeBetweenEdges() {
  const { source, target, sourceNode, targetNode } = edge
  const newNodeId = nanoid(4)
  const newNode = {
    id: newNodeId,
    type: 'custom',
    label: `旅程节点`,
    data: { label: '旅程节点' },
    position: {
      x: (sourceNode.position.x + targetNode.position.x) / 2,
      y: (sourceNode.position.y + targetNode.position.y) / 2
    }
  }
  addNodes([newNode])

  const newEdges = [
    {
      id: `${source}->${newNodeId}`,
      type: 'custom',
      source: source,
      target: newNodeId,
      animated: true,
      markerEnd: MarkerType.ArrowClosed
    },
    {
      id: `${newNodeId}->${target}`,
      type: 'custom',
      source: newNodeId,
      target: target,
      animated: true,
      markerEnd: MarkerType.ArrowClosed
    }
  ]
  removeEdges([props.id])
  addEdges(newEdges)
}
</script>

<template>
  <StepEdge :id="id" :style="style" :path="path[0]" :marker-end="markerEnd" :interactionWidth="30"></StepEdge>
  <EdgeLabelRenderer>
    <div
      :style="{
        pointerEvents: 'all',
        position: 'absolute',
        transform: `translate(-50%, -50%) translate(${path[1]}px,${path[2]}px)`
      }"
      v-if="!disabled">
      <el-button-group>
        <el-button :icon="Plus" circle @click="addNodeBetweenEdges"></el-button>
      </el-button-group>
    </div>
  </EdgeLabelRenderer>
</template>
