<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { VueFlow, useVueFlow, Handle, Position, type Node, type Edge } from '@vue-flow/core'
import { Controls } from '@vue-flow/controls'
import '@vue-flow/core/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'
import '@vue-flow/controls/dist/style.css'
import {
  useAgentsStore,
  useSelectionStore,
  type IRawStepTask,
  type IApiAgentAction
} from '@/stores'
import { getAgentMapIcon, getActionTypeDisplay } from '@/layout/components/config.ts'
import SvgIcon from '@/components/SvgIcon/index.vue'
import { ElTooltip, ElIcon, ElMessage } from 'element-plus'
import { CirclePlus, Remove } from '@element-plus/icons-vue'
import api from '@/api'
import { v4 as uuidv4 } from 'uuid'

const agentsStore = useAgentsStore()
const selectionStore = useSelectionStore()
const { onConnect, addEdges, fitView: fit } = useVueFlow()

// 🆕 直接从 store 获取当前任务和任务过程数据
const currentTask = computed(() => agentsStore.currentTask)
const taskProcess = computed(() => agentsStore.currentTask?.TaskProcess ?? [])

// 添加分支相关状态
const addingBranchNodeId = ref<string | null>(null)
const branchInput = ref('')
const branchInputRef = ref<InstanceType<typeof HTMLInputElement>>()

// 分支加载状态
const branchLoading = ref(false)

// Mock 数据配置
const USE_MOCK_DATA = false

// 节点和边数据
const nodes = ref<Node[]>([])
const edges = ref<Edge[]>([])

//当前选中的节点ID集合
const selectedNodeIds = ref<Set<string>>(new Set())

// 用于防止重复同步的标志
let isSyncing = false

//初始化标记，避免重复初始化
const BRANCHES_INIT_KEY_PREFIX = 'plan-task-branches-initialized-'

// 🆕 最后选中的分支ID
const LAST_SELECTED_BRANCH_KEY = 'plan-task-last-selected-branch'

// ==================== 辅助函数定义 ====================

// 🆕 获取分支的所有节点（只沿着分支创建方向遍历：right handle连接）
const getAllBranchNodes = (startNodeId: string): string[] => {
  const visited = new Set<string>()
  const toVisit: string[] = [startNodeId]

  while (toVisit.length > 0) {
    const currentId = toVisit.shift()!

    if (visited.has(currentId)) {
      continue
    }
    visited.add(currentId)

    // 🆕 只查找通过 right handle 连接的后续节点（分支创建方向）
    const outgoingEdges = edges.value.filter(
      edge => edge.source === currentId && edge.sourceHandle === 'right'
    )

    for (const edge of outgoingEdges) {
      const targetNodeId = edge.target
      // 只访问分支节点（不包含主流程节点和根节点）
      if (
        !visited.has(targetNodeId) &&
        targetNodeId !== 'root' &&
        nodes.value.find(n => n.id === targetNodeId)?.data.isBranchTask
      ) {
        toVisit.push(targetNodeId)
      }
    }
  }

  return Array.from(visited)
}

// 🆕 获取从指定节点回溯到根节点的路径（只包含主流程节点）
const getPathToRoot = (targetNodeId: string): string[] => {
  const path: string[] = []
  const visited = new Set<string>()
  const queue: Array<{ nodeId: string; path: string[] }> = []

  queue.push({ nodeId: targetNodeId, path: [targetNodeId] })

  while (queue.length > 0) {
    const { nodeId: currentId, path: currentPath } = queue.shift()!

    if (currentId === 'root') {
      // 找到根节点，返回路径（排除根节点本身）
      return currentPath.filter(id => id !== 'root')
    }

    if (visited.has(currentId)) {
      continue
    }
    visited.add(currentId)

    // 只查找指向当前节点的边（回溯）
    const incomingEdges = edges.value.filter(edge => edge.target === currentId)

    for (const edge of incomingEdges) {
      // 只沿着非分支节点回溯（主流程节点）
      const sourceNode = nodes.value.find(n => n.id === edge.source)
      if (sourceNode && !sourceNode.data.isBranchTask) {
        const newPath = [edge.source, ...currentPath]
        queue.push({ nodeId: edge.source, path: newPath })
      }
    }
  }

  return path
}

// 🆕 向上回溯分支的父节点链（只包含分支节点）
const getBranchParentChain = (targetNodeId: string): string[] => {
  const parentChain: string[] = []
  let currentId = targetNodeId

  while (currentId && currentId !== 'root') {
    // 查找指向当前节点的边
    const incomingEdge = edges.value.find(edge => edge.target === currentId)

    if (!incomingEdge) {
      break
    }

    const sourceNode = nodes.value.find(n => n.id === incomingEdge.source)

    // 如果父节点不是分支节点，停止回溯
    if (!sourceNode || !sourceNode.data.isBranchTask) {
      break
    }

    // 添加父节点到链中
    parentChain.push(sourceNode.id)
    currentId = sourceNode.id
  }

  return parentChain
}

// ==================== 初始化流程图 ====================
const initializeFlow = () => {
  if (!currentTask.value) {
    nodes.value = []
    edges.value = []
    return
  }

  // 🆕 获取当前流程数据
  const taskStepId = currentTask.value.Id
  // 🆕 获取当前 agent 组合（用于区分不同 agent 组合的分支数据）
  const currentAgents = currentTask.value.AgentSelection || []

  // 🆕 直接使用 taskProcess.value 作为数据源
  // 注意：虽然 currentTask.id 相同，但不同的 agent 组合对应的 agent 任务过程不同
  // taskProcess.value 从 currentTask.TaskProcess 获取，能正确反映当前 agent 组合的任务过程
  const currentTaskProcess = taskProcess.value
  console.log('currentTaskProcess:', currentTaskProcess)
  // 🆕 立即保存为副本（深拷贝）
  const taskProcessCopy = JSON.parse(JSON.stringify(currentTaskProcess))

  // 🆕 使用副本数据创建节点（而不是 currentTaskProcess）
  const taskProcessForNodes = taskProcessCopy
  const newNodes: Node[] = []
  const newEdges: Edge[] = []

  // 添加根节点
  newNodes.push({
    id: 'root',
    type: 'root',
    position: { x: 50, y: 150 },
    data: {
      isRoot: true
    }
  })

  // 添加 agent 节点
  taskProcessForNodes.forEach((process: any, index: number) => {
    const agentInfo = getAgentMapIcon(process.AgentName)
    const actionTypeInfo = getActionTypeDisplay(process.ActionType)

    // 从 agentsStore 中获取 agent 的个人简介
    const agentProfile =
      agentsStore.agents.find((agent: any) => agent.Name === process.AgentName)?.Profile ||
      '暂无个人简介'

    newNodes.push({
      id: `agent-${index}`,
      type: 'agent',
      position: {
        x: 150 + index * 120,
        y: 150
      },
      data: {
        agentName: process.AgentName,
        agentIcon: agentInfo.icon,
        agentColor: agentInfo.color,
        actionTypeColor: actionTypeInfo?.color || '#909399',
        agentDescription: process.Description || '暂无描述',
        agentProfile: agentProfile,
        actionTypeName: actionTypeInfo?.name || '未知职责',
        actionTypeKey: actionTypeInfo?.key || 'unknown',
        isRoot: false,
        originalIndex: index // 记录原始索引
      }
    })
  })

  // 添加边
  // 根节点连接到第一个 agent
  if (taskProcessForNodes.length > 0) {
    newEdges.push({
      id: 'edge-root-0',
      source: 'root',
      sourceHandle: 'right',
      target: 'agent-0',
      targetHandle: 'left',
      type: 'smoothstep',
      animated: true,
      style: { stroke: '#43a8aa', strokeWidth: 2 }
    })
  }

  // agent 之间依次连接
  for (let i = 0; i < taskProcessForNodes.length - 1; i++) {
    newEdges.push({
      id: `edge-${i}`,
      source: `agent-${i}`,
      sourceHandle: 'right',
      target: `agent-${i + 1}`,
      targetHandle: 'left',
      type: 'smoothstep',
      animated: true,
      style: { stroke: '#43a8aa', strokeWidth: 2 }
    })
  }

  nodes.value = newNodes
  edges.value = newEdges

  // 📂 从 store 恢复已保存的任务过程分支数据
  // taskStepId 已在前面声明 (line 163)

  if (taskStepId) {
    // 🆕 使用当前 agent 组合获取分支数据
    const savedBranches = selectionStore.getTaskProcessBranches(taskStepId, currentAgents)

    // 🆕 检查是否已经初始化过（针对该任务和 agent 组合）
    const branchesInitKey = `${BRANCHES_INIT_KEY_PREFIX}${taskStepId}_${selectionStore.getAgentGroupKey(
      currentAgents
    )}`
    const branchesInitialized = sessionStorage.getItem(branchesInitKey) === 'true'

    if (branchesInitialized && savedBranches.length > 0) {
      nodes.value = []
      edges.value = []

      savedBranches.forEach(branch => {
        // 恢复节点（深拷贝，避免引用问题）
        branch.nodes.forEach(node => {
          nodes.value.push(JSON.parse(JSON.stringify(node)))
        })
        // 恢复边（深拷贝）
        branch.edges.forEach(edge => {
          edges.value.push(JSON.parse(JSON.stringify(edge)))
        })
      })

      // 🆕 恢复最后选中的分支
      const lastSelectedBranchId = sessionStorage.getItem(LAST_SELECTED_BRANCH_KEY)
      if (lastSelectedBranchId) {
        const lastSelectedBranch = savedBranches.find(branch => branch.id === lastSelectedBranchId)
        if (lastSelectedBranch) {
          // 恢复高亮状态
          let nodesToHighlight: string[] = []

          if (lastSelectedBranch.branchContent === '初始流程') {
            // 初始流程：高亮所有主流程节点（从恢复的nodes中获取）
            nodesToHighlight = nodes.value
              .filter(n => !n.data.isBranchTask && n.id !== 'root')
              .map(n => n.id)
          } else {
            // 其他分支：高亮主流程路径 + 分支节点（支持多级分支）
            const firstBranchNode = lastSelectedBranch.nodes[0]
            if (firstBranchNode) {
              // 找到连接到该分支的第一个节点的边（从恢复的edges中查找）
              const incomingEdge = edges.value.find(edge => edge.target === firstBranchNode.id)
              if (incomingEdge) {
                // 回溯主流程路径
                let currentNode = nodes.value.find(n => n.id === incomingEdge.source)
                while (currentNode && currentNode.id !== 'root') {
                  nodesToHighlight.unshift(currentNode.id)
                  const prevEdge = edges.value.find(e => e.target === currentNode.id)
                  currentNode = prevEdge
                    ? nodes.value.find(n => n.id === prevEdge.source)
                    : undefined
                }
              }

              // 🆕 使用多级分支逻辑：获取父节点链和子节点
              const branchParentChain = getBranchParentChain(firstBranchNode.id)
              const branchChildNodes = getAllBranchNodes(firstBranchNode.id)

              // 合并：父节点链 + 子节点
              nodesToHighlight.push(...branchParentChain, ...branchChildNodes)
            }
          }

          selectedNodeIds.value = new Set(nodesToHighlight)
        } else {
          // 找不到最后选中的分支，默认选中初始流程的高亮状态
          const mainProcessNodes = nodes.value
            .filter(n => !n.data.isBranchTask && n.id !== 'root')
            .map(n => n.id)
          selectedNodeIds.value = new Set(mainProcessNodes)
        }
      } else {
        // 没有保存的选中分支，默认选中初始流程的高亮状态
        const mainProcessNodes = nodes.value
          .filter(n => !n.data.isBranchTask && n.id !== 'root')
          .map(n => n.id)
        selectedNodeIds.value = new Set(mainProcessNodes)
      }
    } else {
      // 🆕 首次初始化：设置节点和边，并保存为"初始流程"分支
      nodes.value = newNodes
      edges.value = newEdges

      const initialBranchNodes = newNodes // ✅ 保留所有节点，包括根节点
      const initialBranchEdges = [...newEdges]

      const initialBranchId = selectionStore.addTaskProcessBranch(taskStepId, currentAgents, {
        parentNodeId: 'root',
        branchContent: '初始流程',
        branchType: 'root',
        nodes: JSON.parse(JSON.stringify(initialBranchNodes)),
        edges: JSON.parse(JSON.stringify(initialBranchEdges)),
        tasks: taskProcessCopy // 👈 使用副本（已经是深拷贝）
      })

      // 🆕 标记已初始化（针对该任务步骤和 agent 组合）
      sessionStorage.setItem(branchesInitKey, 'true')

      // 🆕 首次初始化时，设置初始流程为当前选中分支
      selectionStore.setActiveTaskProcessBranch(taskStepId, currentAgents, initialBranchId)

      // 默认选中"初始流程"的高亮状态
      const mainProcessNodes = newNodes
        .filter(n => !n.data.isBranchTask && n.id !== 'root')
        .map(n => n.id)
      selectedNodeIds.value = new Set(mainProcessNodes)
    }
  }
}

// 同步当前所有分支数据到 store
const syncBranchesToStore = () => {
  if (isSyncing || !currentTask.value?.Id) return

  isSyncing = true
  const taskStepId = currentTask.value.Id
  // 🆕 获取当前 agent 组合
  const currentAgents = currentTask.value.AgentSelection || []

  // 🔄 获取现有的分支数据（用于保留初始流程分支）
  const existingBranches = selectionStore.getTaskProcessBranches(taskStepId, currentAgents)
  const existingBranchesMap = new Map<string, any>()
  existingBranches.forEach(branch => {
    // 使用分支ID作为key
    existingBranchesMap.set(branch.id, branch)
  })

  // 获取当前所有分支节点（标记为 isBranchTask）
  const currentBranchNodes = nodes.value.filter((n: Node) => n.data.isBranchTask)

  if (currentBranchNodes.length === 0) {
    isSyncing = false
    return
  }

  // 按照分支分组节点和边
  // 通过 parentId 将节点分组
  const branchesMap = new Map<
    string,
    {
      nodes: Node[]
      edges: Edge[]
      branchContent: string
      branchType: 'root' | 'task'
      createdAt: number
      tasks?: any[] // 🆕 添加 tasks 字段
    }
  >()

  currentBranchNodes.forEach((node: Node) => {
    // 找到连接到该节点的边，确定父节点
    const incomingEdge = edges.value.find((e: Edge) => e.target === node.id)
    const parentNodeId = incomingEdge?.source || 'root'
    const isFirstBranchNode = incomingEdge?.sourceHandle === 'bottom'

    if (isFirstBranchNode) {
      if (!branchesMap.has(parentNodeId)) {
        // 🆕 从现有分支数据中恢复元数据
        const existingMetadata = existingBranchesMap.get(node.id)

        branchesMap.set(parentNodeId, {
          nodes: [],
          edges: [],
          branchContent: existingMetadata?.branchContent || '分支',
          branchType: existingMetadata?.branchType || (parentNodeId === 'root' ? 'root' : 'task'),
          createdAt: Date.now(),
          tasks: existingMetadata?.tasks //
        })
      }

      // 收集该分支的所有节点（从第一个节点开始，通过 right handle 连接的节点）
      const branchNodes: Node[] = []
      let currentNode: Node | undefined = node

      while (currentNode) {
        branchNodes.push(currentNode)

        // 查找通过 right handle 连接的下一个节点
        const outgoingEdge = edges.value.find(
          (e: Edge) => e.source === currentNode!.id && e.sourceHandle === 'right'
        )
        if (outgoingEdge) {
          currentNode = currentBranchNodes.find((n: Node) => n.id === outgoingEdge.target)
        } else {
          currentNode = undefined
        }
      }

      // 添加所有分支节点
      branchNodes.forEach((n: Node) => {
        if (
          !branchesMap
            .get(parentNodeId)!
            .nodes.find((existingNode: Node) => existingNode.id === n.id)
        ) {
          branchesMap.get(parentNodeId)!.nodes.push(n)
        }
      })

      // 找到该分支的所有边
      branchNodes.forEach((branchNode: Node) => {
        const branchEdges = edges.value.filter(
          (e: Edge) => e.source === branchNode.id || e.target === branchNode.id
        )
        branchEdges.forEach((edge: Edge) => {
          if (!branchesMap.get(parentNodeId)!.edges.find((e: Edge) => e.id === edge.id)) {
            branchesMap.get(parentNodeId)!.edges.push(edge)
          }
        })
      })
    }
  })

  // 保存所有分支到 store（使用深拷贝）
  branchesMap.forEach((branchData, parentNodeId) => {
    // 🆕 优先使用恢复的 tasks 数据，如果没有才重新创建
    let tasks = branchData.tasks

    if (!tasks || tasks.length === 0) {
      // 转换节点数据为 IRawStepTask 格式
      tasks = branchData.nodes.map((node: Node) => ({
        Id: node.id,
        StepName: node.data.actionTypeName,
        TaskContent: node.data.agentDescription,
        InputObject_List: [],
        OutputObject: '',
        AgentSelection: [node.data.agentName],
        Collaboration_Brief_frontEnd: {
          template: '',
          data: {}
        } as any,
        TaskProcess: []
      }))
    } else {
    }

    selectionStore.addTaskProcessBranch(taskStepId, currentAgents, {
      parentNodeId,
      branchContent: JSON.parse(JSON.stringify(branchData.branchContent)),
      branchType: JSON.parse(JSON.stringify(branchData.branchType)),
      nodes: JSON.parse(JSON.stringify(branchData.nodes)),
      edges: JSON.parse(JSON.stringify(branchData.edges)),
      tasks: JSON.parse(JSON.stringify(tasks)) // 🆕 优先使用恢复的 tasks
    })
  })

  // 延迟重置标志，避免连续触发
  setTimeout(() => {
    isSyncing = false
  }, 100)
}

// 监听节点和边的变化，同步到 store
// ⚠️ 已禁用自动同步，因为会导致分支ID变化，sessionStorage中保存的选中分支无法恢复
// 分支数据在添加分支时就已经保存到store了，不需要在nodes/edges变化时重新同步
// watch(
//   [nodes, edges],
//   () => {
//     // 如果正在同步，跳过
//     if (isSyncing) return

//     // 只在有分支节点时才同步
//     const hasBranchNodes = nodes.value.some((n: Node) => n.data.isBranchTask)
//     if (hasBranchNodes && currentTask.value) {
//       syncBranchesToStore()
//     }
//   },
//   { deep: true }
// )

// 组件挂载后初始化
onMounted(() => {
  if (currentTask.value) {
    initializeFlow()
    // 适应视图 - 增加padding让节点显示更小
    nextTick(() => {
      setTimeout(() => {
        fit({ padding: 0.4, duration: 300 })
      }, 100)
    })
  }
})

// 分支添加相关方法
const startAddBranch = (nodeId: string) => {
  addingBranchNodeId.value = nodeId
  branchInput.value = ''
  nextTick(() => {
    branchInputRef.value?.focus()
  })
}

const cancelAddBranch = () => {
  addingBranchNodeId.value = null
  branchInput.value = ''
}

// 🆕 节点点击事件
const onNodeClick = (event: any) => {
  const nodeId = event.node.id
  const nodeData = event.node.data as any

  // 如果点击的是根节点，不做处理（根节点不参与高亮）
  if (nodeId === 'root') {
    return
  }

  // 判断是否是分支节点
  const isBranchNode = nodeData.isBranchTask

  if (isBranchNode) {
    // 点击的是分支节点
    // 🆕 向上回溯分支父节点链（多级分支）
    const branchParentChain = getBranchParentChain(nodeId)

    // 🆕 向下遍历分支的子节点（只沿right handle方向）
    const branchChildNodes = getAllBranchNodes(nodeId)

    // 找到最顶层的分支父节点（连接到主流程或根节点的）
    let topBranchNodeId: string | null = null
    if (branchParentChain.length > 0) {
      // 取父节点链的最后一个（最顶层的分支节点）
      topBranchNodeId = branchParentChain[branchParentChain.length - 1]
    } else {
      // 如果没有分支父节点，当前节点就是最顶层
      topBranchNodeId = nodeId
    }

    // 找到最顶层分支节点的父节点（主流程节点或根节点）
    let parentNodeId: string | null = null
    const topBranchIncomingEdge = edges.value.find(edge => edge.target === topBranchNodeId)

    if (topBranchIncomingEdge) {
      parentNodeId = topBranchIncomingEdge.source
    }

    if (parentNodeId) {
      // 回溯到根节点，获取主流程路径
      const pathToRoot = getPathToRoot(parentNodeId)

      // 🔧 getPathToRoot 已经返回正序（从左到右），不需要反转
      const correctPathToRoot = pathToRoot // [agent-0, agent-1, agent-2, ...]
      const correctBranchParentChain = [...branchParentChain].reverse() // 顶层分支 → ... → 直接父分支（正序）

      // 合并：主流程路径（正序） + 分支父节点链（正序） + 分支子节点（正序）
      const allNodesToHighlight = [
        ...correctPathToRoot,
        ...correctBranchParentChain,
        ...branchChildNodes
      ]
      selectedNodeIds.value = new Set(allNodesToHighlight)

      console.log('📋 路径顺序（从上到下、从左到右）:', {
        pathToRoot: correctPathToRoot,
        branchParentChain: correctBranchParentChain,
        branchChildNodes: branchChildNodes,
        total: allNodesToHighlight.length
      })

      // 🆕 保存完整的 TaskProcess 数据（主流程 + 分支）到 store
      if (currentTask.value) {
        const completeTaskProcess: any[] = []

        // 🆕 从 store 中获取"初始流程"副本（而不是使用 taskProcess.value）
        const taskStepId = currentTask.value.Id
        const currentAgents = currentTask.value.AgentSelection || []
        const branches = selectionStore.getTaskProcessBranches(taskStepId, currentAgents)
        const initialBranch = branches.find(branch => branch.branchContent === '初始流程')
        const mainProcessData = initialBranch?.tasks || taskProcess.value

        console.log('🔍 开始按高亮路径收集数据，总节点数:', allNodesToHighlight.length)

        // 🆕 按照高亮路径顺序收集每个节点的数据
        allNodesToHighlight.forEach(nodeId => {
          const node = nodes.value.find(n => n.id === nodeId)

          if (!node) return

          // 判断是主流程节点还是分支节点
          if (!node.data.isBranchTask && node.data.originalIndex !== undefined) {
            // 主流程节点：从初始流程数据中获取
            const originalIndex = node.data.originalIndex
            const processData = mainProcessData[originalIndex]
            if (processData && processData.ID && processData.AgentName && processData.Description) {
              completeTaskProcess.push(processData)
              console.log(`  📦 添加主流程节点: ${nodeId}, 索引: ${originalIndex}`)
            }
          } else if (node.data.isBranchTask) {
            // 分支节点：从对应的分支数据中获取（按索引匹配）
            const parentBranch = branches.find(branch => branch.nodes.some(n => n.id === nodeId))

            if (parentBranch && parentBranch.tasks) {
              // 找到该节点在分支节点列表中的索引
              const nodeIndex = parentBranch.nodes.findIndex(n => n.id === nodeId)
              if (nodeIndex !== -1 && parentBranch.tasks[nodeIndex]) {
                const taskData = parentBranch.tasks[nodeIndex]
                if (taskData.ID && taskData.AgentName && taskData.Description) {
                  completeTaskProcess.push(taskData)
                  console.log(
                    `  📦 添加分支节点: ${nodeId}, 分支: ${parentBranch.branchContent}, 索引: ${nodeIndex}`
                  )
                }
              }
            }
          }
        })

        console.log(`✅ 数据收集完成，总任务数: ${completeTaskProcess.length}`)

        // 🆕 找到当前点击节点所属的分支，用于保存选中状态
        const matchedBranch = branches.find(branch => {
          return branch.nodes.some(node => node.id === nodeId)
        })

        if (matchedBranch) {
          sessionStorage.setItem(LAST_SELECTED_BRANCH_KEY, matchedBranch.id)
          console.log(`💾 保存选中的分支ID: ${matchedBranch.id}`)
        }

        selectionStore.setActiveTaskProcessData(
          currentTask.value.Id,
          currentAgents,
          completeTaskProcess
        )
        agentsStore.setCurrentTaskProcess(completeTaskProcess)
      }
    } else {
      // 如果找不到父节点，只高亮分支节点
      const allBranchNodes = [...branchParentChain, ...branchChildNodes]
      selectedNodeIds.value = new Set(allBranchNodes)
    }
  } else {
    // 🆕 点击的是主流程节点，高亮所有主流程节点（初始流程）
    const mainProcessNodes = nodes.value
      .filter(n => !n.data.isBranchTask && n.id !== 'root')
      .map(n => n.id)

    selectedNodeIds.value = new Set(mainProcessNodes)

    // 🆕 点击主流程节点时，从 store 读取"初始流程"分支的副本
    if (currentTask.value) {
      const taskStepId = currentTask.value.Id
      if (!taskStepId) {
        return
      }
      const currentAgents = currentTask.value.AgentSelection || []
      const branches = selectionStore.getTaskProcessBranches(taskStepId, currentAgents)
      const initialBranch = branches.find(branch => branch.branchContent === '初始流程')

      if (initialBranch && initialBranch.tasks) {
        // 使用 store 中保存的初始流程副本
        selectionStore.setActiveTaskProcessData(taskStepId, currentAgents, initialBranch.tasks)

        // 🆕 同步更新 currentTask.TaskProcess（实现全局数据联动）
        agentsStore.setCurrentTaskProcess(initialBranch.tasks)

        // 🆕 保存选中的分支ID到 sessionStorage
        sessionStorage.setItem(LAST_SELECTED_BRANCH_KEY, initialBranch.id)
      } else {
        // 降级：使用 taskProcess.value
        const originalTaskProcess = taskProcess.value
        selectionStore.setActiveTaskProcessData(taskStepId, currentAgents, originalTaskProcess)

        // 🆕 同步更新 currentTask.TaskProcess（实现全局数据联动）
        agentsStore.setCurrentTaskProcess(originalTaskProcess)
      }
    }
  }
}

// 添加分支
const submitBranch = async () => {
  if (!branchInput.value.trim() || !addingBranchNodeId.value) return

  const parentNodeId = addingBranchNodeId.value
  const branchContent = branchInput.value.trim()

  // 获取父节点
  const parentNode = nodes.value.find((n: Node) => n.id === parentNodeId)
  if (!parentNode) {
    ElMessage.error('找不到父节点')
    return
  }

  // 开始加载
  branchLoading.value = true

  try {
    // ==================== 移动已有分支 ====================
    // 🆕 只移动在当前父节点下方的分支节点（Y坐标 > 父节点Y坐标）
    const parentNodeY = parentNode.position.y

    // 查找所有已有的分支任务节点（标记为 isBranchTask）
    const allExistingBranchNodes = nodes.value.filter((n: Node) => n.data.isBranchTask)

    // 过滤出在父节点下方的分支节点
    const branchesBelowParent = allExistingBranchNodes.filter(
      (node: Node) => node.position.y > parentNodeY
    )

    const branchIdsBelowParent = branchesBelowParent.map((n: Node) => n.id)

    console.log(
      `📍 移动了 ${branchIdsBelowParent.length} 个分支（Y坐标 > ${parentNodeY}），总共 ${allExistingBranchNodes.length} 个分支`
    )

    // 将当前父节点下方的分支向下移动250px（通过创建新节点来触发响应式更新）
    nodes.value = nodes.value.map((node: Node) => {
      if (branchIdsBelowParent.includes(node.id)) {
        return {
          ...node,
          position: {
            ...node.position,
            y: node.position.y + 250
          }
        }
      }
      return node
    })

    // 💾 同步更新 store 中保存的分支位置
    if (currentTask.value?.Id) {
      const taskStepId = currentTask.value.Id
      const currentAgents = currentTask.value.AgentSelection || []
      const savedBranches = selectionStore.getTaskProcessBranches(taskStepId, currentAgents)

      savedBranches.forEach(branch => {
        branch.nodes.forEach(branchNode => {
          if (branchNode.data.isBranchTask && branchIdsBelowParent.includes(branchNode.id)) {
            branchNode.position.y += 250
          }
        })
      })
    }

    // 用于存储新创建的分支节点和边
    const newBranchNodes: Node[] = []
    const newBranchEdges: Edge[] = []

    // 判断是根节点还是 agent 节点
    if (parentNodeId === 'root') {
      // ========== 根节点分支 ==========
      let newAgentActions: IApiAgentAction[] = []

      if (USE_MOCK_DATA) {
        // 使用 Mock API
        const generalGoal = agentsStore.agentRawPlan.data?.['General Goal'] || ''

        // 🆕 根节点分支：从零开始生成完整方案
        // Baseline_Completion = 0 表示没有已完成的部分，需要生成所有阶段
        // Existing_Steps 传空数组，不传递初始流程信息
        const response = await api.mockBranchTaskProcess({
          branch_Number: 1,
          Modification_Requirement: branchContent,
          Existing_Steps: [],  // ← 根节点分支不传递现有步骤
          Baseline_Completion: 0,  // ← 从零开始
          stepTaskExisting: currentTask.value,
          goal: generalGoal
        })

        // 后端返回格式: [[action1, action2], [action3, action4]]
        // 取第一个分支
        if (response && response.length > 0) {
          const firstBranch = response[0]

          // 直接遍历 action 数组
          firstBranch.forEach((action: any) => {
            // 直接使用接口返回的 ActionType
            newAgentActions.push({
              id: action.ID || uuidv4(),
              type: action.ActionType,
              agent: action.AgentName,
              description: action.Description,
              inputs: action.ImportantInput || []
            })
          })
        }

        ElMessage.success('[Mock] 任务流程分支创建成功')
      } else {
        // 调用真实 API
        const generalGoal = agentsStore.agentRawPlan.data?.['General Goal'] || ''

        // 🆕 根节点分支：从零开始生成完整方案
        // Baseline_Completion = 0 表示没有已完成的部分，需要生成所有阶段
        // Existing_Steps 传空数组，不传递初始流程信息
        const response = await api.branchTaskProcess({
          branch_Number: 1,
          Modification_Requirement: branchContent,
          Existing_Steps: [],  // ← 根节点分支不传递现有步骤
          Baseline_Completion: 0,  // ← 从零开始
          stepTaskExisting: currentTask.value,
          goal: generalGoal
        })

        // 后端返回格式: [[action1, action2], [action3, action4]]
        // 取第一个分支
        if (response && response.length > 0) {
          const firstBranch = response[0]

          // 直接遍历 action 数组
          firstBranch.forEach((action: any) => {
            // 直接使用接口返回的 ActionType
            newAgentActions.push({
              id: action.ID || uuidv4(),
              type: action.ActionType,
              agent: action.AgentName,
              description: action.Description,
              inputs: action.ImportantInput || []
            })
          })
        }

        ElMessage.success('任务流程分支创建成功')
      }

      // 创建新的 agent 节点
      if (newAgentActions.length > 0) {
        // 计算分支起始位置：在根节点下方（固定位置）
        const branchStartX = parentNode.position.x
        const branchStartY = parentNode.position.y + 200 // 固定位置：父节点下方200px
        const timestamp = Date.now()
        const agentNodeIds: string[] = []

        // 为每个动作创建一个 agent 节点
        newAgentActions.forEach((action, index) => {
          const agentNodeId = `branch-agent-${parentNodeId}-${timestamp}-${index}`
          agentNodeIds.push(agentNodeId)

          const agentInfo = getAgentMapIcon(action.agent)
          const actionTypeInfo = getActionTypeDisplay(action.type)

          // 从 agentsStore 中获取 agent 的个人简介
          const agentProfile =
            agentsStore.agents.find((agent: any) => agent.Name === action.agent)?.Profile ||
            '暂无个人简介'

          // 计算位置：横向排列
          const nodeX = branchStartX + 100 + index * 120
          const nodeY = branchStartY

          // 创建 agent 节点
          const newAgentNode: Node = {
            id: agentNodeId,
            type: 'agent',
            position: { x: nodeX, y: nodeY },
            data: {
              agentName: action.agent,
              agentIcon: agentInfo.icon,
              agentColor: agentInfo.color,
              actionTypeColor: actionTypeInfo?.color || '#909399',
              agentDescription: action.description || '暂无描述',
              agentProfile: agentProfile,
              actionTypeName: actionTypeInfo?.name || '未知职责',
              actionTypeKey: actionTypeInfo?.key || 'unknown',
              isRoot: false,
              isBranchTask: true // 标记为分支任务
            }
          }

          nodes.value.push(newAgentNode)
          newBranchNodes.push(newAgentNode)

          // 创建连接边
          if (index === 0) {
            // 第一个 agent 连接到父节点（根节点）
            const newEdge: Edge = {
              id: `edge-${parentNodeId}-${agentNodeId}`,
              source: parentNodeId,
              target: agentNodeId,
              sourceHandle: 'bottom',
              targetHandle: 'left',
              type: 'smoothstep',
              animated: true,
              style: { stroke: '#67c23a', strokeWidth: 2, strokeDasharray: '5,5' }
            }
            edges.value.push(newEdge)
            newBranchEdges.push(newEdge)
          } else {
            // 后续 agent 连接到前一个 agent
            const prevAgentNodeId = agentNodeIds[index - 1]
            const newEdge: Edge = {
              id: `edge-${prevAgentNodeId}-${agentNodeId}`,
              source: prevAgentNodeId,
              target: agentNodeId,
              sourceHandle: 'right',
              targetHandle: 'left',
              type: 'smoothstep',
              animated: true,
              style: { stroke: '#67c23a', strokeWidth: 2 }
            }
            edges.value.push(newEdge)
            newBranchEdges.push(newEdge)
          }
        })

        // 📂 保存分支数据到 store
        if (newBranchNodes.length > 0) {
          // 将 IApiAgentAction 转换为 TaskProcess 格式用于存储
          // 与 fill-step-task-mock.ts 中的 TaskProcess 格式保持一致
          const branchTasks = newAgentActions.map(action => ({
            ID: action.id || uuidv4(),
            ActionType: action.type,
            AgentName: action.agent,
            Description: action.description,
            ImportantInput: action.inputs || []
          }))

          // 使用任务过程分支存储
          // 注意：需要对 nodes 和 edges 进行深拷贝，避免保存响应式引用
          const taskStepId = currentTask.value?.Id || ''
          const currentAgents = currentTask.value?.AgentSelection || []
          isSyncing = true // 设置标志，避免 watch 触发重复同步
          selectionStore.addTaskProcessBranch(taskStepId, currentAgents, {
            parentNodeId: parentNodeId,
            branchContent: branchContent,
            branchType: 'root',
            nodes: JSON.parse(JSON.stringify(newBranchNodes)),
            edges: JSON.parse(JSON.stringify(newBranchEdges)),
            tasks: JSON.parse(JSON.stringify(branchTasks))
          })
          setTimeout(() => {
            isSyncing = false
          }, 100)
        }
      }
    } else {
      // ========== Agent 节点分支 ==========
      const parentIsBranchTask = parentNode.data.isBranchTask || false
      const parentOriginalIndex = parentNode.data.originalIndex ?? 0
      let newAgentActions: IApiAgentAction[] = []

      if (USE_MOCK_DATA) {
        // 使用 Mock API
        const generalGoal = agentsStore.agentRawPlan.data?.['General Goal'] || ''
        const currentTaskProcess = taskProcess.value || []

        // 🆕 根据父节点类型构建 existingSteps
        let existingSteps: any[] = []
        let baselineCompletion = 100

        if (!parentIsBranchTask) {
          // 父节点是主流程节点：传递主流程从 0 到父节点的步骤
          baselineCompletion =
            currentTaskProcess.length > 0
              ? Math.round(((parentOriginalIndex + 1) / currentTaskProcess.length) * 100)
              : 100

          existingSteps = currentTaskProcess.slice(0, parentOriginalIndex + 1).map((p: any) => ({
            ID: p.ID,
            ActionType: p.ActionType,
            AgentName: p.AgentName,
            Description: p.Description,
            ImportantInput: p.ImportantInput || []
          }))
        } else {
          // 父节点是分支节点：从分支数据中获取步骤
          const taskStepId = currentTask.value?.Id || ''
          const currentAgents = currentTask.value?.AgentSelection || []
          const branches = selectionStore.getTaskProcessBranches(taskStepId, currentAgents)

          // 找到父节点所属的分支
          const parentBranch = branches.find(branch =>
            branch.nodes.some(n => n.id === parentNode.id)
          )

          if (parentBranch && parentBranch.tasks) {
            // 获取分支中从第一个节点到父节点的所有步骤
            const parentIndexInBranch = parentBranch.nodes.findIndex(n => n.id === parentNode.id)
            existingSteps = parentBranch.tasks.slice(0, parentIndexInBranch + 1).map((p: any) => ({
              ID: p.ID,
              ActionType: p.ActionType,
              AgentName: p.AgentName,
              Description: p.Description,
              ImportantInput: p.ImportantInput || []
            }))

            // 分支节点的基线完成度：根据主流程进度计算
            baselineCompletion =
              currentTaskProcess.length > 0
                ? Math.round(((parentOriginalIndex + 1) / currentTaskProcess.length) * 100)
                : 100
          }
        }

        // 调用 Mock API
        const response = await api.mockBranchTaskProcess({
          branch_Number: 1,
          Modification_Requirement: branchContent,
          Existing_Steps: existingSteps,
          Baseline_Completion: baselineCompletion,
          stepTaskExisting: currentTask.value,
          goal: generalGoal
        })

        // 后端返回格式: [[action1, action2], [action3, action4]]
        // 取第一个分支
        if (response && response.length > 0) {
          const firstBranch = response[0]

          // 直接遍历 action 数组
          firstBranch.forEach((action: any) => {
            // 直接使用接口返回的 ActionType
            newAgentActions.push({
              id: action.ID || uuidv4(),
              type: action.ActionType,
              agent: action.AgentName,
              description: action.Description,
              inputs: action.ImportantInput || []
            })
          })
        }

        ElMessage.success('[Mock] 任务流程分支创建成功')
      } else {
        // 调用真实 API
        const generalGoal = agentsStore.agentRawPlan.data?.['General Goal'] || ''
        const currentTaskProcess = taskProcess.value || []

        // 🆕 根据父节点类型构建 existingSteps
        let existingSteps: any[] = []
        let baselineCompletion = 100

        if (!parentIsBranchTask) {
          // 父节点是主流程节点：传递主流程从 0 到父节点的步骤
          baselineCompletion =
            currentTaskProcess.length > 0
              ? Math.round(((parentOriginalIndex + 1) / currentTaskProcess.length) * 100)
              : 100

          existingSteps = currentTaskProcess.slice(0, parentOriginalIndex + 1).map((p: any) => ({
            ID: p.ID,
            ActionType: p.ActionType,
            AgentName: p.AgentName,
            Description: p.Description,
            ImportantInput: p.ImportantInput || []
          }))
        } else {
          // 父节点是分支节点：从分支数据中获取步骤
          const taskStepId = currentTask.value?.Id || ''
          const currentAgents = currentTask.value?.AgentSelection || []
          const branches = selectionStore.getTaskProcessBranches(taskStepId, currentAgents)

          // 找到父节点所属的分支
          const parentBranch = branches.find(branch =>
            branch.nodes.some(n => n.id === parentNode.id)
          )

          if (parentBranch && parentBranch.tasks) {
            // 获取分支中从第一个节点到父节点的所有步骤
            const parentIndexInBranch = parentBranch.nodes.findIndex(n => n.id === parentNode.id)
            existingSteps = parentBranch.tasks.slice(0, parentIndexInBranch + 1).map((p: any) => ({
              ID: p.ID,
              ActionType: p.ActionType,
              AgentName: p.AgentName,
              Description: p.Description,
              ImportantInput: p.ImportantInput || []
            }))

            // 分支节点的基线完成度：根据主流程进度计算
            baselineCompletion =
              currentTaskProcess.length > 0
                ? Math.round(((parentOriginalIndex + 1) / currentTaskProcess.length) * 100)
                : 100
          }
        }

        const response = await api.branchTaskProcess({
          branch_Number: 1,
          Modification_Requirement: branchContent,
          Existing_Steps: existingSteps,
          Baseline_Completion: baselineCompletion,
          stepTaskExisting: currentTask.value,
          goal: generalGoal
        })

        console.log('branchTaskProcess response:', response)
        // 后端返回格式: [[action1, action2], [action3, action4]]
        // 取第一个分支
        if (response && response.length > 0) {
          const firstBranch = response[0]

          // 直接遍历 action 数组
          firstBranch.forEach((action: any) => {
            // 直接使用接口返回的 ActionType
            newAgentActions.push({
              id: action.ID || uuidv4(),
              type: action.ActionType,
              agent: action.AgentName,
              description: action.Description,
              inputs: action.ImportantInput || []
            })
          })
        }

        ElMessage.success('任务流程分支创建成功')
      }

      // 创建新的 agent 节点
      if (newAgentActions.length > 0) {
        // 计算分支起始位置：在父 agent 节点右下方（固定位置）
        const branchStartX = parentNode.position.x + 150
        const branchStartY = parentNode.position.y + 200 // 固定位置：父节点下方200px
        const timestamp = Date.now()
        const agentNodeIds: string[] = []

        // 为每个动作创建一个 agent 节点
        newAgentActions.forEach((action, index) => {
          const agentNodeId = `branch-agent-${parentNodeId}-${timestamp}-${index}`
          agentNodeIds.push(agentNodeId)

          const agentInfo = getAgentMapIcon(action.agent)
          const actionTypeInfo = getActionTypeDisplay(action.type)

          // 从 agentsStore 中获取 agent 的个人简介
          const agentProfile =
            agentsStore.agents.find((agent: any) => agent.Name === action.agent)?.Profile ||
            '暂无个人简介'

          // 计算位置：横向排列
          const nodeX = branchStartX + index * 120
          const nodeY = branchStartY

          // 创建 agent 节点
          const newAgentNode: Node = {
            id: agentNodeId,
            type: 'agent',
            position: { x: nodeX, y: nodeY },
            data: {
              agentName: action.agent,
              agentIcon: agentInfo.icon,
              agentColor: agentInfo.color,
              actionTypeColor: actionTypeInfo?.color || '#909399',
              agentDescription: action.description || '暂无描述',
              agentProfile: agentProfile,
              actionTypeName: actionTypeInfo?.name || '未知职责',
              actionTypeKey: actionTypeInfo?.key || 'unknown',
              isRoot: false,
              isBranchTask: true // 标记为分支任务
            }
          }

          nodes.value.push(newAgentNode)
          newBranchNodes.push(newAgentNode)

          // 创建连接边
          if (index === 0) {
            // 第一个 agent 连接到父节点
            const newEdge: Edge = {
              id: `edge-${parentNodeId}-${agentNodeId}`,
              source: parentNodeId,
              target: agentNodeId,
              sourceHandle: 'bottom',
              targetHandle: 'left',
              type: 'smoothstep',
              animated: true,
              style: { stroke: '#409eff', strokeWidth: 2, strokeDasharray: '5,5' }
            }
            edges.value.push(newEdge)
            newBranchEdges.push(newEdge)
          } else {
            // 后续 agent 连接到前一个 agent
            const prevAgentNodeId = agentNodeIds[index - 1]
            const newEdge: Edge = {
              id: `edge-${prevAgentNodeId}-${agentNodeId}`,
              source: prevAgentNodeId,
              target: agentNodeId,
              sourceHandle: 'right',
              targetHandle: 'left',
              type: 'smoothstep',
              animated: true,
              style: { stroke: '#409eff', strokeWidth: 2 }
            }
            edges.value.push(newEdge)
            newBranchEdges.push(newEdge)
          }
        })

        // 📂 保存分支数据到 store
        if (newBranchNodes.length > 0) {
          // 将 IApiAgentAction 转换为 TaskProcess 格式用于存储
          // 与 fill-step-task-mock.ts 中的 TaskProcess 格式保持一致
          const branchTasks = newAgentActions.map(action => ({
            ID: action.id || uuidv4(),
            ActionType: action.type,
            AgentName: action.agent,
            Description: action.description,
            ImportantInput: action.inputs || []
          }))

          // 使用任务过程分支存储
          // 注意：需要对 nodes 和 edges 进行深拷贝，避免保存响应式引用
          const taskStepId = currentTask.value?.Id || ''
          const currentAgents = currentTask.value?.AgentSelection || []
          isSyncing = true // 设置标志，避免 watch 触发重复同步
          selectionStore.addTaskProcessBranch(taskStepId, currentAgents, {
            parentNodeId: parentNodeId,
            branchContent: branchContent,
            branchType: 'task',
            nodes: JSON.parse(JSON.stringify(newBranchNodes)),
            edges: JSON.parse(JSON.stringify(newBranchEdges)),
            tasks: JSON.parse(JSON.stringify(branchTasks))
          })
          setTimeout(() => {
            isSyncing = false
          }, 100)
        }
      }
    }

    // 重置当前添加分支的节点 ID
    addingBranchNodeId.value = null
    branchInput.value = ''

    // 适应视图以显示新节点
    nextTick(() => {
      setTimeout(() => {
        fit({ padding: 100, duration: 300 })
      }, 100)
    })
  } catch (error) {
    ElMessage.error('添加分支失败，请重试')
    addingBranchNodeId.value = null
    branchInput.value = ''
  } finally {
    branchLoading.value = false
  }
}

const handleBranchKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    event.preventDefault()
    submitBranch()
  } else if (event.key === 'Escape') {
    cancelAddBranch()
  }
}

onConnect(params => addEdges(params))
</script>

<template>
  <div class="plan-task-container">
    <div v-if="!currentTask || !taskProcess || taskProcess.length === 0" class="empty-state">
      <el-empty description="请选择一个任务过程卡片" />
    </div>

    <div v-else v-loading="branchLoading" class="vue-flow-wrapper">
      <VueFlow
        v-model:nodes="nodes"
        v-model:edges="edges"
        :delete-key-code="null"
        :default-viewport="{ zoom: 0.5, x: 0, y: 0 }"
        :min-zoom="0.5"
        :max-zoom="4"
        @node-click="onNodeClick"
        class="vue-flow-container"
      >
        <!-- <Background /> -->
        <!-- <Controls /> -->

        <template #node-root="nodeProps">
          <div class="root-task-node-wrapper">
            <Handle type="source" :position="Position.Right" id="right" />
            <Handle type="source" :position="Position.Bottom" id="bottom" />

            <!-- 圆形卡片 -->
            <div class="root-node-wrapper">
              <!-- 中央添加/取消按钮 -->
              <div
                v-if="addingBranchNodeId !== 'root'"
                class="root-add-btn"
                @click="startAddBranch('root')"
              >
                <el-icon :size="28" color="#409eff">
                  <CirclePlus />
                </el-icon>
              </div>
              <div v-else class="root-add-btn" @click="cancelAddBranch">
                <el-icon :size="28" color="#f56c6c">
                  <Remove />
                </el-icon>
              </div>
            </div>

            <!-- 外部输入框 -->
            <div v-if="addingBranchNodeId === 'root'" class="external-input-container">
              <el-input
                v-model="branchInput"
                placeholder="输入分支需求..."
                size="small"
                @keydown="handleBranchKeydown"
                ref="branchInputRef"
                class="branch-input"
              >
                <template #suffix>
                  <svg-icon
                    icon-class="paper-plane"
                    size="16px"
                    color="#409eff"
                    class="submit-icon"
                    :class="{ 'is-disabled': !branchInput.trim() }"
                    @click="submitBranch"
                  />
                </template>
              </el-input>
            </div>
          </div>
        </template>

        <template #node-agent="nodeProps">
          <div class="task-node-wrapper">
            <div
              class="agent-node-wrapper"
              :class="{ 'is-branch-selected': selectedNodeIds.has(nodeProps.id) }"
              :style="{ background: nodeProps.data.actionTypeColor }"
            >
              <Handle type="target" :position="Position.Left" id="left" />
              <Handle type="source" :position="Position.Bottom" id="bottom" />
              <el-tooltip
                effect="light"
                placement="bottom"
                :show-after="1000"
                popper-class="agent-tooltip-popper"
              >
                <template #content>
                  <div class="agent-tooltip-content">
                    <div class="agent-tooltip-name">{{ nodeProps.data.agentName }}</div>
                    <div class="agent-tooltip-divider"></div>
                    <div class="agent-tooltip-section">
                      <span class="section-label">职责：</span>
                      <span
                        class="section-value"
                        :style="{ color: nodeProps.data.actionTypeColor }"
                      >
                        {{ nodeProps.data.actionTypeName }}
                      </span>
                    </div>
                    <div class="agent-tooltip-divider"></div>
                    <div class="agent-tooltip-section-title">个人简介</div>
                    <div class="agent-tooltip-profile">{{ nodeProps.data.agentProfile }}</div>
                    <div class="agent-tooltip-divider"></div>
                    <div class="agent-tooltip-section-title">任务描述</div>
                    <div class="agent-tooltip-description">
                      {{ nodeProps.data.agentDescription }}
                    </div>
                  </div>
                </template>
                <div class="agent-avatar" :style="{ background: nodeProps.data.agentColor }">
                  <svg-icon :icon-class="nodeProps.data.agentIcon" size="28px" color="#fff" />
                </div>
              </el-tooltip>
              <Handle type="source" :position="Position.Right" id="right" />
            </div>

            <!-- 底部添加按钮 -->
            <div
              v-if="addingBranchNodeId !== nodeProps.id"
              class="external-add-btn"
              @click="startAddBranch(nodeProps.id)"
            >
              <el-icon :size="20" color="#409eff">
                <CirclePlus />
              </el-icon>
            </div>

            <!-- 取消按钮 -->
            <div v-else class="external-add-btn cancel-btn" @click="cancelAddBranch">
              <el-icon :size="20" color="#f56c6c">
                <Remove />
              </el-icon>
            </div>

            <!-- 外部输入框 -->
            <div v-if="addingBranchNodeId === nodeProps.id" class="external-input-container">
              <el-input
                v-model="branchInput"
                placeholder="输入分支需求..."
                size="small"
                @keydown="handleBranchKeydown"
                ref="branchInputRef"
                class="branch-input"
              >
                <template #suffix>
                  <svg-icon
                    icon-class="paper-plane"
                    size="16px"
                    color="#409eff"
                    class="submit-icon"
                    :class="{ 'is-disabled': !branchInput.trim() }"
                    @click="submitBranch"
                  />
                </template>
              </el-input>
            </div>
          </div>
        </template>
      </VueFlow>
    </div>
  </div>
</template>

<style scoped lang="scss">
.plan-task-container {
  width: 100%;
  height: 100%;
}

.vue-flow-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

.vue-flow-container {
  width: 100%;
  height: 100%;
  background-color: var(--color-bg-three);
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.root-node-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background: var(--color-bg-three);
  border: 2px solid var(--color-border);
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: var(--color-bg-three-hover);
    transform: scale(1.05);
  }
}

// 根节点中央按钮
.root-add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    transform: scale(1.1);
  }

  &:active {
    transform: scale(0.95);
  }
}

// 根节点包装器（用于容纳外部按钮）
.root-task-node-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

// 节点包装器（用于容纳外部按钮）
.task-node-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

// 外部添加按钮
.external-add-btn {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #fff;
  border: 2px solid #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);

  &:hover {
    background: #409eff;
    transform: translateX(-50%) scale(1.1);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

    .el-icon {
      color: #fff;
    }
  }

  &:active {
    transform: translateX(-50%) scale(0.95);
  }

  // 取消按钮样式
  &.cancel-btn {
    border-color: #f56c6c;
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);

    &:hover {
      background: #f56c6c;
      box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
    }
  }
}

// 外部输入容器
.external-input-container {
  position: absolute;
  bottom: -80px;
  left: 50%;
  transform: translateX(-50%);
  width: 260px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  z-index: 100;
  animation: slideDown 0.2s ease-out;

  &::before {
    content: '';
    position: absolute;
    top: -6px;
    left: 50%;
    transform: translateX(-50%) rotate(45deg);
    width: 12px;
    height: 12px;
    background: #fff;
    border-left: 1px solid #dcdfe6;
    border-top: 1px solid #dcdfe6;
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.branch-input {
  width: 100%;

  :deep(.el-input__wrapper) {
    background: transparent;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-shadow: none;

    &:hover {
      border-color: #c0c4cc;
    }

    &.is-focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }

    .el-input__inner {
      font-size: 13px;
      color: var(--color-text-primary);
      padding-right: 40px;
    }
  }
}

// 提交图标样式
.submit-icon {
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;

  &:hover:not(.is-disabled) {
    transform: scale(1.1);
  }

  &:active:not(.is-disabled) {
    transform: scale(0.95);
  }

  &.is-disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }
}

.agent-node-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  width: 60px;
  height: 60px;
  opacity: 0.9;
  transition: all 0.2s ease;

  // 🆕 分支选中高亮样式
  &.is-branch-selected {
    box-shadow: 0 0 0 3px #000, 0 0 20px rgba(0, 0, 0, 0.5);
    z-index: 10;
  }

  .agent-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    transition: transform 0.2s ease;

    &:hover {
      transform: scale(1.1);
    }
  }
}

:deep(.vue-flow__handle) {
  width: 8px;
  height: 8px;
  background: #43a8aa;
  border: 2px solid #fff;
}

:deep(.vue-flow__edge) {
  .vue-flow__edge-path {
    stroke: #43a8aa;
  }
}

:deep(.vue-flow__controls) {
  button {
    background-color: #43a8aa;
    border-color: #43a8aa;

    &:hover {
      background-color: #358d8f;
    }
  }
}

/* 智能体悬浮提示样式 */
:deep(.agent-tooltip-popper) {
  z-index: 4000 !important;
}

.agent-tooltip-content {
  width: 240px;
  max-width: 240px;
}

.agent-tooltip-name {
  font-size: 16px;
  font-weight: bold;
  color: var(--color-text);
  margin-bottom: 4px;
}

.agent-tooltip-divider {
  height: 1px;
  background: #e0e0e0;
  margin: 6px 0;
}

.agent-tooltip-section {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 4px 0;
  font-size: 14px;
}

.section-label {
  font-weight: 500;
  color: var(--color-text);
}

.section-value {
  font-weight: bold;
}

.agent-tooltip-section-title {
  font-size: 13px;
  font-weight: 600;
  color: var(--color-text);
  margin-top: 4px;
  margin-bottom: 2px;
}

.agent-tooltip-profile {
  font-size: 13px;
  color: var(--color-text);
  line-height: 1.4;
  word-break: break-word;
  margin-bottom: 4px;
}

.agent-tooltip-description {
  font-size: 14px;
  color: var(--color-text);
  line-height: 1.5;
  word-break: break-word;
  margin-top: 4px;
}
</style>

<style>
.agent-tooltip-popper {
  z-index: 4000 !important;
}
</style>
