<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="styledEdges"
        :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">
          <TaskNode
            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)"
            :is-deletable="getNodeDeletable(nodeProps.id).isDeletable"
            :branch-id="getNodeDeletable(nodeProps.id).branchId"
            @add-branch="handleAddBranch"
            @start-add-branch="handleStartAddBranch"
            @cancel-add-branch="handleCancelAddBranch"
            @delete-branch="handleDeleteBranch"
            @delete-node="handleDeleteNode"
          />
        </template>
      </VueFlow>

      <!-- 删除分支确认对话框 -->
      <DeleteConfirmDialog
        v-model="deleteDialogVisible"
        title="确认删除该分支 ?"
        content="删除后，该分支无法恢复 !"
        @confirm="confirmDeleteBranch"
      />

      <!-- 删除单个节点确认对话框 -->
      <DeleteConfirmDialog
        v-model="deleteNodeDialogVisible"
        title="确认删除该节点 ?"
        content="删除后，该节点无法恢复 !"
        @confirm="confirmDeleteNode"
      />
    </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 { useNotification } from '@/composables/useNotification'
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 TaskNode from './components/TaskNode.vue'
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'

const agentsStore = useAgentsStore()
const selectionStore = useSelectionStore()
const { progress, updateProgress, removeNotification } = useNotification()

// 获取协作流程数据
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, getNodes, getEdges } = useVueFlow()

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

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

// 带样式的边数据
const styledEdges = computed(() => {
  return edges.value.map(edge => {
    // 根节点永远参与高亮
    const sourceIsRoot = edge.source === 'root-goal'
    const targetIsRoot = edge.target === 'root-goal'
    const sourceSelected = selectedNodeIds.value.has(edge.source) || sourceIsRoot
    const targetSelected = selectedNodeIds.value.has(edge.target) || targetIsRoot
    const isHighlighted = sourceSelected && targetSelected

    return {
      ...edge,
      style: {
        stroke: isHighlighted ? 'var(--color-node-active)' : 'var(--color-node-border)',
        strokeWidth: 2
      },
      markerEnd: {
        type: 'arrow' as any,
        color: isHighlighted ? 'var(--color-node-active)' : 'var(--color-node-border)',
        width: 20,
        height: 20,
        strokeWidth: 2
      },
      animated: isHighlighted,
      class: isHighlighted ? 'edge-highlighted' : 'edge-normal'
    }
  })
})

// 回溯到根节点的路径
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)

    // 查找分支创建方向的后续节点
    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)

// 初始化标记
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
const START_Y = 50

// 初始化流程图
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 },
        markerEnd: {
          type: 'arrow' as any,
          color: '#e6a23c',
          width: 20,
          height: 20,
          strokeWidth: 2
        }
      })
    }

    // 如果不是第一个任务，创建从前一个任务到当前任务的连接
    if (index > 0) {
      // const prevTaskId = collaborationProcess.value[index - 1].Id || `task-${index - 1}`
      const prev = collaborationProcess.value[index - 1]
      const prevTaskId = prev?.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 },
        markerEnd: {
          type: 'arrow' as any,
          color: '#409eff',
          width: 20,
          height: 20,
          strokeWidth: 2
        }
      })
    }
  })

  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')

    // 保存分支数据到数据库
    saveBranchesToDB()
  }

  // 从 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 => {
    if (!newTask) {
      return
    }

    // 找到包含 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)

      // 更新节点数据
      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 existingNode = nodes.value[nodeIndex]!
            const existingData = existingNode?.data || {}
            const updatedNode = {
              ...existingNode,
              data: {
                ...existingData,
                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 existingNode = nodes.value[nodeIndex]!
        const existingData = existingNode?.data || {}
        const updatedNode = {
          ...existingNode,
          data: {
            ...existingData,
            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 handleStartAddBranch = (nodeId: string) => {
  currentAddingBranchNodeId.value = nodeId
}

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

// 判断节点是否可删除（分支从底部出发连接的节点）
const getNodeDeletable = (nodeId: string): { isDeletable: boolean; branchId: string | null } => {
  // 直接从 store 的分支数据里用节点 id 查找它属于哪个分支
  // 获取所有分支数据
  const allBranches = selectionStore.getAllFlowBranches()

  // 遍历所有分支，用节点 id 在 nodes 数组中查找
  for (const branch of allBranches) {
    // 检查该节点是否是该分支的第一个节点
    const firstNode = branch.nodes?.[0]
    if (firstNode && firstNode.id === nodeId) {
      // 只有该分支的第一个节点才显示删除分支按钮
      return {
        isDeletable: true,
        branchId: branch.id || branch.branchContent
      }
    }
  }

  return {
    isDeletable: false,
    branchId: null
  }
}

// 删除分支弹窗相关状态
const deleteDialogVisible = ref(false)
const branchIdToDelete = ref<string | null>(null)

// 删除单个节点弹窗相关状态
const deleteNodeDialogVisible = ref(false)
const nodeIdToDelete = ref<string | null>(null)

// 删除分支（显示确认对话框）
const handleDeleteBranch = (branchId: string) => {
  // 调试信息：输出要删除的分支ID
  const allBranches = selectionStore.getAllFlowBranches()
  const targetBranch = allBranches.find(
    b => b.id === branchId || b.edges.some(e => e.data?.branchId === branchId)
  )
  console.log('[删除分支] 找到的 branchId:', branchId, '分支信息:', targetBranch)

  branchIdToDelete.value = branchId
  deleteDialogVisible.value = true
}

// 确认删除分支
const confirmDeleteBranch = async () => {
  if (!branchIdToDelete.value) return

  const branchId = branchIdToDelete.value

  // 1. 从store中获取该分支的信息
  const allBranches = selectionStore.getAllFlowBranches()
  // 直接使用 branchId 精确匹配分支（而不是通过边的 data.branchId）
  const branchToDelete = allBranches.find(b => b.id === branchId)

  if (!branchToDelete) {
    ElMessage.error('未找到该分支')
    deleteDialogVisible.value = false
    return
  }

  // 2. 从nodes中删除该分支的所有节点（排除根节点）
  const branchNodeIds = branchToDelete.nodes.filter(n => n.id !== 'root-goal').map(n => n.id)

  nodes.value = nodes.value.filter(n => !branchNodeIds.includes(n.id))

  // 3. 从edges中删除该分支的所有边
  const branchEdgeIds = branchToDelete.edges.map(e => e.id)
  edges.value = edges.value.filter(e => !branchEdgeIds.includes(e.id))

  // 4. 从selectionStore中删除该分支
  selectionStore.removeFlowBranch(branchToDelete.id)

  // 5. 保存到数据库
  await saveBranchesToDB()

  // 6. 关闭对话框并清理状态
  deleteDialogVisible.value = false
  branchIdToDelete.value = null

  // 7. 刷新视图
  nextTick(() => {
    fit({ padding: 0.15, duration: 300 })
  })

  ElMessage.success('分支删除成功')
}

// 开始编辑任务
const handleDeleteNode = (nodeId: string) => {
  nodeIdToDelete.value = nodeId
  deleteNodeDialogVisible.value = true
}

const confirmDeleteNode = async () => {
  if (!nodeIdToDelete.value) return

  const nodeId = nodeIdToDelete.value

  // 0. 检查被删除的节点是否是分支的第一个节点（带删除分支按钮）
  const nodeDeletable = getNodeDeletable(nodeId)
  const deletedBranchId = nodeDeletable.isDeletable ? nodeDeletable.branchId : null

  // 1. 找到该节点的入边和出边
  const incomingEdges = edges.value.filter(e => e.target === nodeId)
  const outgoingEdges = edges.value.filter(e => e.source === nodeId)

  // 1.1 保存删除前的子节点信息（用于后续更新 branchId）
  const childNodeIds = outgoingEdges.map(e => e.target)

  // 1.2 提前获取每个子节点所属分支的 branchId（在删除节点之前获取）
  const allBranches = selectionStore.getAllFlowBranches()
  const childBranchIdMap: Record<string, string> = {}
  outgoingEdges.forEach(outEdge => {
    const childBranch = allBranches.find(branch => branch.nodes.some(n => n.id === outEdge.target))
    if (childBranch) {
      childBranchIdMap[outEdge.target] = childBranch.id
    }
  })

  // 2. 将子节点重新连接到父节点（使用固定的 left/right handle）
  // 修复：为每个子节点使用它自己所属分支的 branchId，而不是父节点的 branchId
  const newEdges: Edge[] = []
  outgoingEdges.forEach(outEdge => {
    incomingEdges.forEach(inEdge => {
      // 使用提前获取的子节点所属分支的 branchId
      const targetBranchId = childBranchIdMap[outEdge.target] || inEdge.data?.branchId

      // 创建新边，连接父节点（右侧）到子节点（左侧）
      const newEdge = {
        id: `e-${inEdge.source}-${outEdge.target}-${Date.now()}`,
        source: inEdge.source,
        target: outEdge.target,
        sourceHandle: 'right', // 父节点右侧
        targetHandle: 'left', // 子节点左侧
        type: 'smoothstep',
        animated: true,
        style: outEdge.style,
        markerEnd: outEdge.markerEnd,
        data: { ...inEdge.data, branchId: targetBranchId } // 使用子节点所属分支的 branchId
      }
      edges.value.push(newEdge)
      newEdges.push(newEdge)
    })
  })

  // 3. 删除该节点的入边和出边
  const relatedEdgeIds = [...incomingEdges.map(e => e.id), ...outgoingEdges.map(e => e.id)]
  edges.value = edges.value.filter(e => !relatedEdgeIds.includes(e.id))

  // 4. 删除该节点
  nodes.value = nodes.value.filter(n => n.id !== nodeId)

  // 4.1 如果删除的是分支的第一个节点，需要更新新第一个节点的边信息
  // 修复：每个子节点使用它自己所属分支的 branchId，而不是统一使用被删除节点的 branchId
  if (deletedBranchId && childNodeIds.length > 0) {
    // 遍历所有子节点，更新它们的入边信息
    childNodeIds.forEach(childNodeId => {
      // 找到连接子节点的入边（删除后新创建的边，sourceHandle 应该是 'right'）
      const childIncomingEdge = edges.value.find(
        e => e.target === childNodeId && e.sourceHandle === 'right'
      )
      if (childIncomingEdge) {
        // 使用预先保存的子节点所属分支的 branchId（删除节点之前就保存好了）
        const targetBranchId = childBranchIdMap[childNodeId] || deletedBranchId

        // 更新边的 sourceHandle 为 'bottom' 并添加 branchId，使新节点成为可删除分支的入口
        childIncomingEdge.sourceHandle = 'bottom'
        childIncomingEdge.data = {
          ...childIncomingEdge.data,
          branchId: targetBranchId
        }
        console.log('[删除节点] 已更新新节点的边信息:', childNodeId, targetBranchId)
      }
    })
  }

  // 5. 找到被删除节点所属的分支，并同步更新 store 中的分支数据
  for (const branch of allBranches) {
    const nodeIndex = branch.nodes.findIndex(n => n.id === nodeId)
    if (nodeIndex !== -1) {
      branch.nodes.splice(nodeIndex, 1)
      branch.edges = branch.edges.filter(e => e.source !== nodeId && e.target !== nodeId)
      if (nodeIndex < branch.tasks.length) {
        branch.tasks.splice(nodeIndex, 1)
      }

      // 5.1 如果删除的是分支的第一个节点，需要更新新第一个节点的 branch 信息
      if (deletedBranchId && childNodeIds.length > 0 && nodeIndex === 0) {
        // 更新 store 中分支的 parentNodeId 指向新的第一个节点
        if (branch.nodes.length > 0) {
          branch.parentNodeId = branch.nodes[0]!.id
        }
      }

      // 5.2 将新的边信息更新到 store 中（如果有新创建的边）
      if (newEdges.length > 0) {
        branch.edges.push(...newEdges)
      }

      break
    }
  }

  // 6. 保存到数据库
  await saveBranchesToDB()

  // 7. 关闭对话框并清理状态
  deleteNodeDialogVisible.value = false
  nodeIdToDelete.value = null

  // 8. 刷新视图
  nextTick(() => {
    fit({ padding: 0.15, duration: 300 })
  })

  ElMessage.success('节点删除成功')
}

const handleEditTask = (nodeId: string) => {
  // 更新节点的编辑状态
  updateNode(nodeId, {
    data: {
      ...findNode(nodeId)?.data,
      isEditing: true
    }
  })
}

// 保存任务编辑
const handleSaveTask = async (nodeId: string, newContent: string) => {
  const node = findNode(nodeId)
  if (!node) return

  // 更新节点的 TaskContent
  const updatedData = {
    ...node.data,
    task: {
      ...node.data.task,
      TaskContent: newContent
    },
    isEditing: false
  }

  updateNode(nodeId, { data: updatedData })

  // 找到当前节点所属的分支，同步更新
  const allBranches = selectionStore.getAllFlowBranches()

  for (const branch of allBranches) {
    const branchNode = branch.nodes.find(n => n.id === nodeId)
    if (branchNode) {
      // 找到分支中的对应任务并更新
      const taskIndex = branch.tasks.findIndex(t => t.Id === node.data.task.Id)
      if (taskIndex !== -1) {
        branch.tasks[taskIndex]!.TaskContent = newContent
        console.log('[handleSaveTask] 已更新分支中的任务内容:', {
          branchContent: branch.branchContent,
          taskName: node.data.task.StepName
        })
      }
      break
    }
  }

  // 保存到数据库
  saveBranchesToDB()
}

// 取消编辑任务
const handleCancelEdit = (nodeId: string) => {
  const node = findNode(nodeId)
  if (!node) return

  // 恢复编辑状态
  updateNode(nodeId, {
    data: {
      ...node.data,
      isEditing: false
    }
  })
}

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

  // 查找已有分支节点
  const allExistingBranchNodes = nodes.value.filter(n => n.data.isBranchTask)

  // 移动父节点下方的分支
  const parentNodeY = parentNode.position.y
  const branchesBelowParent = allExistingBranchNodes.filter(node => node.position.y > parentNodeY)

  // 向下移动分支
  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[] = []

      // 调用真实 API
      const generalGoal = agentsStore.agentRawPlan.data?.['General Goal'] || ''
      const initialInput = agentsStore.agentRawPlan.data?.['Initial Input Object'] || []

      //  根节点分支：从零开始生成完整方案
      const response = await api.branchPlanOutline({
        branch_Number: 1,
        Modification_Requirement: branchContent,
        Existing_Steps: [],
        Baseline_Completion: 0,
        initialInputs: Array.isArray(initialInput) ? initialInput : [initialInput],
        goal: generalGoal
      })

      // WebSocket 返回格式: { data: [[{...}]], ... }
      // REST API 返回格式: [[{...}]]
      const responseData = response.data || response
      // 直接获取协作流程数据
      if (Array.isArray(responseData)) {
        // 可能是二维数组
        newTasks = responseData[0] || []
      } else if (responseData && responseData['Collaboration Process']) {
        // 如果返回的是对象，尝试读取 Collaboration Process 字段
        newTasks = responseData['Collaboration Process'] || []
      } else {
        newTasks = []
      }

      // ========== 立即创建节点显示大纲 ==========
      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

          const newTaskNode: Node = {
            id: taskNodeId,
            type: 'task',
            position: { x: taskX, y: taskY },
            data: {
              task,
              isEditing: false,
              editingContent: '',
              isBranchTask: true,
              branchId: String(timestamp),
              updateKey: Date.now()
            }
          }

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

          // 创建连接边
          if (index === 0) {
            const strokeColor = taskId === 'root-goal' ? '#409eff' : '#67c23a'
            const newEdge: Edge = {
              id: `edge-${taskId}-${taskNodeId}`,
              source: taskId,
              target: taskNodeId,
              sourceHandle: 'bottom',
              targetHandle: 'left',
              type: 'smoothstep',
              animated: true,
              style: { stroke: strokeColor, strokeWidth: 2, strokeDasharray: '5,5' },
              markerEnd: {
                type: 'arrow' as any,
                color: strokeColor,
                width: 20,
                height: 20,
                strokeWidth: 2
              },
              data: {
                branchId: String(timestamp)
              }
            }
            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 },
              markerEnd: {
                type: 'arrow' as any,
                color: '#409eff',
                width: 20,
                height: 20,
                strokeWidth: 2
              }
            }
            edges.value.push(newEdge)
            newBranchEdges.push(newEdge)
          }
        })

        // 保存分支到 store（此时只有大纲）
        selectionStore.addFlowBranch({
          parentNodeId: taskId,
          branchContent: branchContent,
          branchType: 'root',
          nodes: newBranchNodes,
          edges: newBranchEdges,
          tasks: JSON.parse(JSON.stringify(newTasks))
        })

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

        // 保存分支数据到数据库
        saveBranchesToDB()

        // 适应视图，让用户先看到大纲
        nextTick(() => {
          setTimeout(() => {
            fit({ padding: 100, duration: 300 })
          }, 100)
        })

        // ========== 关闭遮罩层Loading ==========
        branchLoading.value = false

        // ========== 异步填充详情（后台进行）==========
        const notificationId = progress('正在生成分支任务协作流程...', 0, newTasks.length)

        // 带重试的填充函数
        const fillStepWithRetry = async (
          task: IRawStepTask,
          index: number,
          retryCount = 0
        ): Promise<void> => {
          const maxRetries = 2

          try {
            const filledTask = await api.fillStepTask({
              goal: generalGoal,
              stepTask: task
            })

            // 更新任务的 AgentSelection 和 TaskProcess
            newTasks[index]!.AgentSelection = filledTask.AgentSelection
            newTasks[index]!.TaskProcess = filledTask.TaskProcess
            newTasks[index]!.Collaboration_Brief_frontEnd = filledTask.Collaboration_Brief_frontEnd

            // 更新节点数据
            const taskNodeId = taskNodeIds[index]!
            updateNode(taskNodeId, {
              data: {
                ...findNode(taskNodeId)?.data,
                task: { ...newTasks[index] },
                updateKey: Date.now()
              }
            })

            // 更新进度
            updateProgress(notificationId, index + 1, newTasks.length)
          } catch (error) {
            console.error(
              `填充分支任务 ${task.StepName} 详情失败 (尝试 ${retryCount + 1}/${maxRetries + 1}):`,
              error
            )

            if (retryCount < maxRetries) {
              // 延迟后重试
              await new Promise(resolve => setTimeout(resolve, 1000))
              return fillStepWithRetry(task, index, retryCount + 1)
            } else {
              console.error(`分支任务 ${task.StepName} 在 ${maxRetries + 1} 次尝试后仍然失败`)
            }
          }
        }

        // 串行填充所有任务的详情（避免并发问题导致字段混乱）
        for (let i = 0; i < newTasks.length; i++) {
          await fillStepWithRetry(newTasks[i]!, i)
        }

        // 更新 store 中的任务数据
        const allBranches = selectionStore.getAllFlowBranches()
        const currentBranch = allBranches.find(
          b => b.branchContent === branchContent && b.parentNodeId === taskId
        )
        if (currentBranch) {
          currentBranch.tasks = JSON.parse(JSON.stringify(newTasks))
        }

        // 填充完成后再次保存分支数据到数据库（确保 TaskProcess 等完整数据被保存）
        saveBranchesToDB()

        removeNotification(notificationId)
      }
    } else {
      // ========== 任务节点级别分支 ==========
      let newTasks: IRawStepTask[] = []

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

      // 判断父节点是否是分支节点
      const parentIsBranchTask = parentNode.data.isBranchTask || false

      // 调用真实 API
      const generalGoal = agentsStore.agentRawPlan.data?.['General Goal'] || ''
      const initialInput = agentsStore.agentRawPlan.data?.['Initial Input Object'] || []

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

      if (!parentIsBranchTask) {
        // 父节点是主流程节点：传递主流程从 0 到父节点的步骤
        const parentTaskIndex = collaborationProcess.value.findIndex(
          task => task.StepName === parentNode.data.task.StepName
        )
        const parentIndex = parentTaskIndex >= 0 ? parentTaskIndex : 0

        existingSteps = collaborationProcess.value.slice(0, parentIndex + 1).map(step => ({
          StepName: step.StepName,
          TaskContent: step.TaskContent,
          InputObject_List: step.InputObject_List || [],
          OutputObject: step.OutputObject || ''
        }))

        baselineCompletion =
          collaborationProcess.value.length > 0
            ? Math.round(((parentIndex + 1) / collaborationProcess.value.length) * 100)
            : 0
      } else {
        // 父节点是分支节点：从分支数据中获取步骤
        const branches = selectionStore.getAllFlowBranches()

        // 找到父节点所属的分支
        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(step => ({
            StepName: step.StepName,
            TaskContent: step.TaskContent,
            InputObject_List: step.InputObject_List || [],
            OutputObject: step.OutputObject || ''
          }))

          // 分支节点的基线完成度：根据主流程进度计算
          const parentTaskIndex = collaborationProcess.value.findIndex(
            task => task.StepName === parentNode.data.task.StepName
          )
          const parentIndex = parentTaskIndex >= 0 ? parentTaskIndex : 0
          baselineCompletion =
            collaborationProcess.value.length > 0
              ? Math.round(((parentIndex + 1) / 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
      })
      // WebSocket 返回格式: { data: [[{...}]], ... }
      // REST API 返回格式: [[{...}]]
      const responseData = response.data || response
      // 直接获取协作流程数据
      // newTasks = response?.[0] || []
      if (Array.isArray(responseData)) {
        // 可能是二维数组
        newTasks = responseData[0] || []
      } else if (responseData && responseData['Collaboration Process']) {
        // 如果返回的是对象，尝试读取 Collaboration Process 字段
        newTasks = responseData['Collaboration Process'] || []
      } else {
        newTasks = []
      }

      // ========== 立即创建节点显示大纲 ==========
      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

          // 创建任务节点
          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' },
              markerEnd: {
                type: 'arrow' as any,
                color: '#67c23a',
                width: 20,
                height: 20,
                strokeWidth: 2
              },
              data: {
                branchId: String(timestamp)
              }
            }
            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 },
              markerEnd: {
                type: 'arrow' as any,
                color: '#67c23a',
                width: 20,
                height: 20,
                strokeWidth: 2
              }
            }
            edges.value.push(newEdge)
            newBranchEdges.push(newEdge)
          }
        })

        // 保存分支数据到 store（此时只有大纲）
        selectionStore.addFlowBranch({
          parentNodeId: taskId,
          branchContent: branchContent,
          branchType: 'task',
          nodes: newBranchNodes,
          edges: newBranchEdges,
          tasks: JSON.parse(JSON.stringify(newTasks))
        })

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

        // 保存分支数据到数据库
        saveBranchesToDB()

        // 适应视图，让用户先看到大纲
        nextTick(() => {
          setTimeout(() => {
            fit({ padding: 100, duration: 300 })
          }, 100)
        })

        // ========== 关闭遮罩层Loading ==========
        branchLoading.value = false

        // ========== 异步填充详情（后台进行）==========
        const notificationId = progress('正在生成分支任务协作流程...', 0, newTasks.length)

        // 带重试的填充函数
        const fillStepWithRetry = async (
          task: IRawStepTask,
          index: number,
          retryCount = 0
        ): Promise<void> => {
          const maxRetries = 2

          try {
            const filledTask = await api.fillStepTask({
              goal: generalGoal,
              stepTask: task
            })

            // 更新任务的 AgentSelection 和 TaskProcess
            newTasks[index]!.AgentSelection = filledTask.AgentSelection
            newTasks[index]!.TaskProcess = filledTask.TaskProcess
            newTasks[index]!.Collaboration_Brief_frontEnd = filledTask.Collaboration_Brief_frontEnd

            // 更新节点数据
            const taskNodeId = taskNodeIds[index]!
            updateNode(taskNodeId, {
              data: {
                ...findNode(taskNodeId)?.data,
                task: { ...newTasks[index] },
                updateKey: Date.now()
              }
            })

            // 更新进度
            updateProgress(notificationId, index + 1, newTasks.length)
          } catch (error) {
            console.error(
              `填充分支任务 ${task.StepName} 详情失败 (尝试 ${retryCount + 1}/${maxRetries + 1}):`,
              error
            )

            if (retryCount < maxRetries) {
              // 延迟后重试
              await new Promise(resolve => setTimeout(resolve, 1000))
              return fillStepWithRetry(task, index, retryCount + 1)
            } else {
              console.error(`分支任务 ${task.StepName} 在 ${maxRetries + 1} 次尝试后仍然失败`)
            }
          }
        }

        // 串行填充所有任务的详情（避免并发问题导致字段混乱）
        for (let i = 0; i < newTasks.length; i++) {
          await fillStepWithRetry(newTasks[i]!, i)
        }

        // 更新 store 中的任务数据
        const allBranches = selectionStore.getAllFlowBranches()
        const currentBranch = allBranches.find(
          b => b.branchContent === branchContent && b.parentNodeId === taskId
        )
        if (currentBranch) {
          currentBranch.tasks = JSON.parse(JSON.stringify(newTasks))
        }

        // 填充完成后再次保存分支数据到数据库（确保 TaskProcess 等完整数据被保存）
        saveBranchesToDB()

        removeNotification(notificationId)
      }
    }
  } catch (error) {
    ElMessage.error('添加分支失败，请重试')
  } finally {
    branchLoading.value = false
  }

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

  // 适应视图
  nextTick(() => {
    setTimeout(() => {
      fit({ padding: 100, duration: 300 })
    }, 100)
  })
}

// 保存分支数据到数据库
const saveBranchesToDB = async () => {
  const taskId = (window as any).__CURRENT_TASK_ID__
  if (taskId) {
    try {
      await selectionStore.saveBranchesToDB(taskId)
    } catch (error) {
      console.error('保存分支数据失败:', error)
    }
  } else {
    console.warn('[saveBranchesToDB] 未找到 taskId，跳过保存')
  }
}

// 重置视图
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-settings-panel-content-bg);
}

.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-settings-panel-content-bg);
}

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

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

// 节点连线样式
:deep(.vue-flow__edge-path) {
  stroke: var(--color-node-border);
  stroke-width: 2;
  stroke-dasharray: 5 5;
}

:deep(.vue-flow__edge.edge-highlighted .vue-flow__edge-path) {
  stroke: var(--color-node-active) !important;
  stroke-width: 2;
  stroke-dasharray: 5 5;
}
</style>
