<template>
  <div class="plan-modification">
    <div
      v-loading="agentsStore.agentRawPlan.loading || branchLoading"
      class="flow-wrapper"
      v-if="collaborationProcess.length > 0"
    >
      <VueFlow
        v-model:nodes="nodes"
        v-model:edges="edges"
        :default-zoom="0.5"
        :min-zoom="0.5"
        :delete-key-code="null"
        :max-zoom="2"
        class="flow-container"
        @node-click="onNodeClick"
      >
        <!-- 根节点 -->
        <template #node-root="nodeProps">
          <RootNode
            v-bind="nodeProps"
            :is-adding-branch="currentAddingBranchNodeId === nodeProps.id"
            @add-branch="handleAddBranch"
            @start-add-branch="handleStartAddBranch"
            @cancel-add-branch="handleCancelAddBranch"
          />
        </template>

        <!-- 自定义任务节点 -->
        <template #node-task="nodeProps">
          <TaskNode
            :key="nodeProps.data.updateKey || nodeProps.id"
            v-bind="nodeProps"
            :is-adding-branch="currentAddingBranchNodeId === nodeProps.id"
            :is-branch-selected="selectedNodeIds.has(nodeProps.id)"
            @add-branch="handleAddBranch"
            @start-add-branch="handleStartAddBranch"
            @cancel-add-branch="handleCancelAddBranch"
          />
        </template>
      </VueFlow>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { VueFlow, useVueFlow } from '@vue-flow/core'
import type { Node, Edge } from '@vue-flow/core'
import { useAgentsStore, useSelectionStore, type IRawStepTask } from '@/stores'
import { ElMessage } from 'element-plus'
import api from '@/api'
import { v4 as uuidv4 } from 'uuid'

import '@vue-flow/core/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'
import '@vue-flow/minimap/dist/style.css'
import '@vue-flow/controls/dist/style.css'

// 节点组件
import RootNode from './components/RootNode.vue'
import TaskNode from './components/TaskNode.vue'

const agentsStore = useAgentsStore()
const selectionStore = useSelectionStore()

//  Mock 数据配置
// 开关：控制是否使用 mock 数据（开发时设置为 true，生产时设置为 false）
const USE_MOCK_DATA = false

// 获取协作流程数据
const collaborationProcess = computed(() => {
  return agentsStore.agentRawPlan.data?.['Collaboration Process'] ?? []
})

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

// Vue Flow 实例方法
const { fitView: fit, setTransform, updateNode, findNode } = useVueFlow()

// 编辑状态管理
const editingTasks = ref<Record<string, string>>({})

// 当前正在添加分支的节点 ID
const currentAddingBranchNodeId = ref<string | null>(null)

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

// 获取从目标节点回溯到根节点的路径
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-goal') {
      return currentPath.filter(id => id !== 'root-goal') // 排除根节点
    }

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

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

    for (const edge of incomingEdges) {
      const newPath = [edge.source, ...currentPath]
      queue.push({ nodeId: edge.source, path: newPath })
    }
  }

  return path
}

// 获取分支的所有子节点（只向右遍历，不跨分支）
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-goal' &&
        targetNodeId.startsWith('branch-task-')
      ) {
        toVisit.push(targetNodeId)
      }
    }
  }

  return Array.from(visited)
}

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

  while (currentId && currentId !== 'root-goal') {
    // 查找指向当前节点的边
    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.id.startsWith('branch-task-')) {
      break
    }

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

  return parentChain
}

// 判断节点是否为主流程节点
const isMainProcessNode = (nodeId: string): boolean => {
  return nodeId.startsWith('task-') && !nodeId.startsWith('branch-task-')
}

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

// 初始化标记，避免重复适应视图（使用 sessionStorage 持久化）
const INIT_KEY = 'plan-modification-initialized'
const isInitialized = ref(sessionStorage.getItem(INIT_KEY) === 'true')

//  分支初始化标记
const BRANCHES_INIT_KEY = 'plan-modification-branches-initialized'

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

// 标记是否已经挂载
const isMounted = ref(false)

//  节点尺寸配置
const NODE_WIDTH = 120 // 任务节点宽度
const ROOT_WIDTH = 200 // 根节点宽度
const NODE_GAP = 80 // 节点间距
const START_X = 40 // 起始 X 坐标
const START_Y = 50 // 起始 Y 坐标

// 初始化流程图 - 横向布局（根节点为初始目标，只展示流程卡片）
const initializeFlow = () => {
  const branchesInitialized = sessionStorage.getItem(BRANCHES_INIT_KEY) === 'true'
  const savedBranches = selectionStore.getAllFlowBranches()

  // 如果已经初始化过，只恢复已保存的分支，不重新创建
  if (branchesInitialized && savedBranches.length > 0) {
    const newNodes: Node[] = []
    const newEdges: Edge[] = []

    // 恢复根节点
    const generalGoal = agentsStore.agentRawPlan.data?.['General Goal']
    const initialInput = agentsStore.agentRawPlan.data?.['Initial Input Object']

    if (generalGoal) {
      newNodes.push({
        id: 'root-goal',
        type: 'root',
        position: { x: START_X, y: START_Y - 2 },
        data: {
          goal: generalGoal,
          initialInput: initialInput,
          isRoot: true
        }
      })
    }

    // 恢复所有分支的节点和边
    savedBranches.forEach(branch => {
      branch.nodes.forEach(node => {
        if (node.id === 'root-goal') {
          // 根节点已存在，跳过
          if (!newNodes.find(n => n.id === 'root-goal')) {
            newNodes.push(node)
          }
        } else {
          newNodes.push(node)
        }
      })
      branch.edges.forEach(edge => {
        newEdges.push(edge)
      })
    })

    nodes.value = newNodes
    edges.value = newEdges

    // 恢复最后选中的分支状态
    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 === '初始流程') {
          nodesToHighlight = nodes.value
            .filter(node => isMainProcessNode(node.id))
            .map(node => node.id)
        } else {
          // 其他分支：需要构建完整路径（主流程 + 分支）
          const firstBranchNode = lastSelectedBranch.nodes[0]
          if (firstBranchNode) {
            // 找到连接到该分支的第一个节点的边
            const incomingEdge = newEdges.find(edge => edge.target === firstBranchNode.id)

            if (incomingEdge) {
              const parentNodeId = incomingEdge.source
              // 从父节点回溯到根节点，获取主流程路径
              const mainPathNodes = getPathToRoot(parentNodeId)

              // 合并主流程节点和分支节点
              nodesToHighlight = [
                ...mainPathNodes,
                ...lastSelectedBranch.nodes.map(node => node.id)
              ]
            }
          }
        }

        selectedNodeIds.value = new Set(nodesToHighlight)
      }
    } else {
      const mainProcessNodeIds = nodes.value
        .filter(node => isMainProcessNode(node.id))
        .map(node => node.id)
      selectedNodeIds.value = new Set(mainProcessNodeIds)
    }

    nextTick(() => {
      setTimeout(() => {
        fit({ padding: 0.15, duration: 300 })
      }, 100)
    })

    return
  }

  // 首次初始化：创建完整的流程

  const newNodes: Node[] = []
  const newEdges: Edge[] = []

  // 获取初始目标作为根节点
  const generalGoal = agentsStore.agentRawPlan.data?.['General Goal']
  const initialInput = agentsStore.agentRawPlan.data?.['Initial Input Object']

  // 创建根节点（初始目标）
  if (generalGoal) {
    newNodes.push({
      id: 'root-goal',
      type: 'root',
      position: { x: START_X, y: START_Y - 2 }, // 向下偏移与任务卡片中心对齐
      data: {
        goal: generalGoal,
        initialInput: initialInput,
        isRoot: true
      }
    })
  }

  // 遍历协作流程，创建任务节点
  collaborationProcess.value.forEach((task, index) => {
    const taskId = task.Id || `task-${index}`

    // 计算任务节点位置（横向排列）
    const taskX = START_X + ROOT_WIDTH + NODE_GAP + index * (NODE_WIDTH + NODE_GAP)

    // 创建任务节点
    const taskNode: Node = {
      id: `task-${taskId}`,
      type: 'task',
      position: { x: taskX, y: START_Y },
      data: {
        task,
        isEditing: false,
        editingContent: task.TaskContent || '',
        updateKey: Date.now() // 添加更新时间戳，用于强制组件重新渲染
      }
    }

    newNodes.push(taskNode)

    // 如果是第一个任务，创建从根节点到第一个任务的连接
    if (index === 0 && generalGoal) {
      newEdges.push({
        id: 'edge-root-task',
        source: 'root-goal',
        target: `task-${taskId}`,
        sourceHandle: 'right',
        targetHandle: 'left',
        animated: true,
        type: 'smoothstep',
        style: { stroke: '#e6a23c', strokeWidth: 2 },
        label: ''
      })
    }

    // 如果不是第一个任务，创建从前一个任务到当前任务的连接
    if (index > 0) {
      const prevTaskId = collaborationProcess.value[index - 1].Id || `task-${index - 1}`
      newEdges.push({
        id: `edge-task-${prevTaskId}-${taskId}`,
        source: `task-${prevTaskId}`,
        target: `task-${taskId}`,
        sourceHandle: 'right',
        targetHandle: 'left',
        animated: true,
        type: 'smoothstep',
        style: { stroke: '#409eff', strokeWidth: 2 },
        label: ''
      })
    }
  })

  nodes.value = newNodes
  edges.value = newEdges

  // 🆕 检查是否需要保存初始流程为分支
  // 如果没有任何分支（首次初始化），将初始流程保存为一个分支
  if (savedBranches.length === 0) {
    const initialBranchNodes = newNodes.filter(node => node.id !== 'root-goal')
    const initialBranchEdges = [...newEdges]

    selectionStore.addFlowBranch({
      parentNodeId: 'root',
      branchContent: '初始流程',
      branchType: 'root',
      nodes: initialBranchNodes,
      edges: initialBranchEdges,
      tasks: JSON.parse(JSON.stringify(collaborationProcess.value))
    })

    sessionStorage.setItem(BRANCHES_INIT_KEY, 'true')
  }

  // 后续初始化：从 store 恢复所有分支节点
  if (savedBranches.length > 0) {
    savedBranches.forEach(branch => {
      branch.nodes.forEach(node => {
        if (node.id !== 'root-goal') {
          nodes.value.push(node)
        }
      })
      branch.edges.forEach(edge => {
        edges.value.push(edge)
      })
    })
  }

  const mainProcessNodeIds = nodes.value
    .filter(node => isMainProcessNode(node.id))
    .map(node => node.id)
  selectedNodeIds.value = new Set(mainProcessNodeIds)

  // 只在首次挂载后初始化时适应视图，后续数据变化不适应
  if (isMounted.value && !isInitialized.value) {
    nextTick(() => {
      setTimeout(() => {
        fit({ padding: 0.15, duration: 300 })
        isInitialized.value = true
        sessionStorage.setItem(INIT_KEY, 'true')
      }, 100)
    })
  }
}

// 监听 currentTask 变化，自动高亮对应分支并更新节点数据
watch(
  () => agentsStore.currentTask,
  (newTask, oldTask) => {
    if (!newTask) {
      return
    }

    // 1. 找到包含 currentTask 的分支
    const allBranches = selectionStore.getAllFlowBranches()

    const matchedBranch = allBranches.find(branch => {
      return branch.tasks.some(task => task.Id === newTask.Id)
    })

    if (matchedBranch) {
      const branchNodeIds = matchedBranch.nodes.map(node => node.id)
      selectedNodeIds.value = new Set(branchNodeIds)

      // 更新对应节点的 task 数据（同步 AgentAllocation 中的修改）
      if (newTask.StepName) {
        const matchedNodes = nodes.value.filter(node => {
          return node.data?.task?.StepName === newTask.StepName
        })

        matchedNodes.forEach(node => {
          const newUpdateKey = Date.now()

          updateNode(node.id, {
            data: {
              ...node.data,
              task: { ...newTask },
              updateKey: newUpdateKey
            }
          })

          const nodeIndex = nodes.value.findIndex(n => n.id === node.id)
          if (nodeIndex !== -1) {
            const updatedNode = {
              ...nodes.value[nodeIndex],
              data: {
                ...nodes.value[nodeIndex].data,
                task: { ...newTask },
                updateKey: newUpdateKey
              }
            }
            nodes.value.splice(nodeIndex, 1, updatedNode)
          }
        })
      }
    }
  },
  { deep: true }
)

// 组件挂载后初始化
onMounted(() => {
  isMounted.value = true
  initializeFlow()

  // 主动同步 currentTask 数据到节点（解决组件晚挂载的问题）
  if (agentsStore.currentTask && agentsStore.currentTask.StepName) {
    const matchedNodes = nodes.value.filter(node => {
      return node.data?.task?.StepName === agentsStore.currentTask!.StepName
    })

    matchedNodes.forEach(node => {
      const newUpdateKey = Date.now()
      const nodeIndex = nodes.value.findIndex(n => n.id === node.id)

      if (nodeIndex !== -1) {
        const updatedNode = {
          ...nodes.value[nodeIndex],
          data: {
            ...nodes.value[nodeIndex].data,
            task: { ...agentsStore.currentTask! },
            updateKey: newUpdateKey
          }
        }
        nodes.value.splice(nodeIndex, 1, updatedNode)
      }
    })

    const allBranches = selectionStore.getAllFlowBranches()
    const matchedBranch = allBranches.find(branch => {
      return branch.tasks.some(task => task.Id === agentsStore.currentTask!.Id)
    })

    if (matchedBranch) {
      const branchNodeIds = matchedBranch.nodes.map(node => node.id)
      selectedNodeIds.value = new Set(branchNodeIds)
    }
  }
})

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

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

  // 高亮逻辑
  let nodesToHighlight: string[] = []

  if (isMainProcessNode(nodeId)) {
    // 点击的是主流程节点，高亮所有主流程节点
    nodesToHighlight = nodes.value.filter(node => isMainProcessNode(node.id)).map(node => node.id)

    // 🆕 切换到初始流程分支
    const allBranches = selectionStore.getAllFlowBranches()
    const initialBranch = allBranches.find(branch => branch.branchContent === '初始流程')

    if (initialBranch) {
      // 更新 agentsStore 的数据为初始流程
      agentsStore.setAgentRawPlan({
        data: {
          ...agentsStore.agentRawPlan.data!,
          'Collaboration Process': JSON.parse(JSON.stringify(initialBranch.tasks))
        }
      })

      sessionStorage.setItem(LAST_SELECTED_BRANCH_KEY, initialBranch.id)
    }
  } else {
    const branchParentChain = getBranchParentChain(nodeId)
    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)
      const correctPathToRoot = pathToRoot
      const correctBranchParentChain = [...branchParentChain].reverse()

      nodesToHighlight = [...correctPathToRoot, ...correctBranchParentChain, ...branchChildNodes]

      const allBranches = selectionStore.getAllFlowBranches()

      // 根据分支节点找到对应的分支数据
      const matchedBranch = allBranches.find(branch => {
        // 检查分支的节点是否包含当前点击的节点
        return branch.nodes.some(node => node.id === nodeId)
      })

      if (matchedBranch) {
        // 🆕 按照高亮路径顺序收集每个节点的任务数据
        const fullProcessTasks: IRawStepTask[] = []
        const allBranches = selectionStore.getAllFlowBranches()

        // 遍历所有高亮节点，收集对应的任务数据
        nodesToHighlight.forEach(nodeId => {
          const node = nodes.value.find(n => n.id === nodeId)

          if (!node) return

          // 判断是主流程节点还是分支节点
          if (!node.data.isBranchTask) {
            // 主流程节点：直接从 node.data.task 获取
            if (node.data.task) {
              fullProcessTasks.push(node.data.task)
            }
          } else {
            // 分支节点：从对应的分支数据中获取（按索引匹配）
            const parentBranch = allBranches.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]) {
                fullProcessTasks.push(parentBranch.tasks[nodeIndex])
              }
            }
          }
        })

        // 更新 agentsStore 的数据为完整路径的任务
        agentsStore.setAgentRawPlan({
          data: {
            ...agentsStore.agentRawPlan.data!,
            'Collaboration Process': JSON.parse(JSON.stringify(fullProcessTasks))
          }
        })

        // 🆕 保存最后选中的分支ID
        sessionStorage.setItem(LAST_SELECTED_BRANCH_KEY, matchedBranch.id)
      }
    } else {
      // 如果找不到父节点，只高亮分支节点（父节点链 + 子节点）
      nodesToHighlight = [...branchParentChain, ...branchChildNodes]
    }
  }

  // 更新选中的节点集合
  selectedNodeIds.value = new Set(nodesToHighlight)
}

// 编辑任务
const handleEditTask = (taskId: string) => {
  const node = nodes.value.find(n => n.id === taskId)
  if (node && node.data.task) {
    editingTasks.value[taskId] = node.data.task.TaskContent || ''
    node.data.isEditing = true
  }
}
// 开始添加分支（确保同一时间只有一个输入框）
const handleStartAddBranch = (nodeId: string) => {
  currentAddingBranchNodeId.value = nodeId
}

// 取消添加分支
const handleCancelAddBranch = () => {
  currentAddingBranchNodeId.value = null
}

// 添加分支
const handleAddBranch = async (taskId: string, branchContent: string) => {
  // 获取父节点
  const parentNode = nodes.value.find(n => n.id === taskId)
  if (!parentNode) return

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

  // 🆕 只移动在当前父节点下方的分支节点（Y坐标 > 父节点Y坐标）
  const parentNodeY = parentNode.position.y
  const branchesBelowParent = allExistingBranchNodes.filter(node => node.position.y > parentNodeY)

  // 将当前父节点下方的分支向下移动200px
  branchesBelowParent.forEach(node => {
    node.position.y += 200
  })

  // 开始加载
  branchLoading.value = true

  try {
    // 创建分支节点ID
    const branchId = `branch-${Date.now()}`

    // 计算分支节点位置
    // 根节点分支：向下分叉
    // 任务节点分支：向右下方分叉
    let branchX: number
    let branchY: number

    if (taskId === 'root-goal') {
      // 根节点分支：在根节点下方
      branchX = parentNode.position.x
      branchY = parentNode.position.y + 200
    } else {
      // 任务节点分支：在任务节点右下方
      branchX = parentNode.position.x + 200
      branchY = parentNode.position.y + 150
    }

    // 判断是根节点还是任务节点
    if (taskId === 'root-goal') {
      // ========== 根节点级别分支 ==========
      let newTasks: IRawStepTask[] = []

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

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

        // 提取现有步骤名称
        const existingSteps = collaborationProcess.value
          .map(step => step.StepName)
          .filter(Boolean) as string[]

        // 计算基线完成度
        const baselineCompletion =
          collaborationProcess.value.length > 0
            ? Math.round(
                (collaborationProcess.value.length / collaborationProcess.value.length) * 100
              )
            : 0

        // 调用 Mock API
        const response = await api.mockBranchPlanOutline({
          branch_Number: 1,
          Modification_Requirement: branchContent,
          Existing_Steps: existingSteps,
          Baseline_Completion: baselineCompletion,
          initialInputs: Array.isArray(initialInput) ? initialInput : [initialInput],
          goal: generalGoal
        })

        // 从响应中获取协作流程数据
        newTasks = response['Collaboration Process'] || []

        // ========== 填充每个任务的 TaskProcess ==========
        for (let i = 0; i < newTasks.length; i++) {
          const task = newTasks[i]
          if (!task) continue

          try {
            const filledTask = await api.mockFillStepTask({
              goal: generalGoal,
              stepTask: task
            })
            // 更新任务的 AgentSelection 和 TaskProcess
            newTasks[i]!.AgentSelection = filledTask.AgentSelection
            newTasks[i]!.TaskProcess = filledTask.TaskProcess
            newTasks[i]!.Collaboration_Brief_frontEnd = filledTask.Collaboration_Brief_frontEnd
          } catch (error) {
            console.error(error)
          }
        }

        ElMessage.success('任务大纲分支创建成功')
      } else {
        // 调用真实 API
        const generalGoal = agentsStore.agentRawPlan.data?.['General Goal'] || ''
        const initialInput = agentsStore.agentRawPlan.data?.['Initial Input Object'] || []

        // 提取现有步骤名称
        const existingSteps = collaborationProcess.value
          .map(step => step.StepName)
          .filter(Boolean) as string[]

        // 计算基线完成度
        const baselineCompletion =
          collaborationProcess.value.length > 0
            ? Math.round(
                (collaborationProcess.value.length / collaborationProcess.value.length) * 100
              )
            : 0

        const response = await api.branchPlanOutline({
          branch_Number: 1,
          Modification_Requirement: branchContent,
          Existing_Steps: existingSteps,
          Baseline_Completion: baselineCompletion,
          initialInputs: Array.isArray(initialInput) ? initialInput : [initialInput],
          goal: generalGoal
        })

        // 直接获取协作流程数据（API 返回二维数组 [[task1, task2, ...]]，取第一个分支）
        newTasks = response?.[0] || []

        // 调试日志：验证数据提取

        // ========== 填充每个任务的 TaskProcess ==========
        for (let i = 0; i < newTasks.length; i++) {
          const task = newTasks[i]
          if (!task) continue

          try {
            const filledTask = await api.fillStepTask({
              goal: generalGoal,
              stepTask: task
            })
            // 更新任务的 AgentSelection 和 TaskProcess
            newTasks[i]!.AgentSelection = filledTask.AgentSelection
            newTasks[i]!.TaskProcess = filledTask.TaskProcess
            newTasks[i]!.Collaboration_Brief_frontEnd = filledTask.Collaboration_Brief_frontEnd
          } catch (error) {
            console.error(error)
          }
        }

        ElMessage.success('任务大纲分支创建成功')
      }

      // 创建多个任务节点，每个任务显示为单独的流程卡片
      if (newTasks.length > 0) {
        // 分支任务与主流程任务对齐：从第一个主流程任务的位置开始
        const branchBaseX = START_X + ROOT_WIDTH + NODE_GAP
        const branchBaseY = START_Y + 300 // 向下偏移，与主流程垂直排列
        const timestamp = Date.now()
        const taskNodeIds: string[] = []

        // 为每个任务创建节点
        newTasks.forEach((task, index) => {
          const taskNodeId = `branch-task-${taskId}-${timestamp}-${index}`
          taskNodeIds.push(taskNodeId)

          // 计算位置：横向排列，与主流程任务对齐
          const taskX = branchBaseX + index * (NODE_WIDTH + NODE_GAP)
          const taskY = branchBaseY

          // 创建任务节点（只显示 StepName）
          const newTaskNode: Node = {
            id: taskNodeId,
            type: 'task',
            position: { x: taskX, y: taskY },
            data: {
              task,
              isEditing: false,
              editingContent: '',
              isBranchTask: true, // 标记为分支任务，可用于特殊样式
              branchId: String(timestamp), // 添加分支ID，用于识别和分组
              updateKey: Date.now() // 添加更新时间戳，用于强制组件重新渲染
            }
          }

          nodes.value.push(newTaskNode)
          newBranchNodes.push(newTaskNode)

          // 创建连接边
          if (index === 0) {
            // 第一个任务连接到父节点（从根节点底部到第一个任务左边）
            const newEdge: Edge = {
              id: `edge-${taskId}-${taskNodeId}`,
              source: taskId,
              target: taskNodeId,
              sourceHandle: 'bottom',
              targetHandle: 'left',
              type: 'smoothstep',
              animated: true,
              style: { stroke: '#409eff', strokeWidth: 2, strokeDasharray: '5,5' },
              label: ''
            }
            edges.value.push(newEdge)
            newBranchEdges.push(newEdge)
          } else {
            // 后续任务连接到前一个任务（左右连接）
            const prevTaskNodeId = taskNodeIds[index - 1]
            const newEdge: Edge = {
              id: `edge-${prevTaskNodeId}-${taskNodeId}`,
              source: prevTaskNodeId,
              target: taskNodeId,
              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) {
        selectionStore.addFlowBranch({
          parentNodeId: taskId,
          branchContent: branchContent,
          branchType: 'root',
          nodes: newBranchNodes,
          edges: newBranchEdges,
          tasks: JSON.parse(JSON.stringify(newTasks))
        })
      }
    } else {
      // ========== 任务节点级别分支 ==========
      let newTasks: IRawStepTask[] = []

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

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

        // 提取现有步骤名称
        const existingSteps = collaborationProcess.value
          .map(step => step.StepName)
          .filter(Boolean) as string[]

        // 计算基线完成度
        const baselineCompletion =
          collaborationProcess.value.length > 0
            ? Math.round(
                (collaborationProcess.value.length / collaborationProcess.value.length) * 100
              )
            : 0

        // 调用 Mock API
        const response = await api.mockBranchPlanOutline({
          branch_Number: 1,
          Modification_Requirement: branchContent,
          Existing_Steps: existingSteps,
          Baseline_Completion: baselineCompletion,
          initialInputs: Array.isArray(initialInput) ? initialInput : [initialInput],
          goal: generalGoal
        })

        // 从响应中获取协作流程数据
        newTasks = response['Collaboration Process'] || []

        // ========== 填充每个任务的 TaskProcess ==========
        for (let i = 0; i < newTasks.length; i++) {
          const task = newTasks[i]
          if (!task) continue

          try {
            const filledTask = await api.mockFillStepTask({
              goal: generalGoal,
              stepTask: task
            })
            // 更新任务的 AgentSelection 和 TaskProcess
            newTasks[i]!.AgentSelection = filledTask.AgentSelection
            newTasks[i]!.TaskProcess = filledTask.TaskProcess
            newTasks[i]!.Collaboration_Brief_frontEnd = filledTask.Collaboration_Brief_frontEnd
          } catch (error) {
            console.error(error)
          }
        }

        ElMessage.success('任务大纲分支创建成功')
      } else {
        // 调用真实 API
        const generalGoal = agentsStore.agentRawPlan.data?.['General Goal'] || ''
        const initialInput = agentsStore.agentRawPlan.data?.['Initial Input Object'] || []

        // 提取现有步骤名称
        const existingSteps = collaborationProcess.value
          .map(step => step.StepName)
          .filter(Boolean) as string[]

        // 计算基线完成度
        const baselineCompletion =
          collaborationProcess.value.length > 0
            ? Math.round(
                (collaborationProcess.value.length / collaborationProcess.value.length) * 100
              )
            : 0

        const response = await api.branchPlanOutline({
          branch_Number: 1,
          Modification_Requirement: branchContent,
          Existing_Steps: existingSteps,
          Baseline_Completion: baselineCompletion,
          initialInputs: Array.isArray(initialInput) ? initialInput : [initialInput],
          goal: generalGoal
        })

        // 直接获取协作流程数据（API 返回二维数组 [[task1, task2, ...]]，取第一个分支）
        newTasks = response?.[0] || []

        // 调试日志：验证数据提取

        // ========== 填充每个任务的 TaskProcess ==========
        for (let i = 0; i < newTasks.length; i++) {
          const task = newTasks[i]
          if (!task) continue

          try {
            const filledTask = await api.fillStepTask({
              goal: generalGoal,
              stepTask: task
            })
            // 更新任务的 AgentSelection 和 TaskProcess
            newTasks[i]!.AgentSelection = filledTask.AgentSelection
            newTasks[i]!.TaskProcess = filledTask.TaskProcess
            newTasks[i]!.Collaboration_Brief_frontEnd = filledTask.Collaboration_Brief_frontEnd
          } catch (error) {
            console.error(error)
          }
        }

        ElMessage.success('任务大纲分支创建成功')
      }

      // 创建多个任务节点，每个任务显示为单独的流程卡片
      if (newTasks.length > 0) {
        // 计算分支起始位置：在父任务节点的右下方
        const branchBaseX = parentNode.position.x + NODE_WIDTH + NODE_GAP
        const branchBaseY = parentNode.position.y + 300 // 向下偏移，增加距离避免重叠
        const timestamp = Date.now()
        const taskNodeIds: string[] = []

        // 为每个任务创建节点
        newTasks.forEach((task, index) => {
          const taskNodeId = `branch-task-${taskId}-${timestamp}-${index}`
          taskNodeIds.push(taskNodeId)

          // 计算位置：横向排列
          const taskX = branchBaseX + index * (NODE_WIDTH + NODE_GAP)
          const taskY = branchBaseY

          // 创建任务节点（只显示 StepName）
          const newTaskNode: Node = {
            id: taskNodeId,
            type: 'task',
            position: { x: taskX, y: taskY },
            data: {
              task,
              isEditing: false,
              editingContent: '',
              isBranchTask: true, // 标记为分支任务，可用于特殊样式
              updateKey: Date.now() // 添加更新时间戳，用于强制组件重新渲染
            }
          }

          nodes.value.push(newTaskNode)
          newBranchNodes.push(newTaskNode)

          // 创建连接边
          if (index === 0) {
            // 第一个任务连接到父节点（从父任务底部到第一个分支任务左边）
            const newEdge: Edge = {
              id: `edge-${taskId}-${taskNodeId}`,
              source: taskId,
              target: taskNodeId,
              sourceHandle: 'bottom',
              targetHandle: 'left',
              type: 'smoothstep',
              animated: true,
              style: { stroke: '#67c23a', strokeWidth: 2, strokeDasharray: '5,5' },
              label: ''
            }
            edges.value.push(newEdge)
            newBranchEdges.push(newEdge)
          } else {
            // 后续任务连接到前一个任务（左右连接）
            const prevTaskNodeId = taskNodeIds[index - 1]
            const newEdge: Edge = {
              id: `edge-${prevTaskNodeId}-${taskNodeId}`,
              source: prevTaskNodeId,
              target: taskNodeId,
              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) {
        selectionStore.addFlowBranch({
          parentNodeId: taskId,
          branchContent: branchContent,
          branchType: 'task',
          nodes: newBranchNodes,
          edges: newBranchEdges,
          tasks: JSON.parse(JSON.stringify(newTasks))
        })
      }
    }

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

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

// 删除分支
const handleDeleteBranch = (branchId: string) => {
  // 删除分支节点
  nodes.value = nodes.value.filter(n => n.id !== branchId)

  // 删除相关的边
  edges.value = edges.value.filter(e => e.source !== branchId && e.target !== branchId)
}

// 重置视图
const resetView = () => {
  setTransform({ x: 0, y: 0, zoom: 0.5 })
}

// 重置初始化状态并重新适应视图
const refitView = () => {
  isInitialized.value = false
  sessionStorage.removeItem(INIT_KEY)
  nextTick(() => {
    setTimeout(() => {
      fit({ padding: 50, duration: 300 })
      isInitialized.value = true
      sessionStorage.setItem(INIT_KEY, 'true')
    }, 100)
  })
}

// 暴露方法给父组件
defineExpose({
  initializeFlow,
  resetView,
  refitView
})
</script>

<style scoped lang="scss">
.plan-modification {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--color-bg-detail);
}

.plan-modification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: var(--color-card-bg);
  border-bottom: 1px solid var(--color-border);
  h3 {
    margin: 0;
    font-size: 18px;
    color: var(--color-text-title-header);
    font-weight: bold;
  }
  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.flow-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
}

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

// Vue Flow 节点样式
:deep(.vue-flow__node) {
  border-radius: 8px;
}

:deep(.vue-flow__edge-path) {
  stroke-width: 2;
}

:deep(.vue-flow__edge.selected .vue-flow__edge-path) {
  stroke: #409eff;
}
</style>
