<template>
  <template v-if="port?.group === 'start'">
    <div class="port">
      <div/>
    </div>
  </template>
  <template v-else>
    <ElPopover placement="right" trigger="click">
      <template #reference>
        <div class="port">
          <ElTooltip
            placement="top"
            content="123"
            raw-content
          >
            <div/>
          </ElTooltip>
        </div>
      </template>
      <div class="node-add">
        <div class="node-add-item __hover" @click="onAddNode('test')">测试节点</div>
        <div class="node-add-item __hover" @click="onAddNode('if-else')">条件分支</div>
      </div>
    </ElPopover>
  </template>
</template>

<script setup lang="ts">
import {getCurrentInstance, inject, reactive, ref} from "vue";
import { ElPopover, ElTooltip } from 'element-plus';
import {getNodeDefault} from "@/views/workflow/config";
import {WorkflowFunc} from "@/views/workflow/types";
import {handleEdge, handleNode} from "@/views/workflow/handle";

const emits = defineEmits([])
const props = defineProps({
  port: <any>{},
  node: <any>{},
  graph: <any>{},
})
const {proxy}: any = getCurrentInstance()
const state: any = reactive({})
const onAddNode = (type) => {
  const node = getNodeDefault(type)
  const sons = props.graph.getSuccessors(props.node, {breadthFirst: true, deep: false, distance: 1}).filter(v => v.data.edgeSource === props.port.id)
  console.log(sons)
  const diff = 100
  let X = 0
  let Y = 0
  if (sons.length > 0) {
    sons.forEach(s => {
      const {x, y} = s.position()
      const {width, height} = s.size()
      X = Math.max(x, X)
      Y = Math.max(y + height, Y)
    })
    Y += diff
  } else {
    const {x, y} = props.node.position()
    const {width, height} = props.node.size()
    X = x + width + diff
    Y = y
  }

  node.x = X
  node.y = Y
  const edge = {
    target: node.id,
    source: props.port.args.nodeId,
    port: '',
  }
  console.log(props.port)
  if (props.port.args.type === 'more') {
    edge.port = props.port.id
    node.data.edgeSource = props.port.id
  } else {
    node.data.edgeSource = `${props.node.id}_end`
  }
  console.log(node)
  console.log(edge)
  props.graph.addNode(handleNode(node))
  props.graph.addEdge(handleEdge(edge))
}
</script>

<style lang="scss" scoped>
.port {
  width: 100%;
  height: 100%;
  >div {
    width: 100%;
    height: 100%;
    border: 1px solid #8f8f8f;
    background-color: #ffffff;
    border-radius: 50%;
  }
}
.node-add {
  width: 100px;
}
</style>