<template>
  <div class="flowchart-container" ref="container">
    <div class="flowchart" :style="flowchartStyle">
      <FlowNode
        v-for="node in nodes"
        :key="node.id"
        :node="node"
        @add-child="handleAddChild"
        @node-drag="handleNodeDrag"
      />
      <svg class="connectors">
        <path
          v-for="connector in connectors"
          :key="connector.id"
          :d="connector.path"
          stroke="#999"
          stroke-width="2"
          fill="none"
          marker-end="url(#arrowhead)"
        />
      </svg>
    </div>
    <defs>
      <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
        <polygon points="0 0, 10 3.5, 0 7" fill="#999" />
      </marker>
    </defs>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useDraggable } from '@vueuse/core'
import FlowNode from './FlowNode.vue'

// 节点类型定义
const nodeTypes = {
  start: { name: '开始', color: '#4CAF50' },
  process: { name: '处理', color: '#2196F3' },
  decision: { name: '判断', color: '#FFC107' },
  end: { name: '结束', color: '#F44336' }
}

// 初始节点数据
const nodes = ref([
  {
    id: '1',
    type: 'start',
    x: 300,
    y: 50,
    children: ['2']
  },
  {
    id: '2',
    type: 'process',
    x: 300,
    y: 150,
    parent: '1'
  }
])

// 容器拖拽
const container = ref(null)
// 修改容器拖拽初始化
const { x: containerX, y: containerY } = useDraggable(container, {
  onStart: (e) => {
    // 只有当点击的不是节点时才允许拖拽容器
    return !e.target.closest('.flow-node')
  }
})

// 修改节点拖拽处理
const handleNodeDrag = (nodeId, newX, newY) => {
  const nodeIndex = nodes.value.findIndex(n => n.id === nodeId)
  if (nodeIndex !== -1) {
    // 创建新数组确保响应性
    const newNodes = [...nodes.value]
    newNodes[nodeIndex] = {
      ...newNodes[nodeIndex],
      x: newX,
      y: newY
    }
    nodes.value = newNodes
  }
}
const flowchartStyle = computed(() => ({
  transform: `translate(${containerX.value}px, ${containerY.value}px)`
}))

// 计算连接线
const connectors = computed(() => {
  const result = []
  nodes.value.forEach(node => {
    if (node.children) {
      node.children.forEach(childId => {
        const childNode = nodes.value.find(n => n.id === childId)
        if (childNode) {
          result.push({
            id: `${node.id}-${childId}`,
            path: calculatePath(node, childNode)
          })
        }
      })
    }
  })
  return result
})

function calculatePath(startNode, endNode) {
  const startX = startNode.x + 100
  const startY = startNode.y + 40
  const endX = endNode.x + 100
  const endY = endNode.y

  // 简单的贝塞尔曲线路径
  const controlY = (startY + endY) / 2
  return `M${startX},${startY} C${startX},${controlY} ${endX},${controlY} ${endX},${endY}`
}

// 添加子节点
function handleAddChild(parentId, nodeType) {
  const parentNode = nodes.value.find(n => n.id === parentId)
  if (!parentNode) return

  const newNodeId = Date.now().toString()
  const newNode = {
    id: newNodeId,
    type: nodeType,
    x: parentNode.x,
    y: parentNode.y + 120,
    parent: parentId
  }

  if (!parentNode.children) {
    parentNode.children = []
  }
  parentNode.children.push(newNodeId)

  nodes.value.push(newNode)
}
// 自动排列
function autoLayout() {
  // 这里可以实现自动排列算法，如树状布局等
  // 简化版：简单垂直排列
  nodes.value.forEach((node, index) => {
    if (index > 0) {
      node.x = 300
      node.y = 50 + index * 120
    }
  })
}

// 初始化时自动排列
onMounted(() => {
  autoLayout()
})
</script>

<style>
.flowchart-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  cursor: grab;
}

.flowchart {
  position: relative;
  width: max-content;
  height: max-content;
}

.connectors {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}
</style>