<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { useAgentsStore, useSelectionStore } from '@/stores'
import { convertToTaskProcess } from '@/stores/modules/agents'
import { getAgentMapIcon } from '@/layout/components/config'
import SvgIcon from '@/components/SvgIcon/index.vue'
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
import api from '@/api'
const agentsStore = useAgentsStore()
const selectionStore = useSelectionStore()
const agentsHeatmapData = ref<AgentHeatmapData[]>([])
const selectedAgents = ref<Set<string>>(new Set())
const selectedAssignmentGroup = ref<string[]>([])
const selectedDimensions = ref<Set<string>>(new Set())

// 获取当前选中的任务
const currentTask = computed(() => {
  return agentsStore.currentTask
})

// 当前任务的agents列表
const currentTaskAgents = computed(() => {
  return currentTask.value?.AgentSelection || []
})

// 所有agent列表
const allAgents = computed(() => {
  return agentsStore.agents
})

// 从接口返回的数据中获取评分维度（动态）
const scoreDimensions = ref<string[]>([])

// Agent热力图数据类型
interface AgentHeatmapData {
  agentName: string
  scores: number[] // 各维度的评分
  scoreDetails?: Array<{ dimension: string; score: number; reason: string }> // 详细信息
}

// 确认的agent组合列表 - 从 store 读取
const confirmedAgentGroups = computed(() => {
  const taskId = currentTask.value?.Id
  if (!taskId) return []
  return agentsStore.getConfirmedAgentGroups(taskId)
})

// 任务大纲列表 - 从 agentRawPlan 获取
const taskOutlineList = computed(() => {
  const collaborationProcess = agentsStore.agentRawPlan.data?.['Collaboration Process'] || []
  return collaborationProcess
})

// 选中的任务大纲项
const selectedTaskOutline = ref<string>('')

// 监听 currentTask 变化，自动选中当前步骤
watch(
  () => currentTask.value?.StepName,
  newStepName => {
    if (newStepName) {
      selectedTaskOutline.value = newStepName
    }
  },
  { immediate: true }
)

// 判断任务大纲项是否被选中
const isTaskOutlineSelected = (task: { StepName?: string }) => {
  return selectedTaskOutline.value === task.StepName
}

// 选择任务大纲项
const selectTaskOutline = (task: { StepName?: string; Id?: string }) => {
  if (task.StepName) {
    selectedTaskOutline.value = task.StepName
    // 切换到对应的任务
    if (task.Id) {
      const foundTask = taskOutlineList.value.find(t => t.Id === task.Id)
      if (foundTask) {
        agentsStore.setCurrentTask(foundTask)
      }
    }
  }
}

// 搜索框的值
const searchValue = ref('')
// 是否显示新增维度输入框
const showDimensionInput = ref(false)

// 切换新增维度输入框显示
const toggleDimensionInput = () => {
  showDimensionInput.value = !showDimensionInput.value
}

// 标志位：防止重复初始化
const isInitializing = ref(false)
const isAddingDimension = ref(false)
const isLoadingConfirm = ref(false) // 确认 agent 组合时的加载状态
const isLoadingSelectGroup = ref(false) // 选择已保存组合时的加载状态

// 热力图排序：选中的 agent 排在前面，其他按平均分降序
const sortHeatmapBySelection = () => {
  if (agentsHeatmapData.value.length === 0) return
  agentsHeatmapData.value.sort((a, b) => {
    const aIsSelected = selectedAgents.value.has(a.agentName)
    const bIsSelected = selectedAgents.value.has(b.agentName)

    // 如果一个是选中的 agent，另一个不是，选中的 agent 排前面
    if (aIsSelected && !bIsSelected) return -1
    if (!aIsSelected && bIsSelected) return 1

    // 如果都是或都不是选中的 agent，按选中的维度平均分降序排列
    const selectedDimArray = Array.from(selectedDimensions.value)
    const aAverage = calculateAgentAverage(a, selectedDimArray)
    const bAverage = calculateAgentAverage(b, selectedDimArray)
    return bAverage - aAverage
  })
}
// 处理搜索提交
const handleSubmit = async () => {
  if (!searchValue.value.trim() || isAddingDimension.value) return

  const newDimension = searchValue.value.trim()
  // 检查维度是否已存在
  if (scoreDimensions.value.includes(newDimension)) {
    searchValue.value = ''
    return
  }
  try {
    isAddingDimension.value = true

    // 获取大任务ID和小任务信息
    const dbTaskId = (window as any).__CURRENT_TASK_ID__
    const stepTask = currentTask.value
      ? {
          Id: currentTask.value.Id,
          StepName: currentTask.value.StepName,
          TaskContent: currentTask.value.TaskContent,
          InputObject_List: currentTask.value.InputObject_List,
          OutputObject: currentTask.value.OutputObject
        }
      : undefined

    const response = await api.agentSelectModifyAddAspect({
      aspectList: [...scoreDimensions.value, newDimension],
      stepTask: stepTask,
      TaskID: dbTaskId
    })

    scoreDimensions.value.push(response.aspectName)

    // 为每个agent添加新维度的评分（立即显示）
    agentsHeatmapData.value.forEach(agentData => {
      const scoreInfo = response.agentScores[agentData.agentName]
      if (scoreInfo) {
        agentData.scores.push(scoreInfo.score)
        agentData.scoreDetails?.push({
          dimension: response.aspectName,
          score: scoreInfo.score,
          reason: scoreInfo.reason
        })
      }
    })
    //异步更新 store（等前端显示完成后再更新，避免触发重新初始化）
    await nextTick()
    // 使用 Id 作为 key
    const taskId = currentTask.value?.Id

    //更新按任务Id的存储
    if (taskId) {
      const existingTaskData = agentsStore.getTaskScoreData(taskId)
      if (existingTaskData) {
        // 检查维度是否已存在
        if (!existingTaskData.aspectList.includes(response.aspectName)) {
          existingTaskData.aspectList.push(response.aspectName)
        }
        // 更新评分数据
        for (const [agentName, scoreInfo] of Object.entries(response.agentScores)) {
          if (!existingTaskData.agentScores[agentName]) {
            existingTaskData.agentScores[agentName] = {}
          }
          existingTaskData.agentScores[agentName][response.aspectName] = scoreInfo
        }
        // 保存到 store
        agentsStore.setTaskScoreData(taskId, existingTaskData)
      }
    }

    // 兼容旧版本：更新全局存储
    const currentStoreData = agentsStore.IAgentSelectModifyAddRequest
    if (currentStoreData && currentStoreData.aspectList) {
      if (!currentStoreData.aspectList.includes(response.aspectName)) {
        currentStoreData.aspectList.push(response.aspectName)
      }
      for (const [agentName, scoreInfo] of Object.entries(response.agentScores)) {
        if (!currentStoreData.agentScores[agentName]) {
          currentStoreData.agentScores[agentName] = {}
        }
        currentStoreData.agentScores[agentName][response.aspectName] = scoreInfo
      }
    }

    // 清空输入框并隐藏
    searchValue.value = ''
    showDimensionInput.value = false
  } catch (error) {
    console.error('添加新维度失败:', error)
  } finally {
    isAddingDimension.value = false
  }
}

// 判断两个agent组合是否相同
const areAgentGroupsEqual = (group1: string[], group2: string[]): boolean => {
  if (group1.length !== group2.length) return false
  const sorted1 = [...group1].sort()
  const sorted2 = [...group2].sort()
  return sorted1.every((agent, index) => agent === sorted2[index])
}

// 确认选中的agent组合
const confirmAgentSelection = async () => {
  if (selectedAgents.value.size > 0 && currentTask.value?.Id) {
    const agentArray = Array.from(selectedAgents.value)
    // 检查该agent组合是否已存在（统一检查，包括初始组合和用户添加的组合）
    const existingGroups = agentsStore.getConfirmedAgentGroups(currentTask.value.Id)
    const existingDuplicateIndex = existingGroups.findIndex(group =>
      areAgentGroupsEqual(agentArray, group)
    )

    if (existingDuplicateIndex !== -1) {
      const existingGroup = existingGroups[existingDuplicateIndex]!
      selectedAssignmentGroup.value = [...existingGroup]
      selectedAgents.value = new Set(existingGroup)
      return
    }

    // 获取大任务ID
    const dbTaskId = (window as any).__CURRENT_TASK_ID__

    // 添加到内存 store
    agentsStore.addConfirmedAgentGroup(currentTask.value.Id, agentArray)

    // 🆕 保存 confirmed_groups 到数据库
    if (dbTaskId && currentTask.value.Id) {
      try {
        const updatedGroups = agentsStore.getConfirmedAgentGroups(currentTask.value.Id)
        await api.updateAssignedAgents({
          task_id: dbTaskId,
          step_id: currentTask.value.Id,
          agents: agentArray,
          confirmed_groups: updatedGroups
        })
      } catch (error) {
        console.error('❌ 保存 confirmed_groups 失败:', error)
      }
    }

    try {
      isLoadingConfirm.value = true
      const stepTaskForApi = agentsStore.createStepTaskForApi(agentArray)
      const goal = agentsStore.agentRawPlan.data?.['General Goal'] || '开发智能协作系统'

      if (agentsStore.isStopping || agentsStore.hasStoppedFilling) {
        isLoadingConfirm.value = false
        return
      }

      const filledTask = await api.fillStepTaskTaskProcess({
        goal,
        stepTask: stepTaskForApi,
        agents: agentArray,
        TaskID: dbTaskId
      })
      selectionStore.setAgentTaskProcess(currentTask.value.Id, agentArray, filledTask)
    } catch (error) {
      console.error('❌ API 调用失败:', error)
    } finally {
      isLoadingConfirm.value = false
    }
  }
}

// 点击 Assignment 部分的 agent 组合卡片，更新 Comparison 部分的选中状态
const selectAgentGroup = async (agentNames: string[]) => {
  selectedAssignmentGroup.value = [...agentNames]
  selectedAgents.value = new Set(agentNames)
  selectedAgents.value = new Set(selectedAgents.value)

  // 保存到 store
  if (currentTask.value?.Id) {
    agentsStore.setSelectedAgentGroup(currentTask.value.Id, agentNames)
  }

  // 更新 currentTask 的 AgentSelection 和 TaskProcess
  if (currentTask.value?.Id && agentNames.length > 0) {
    let taskProcessData = selectionStore.getAgentTaskProcess(currentTask.value.Id, agentNames)

    // 如果 store 中没有数据，调用 API 生成
    if (!taskProcessData) {
      try {
        isLoadingSelectGroup.value = true
        const stepTaskForApi = agentsStore.createStepTaskForApi(agentNames)
        const goal = agentsStore.agentRawPlan.data?.['General Goal'] || '开发智能协作系统'

        if (agentsStore.isStopping || agentsStore.hasStoppedFilling) {
          return
        }

        const filledTask = await api.fillStepTaskTaskProcess({
          goal,
          stepTask: stepTaskForApi,
          agents: agentNames,
          TaskID: (window as any).__CURRENT_TASK_ID__
        })

        // 🆕 先存储到 store，确保 getAgentCombinations 能获取到
        // 注意：需要转换为后端期望的格式 { process, brief }
        const groupKey = selectionStore.getAgentGroupKey(agentNames)
        selectionStore.setAgentTaskProcess(currentTask.value.Id, agentNames, {
          process: filledTask.process || [],
          brief: filledTask.brief || {}
        })
        taskProcessData = filledTask
      } catch (error) {
        console.error('❌ 加载 TaskProcess 数据失败:', error)
        return
      } finally {
        isLoadingSelectGroup.value = false
      }
    }

    if (taskProcessData) {
      const convertedTaskProcess = convertToTaskProcess(taskProcessData.process || [])

      // 🆕 获取所有 agent combinations（包含新存储的数据）
      // getAgentCombinations 现在使用 stepId 作为第一层 key
      const agentCombinations = selectionStore.getAgentCombinations(currentTask.value.Id)

      await agentsStore.updateCurrentAgentSelection(
        [...agentNames],
        convertedTaskProcess,
        taskProcessData.brief || currentTask.value.Collaboration_Brief_frontEnd,
        agentCombinations
      )
    }

    sortHeatmapBySelection()
  }
}
// 切换维度选中状态
const toggleDimensionSelection = (dimension: string) => {
  if (selectedDimensions.value.has(dimension)) {
    selectedDimensions.value.delete(dimension)
  } else {
    selectedDimensions.value.add(dimension)
  }
  selectedDimensions.value = new Set(selectedDimensions.value)
  sortHeatmapBySelection()
}

// 判断维度是否被选中
const isDimensionSelected = (dimension: string) => {
  return selectedDimensions.value.has(dimension)
}

// 切换agent选中状态
const toggleAgentSelection = (agentName: string) => {
  if (selectedAgents.value.has(agentName)) {
    selectedAgents.value.delete(agentName)
  } else {
    selectedAgents.value.add(agentName)
  }
  selectedAgents.value = new Set(selectedAgents.value)
  sortHeatmapBySelection()
}

// 判断agent组合是否被选中（用于Assignment卡片的选中效果）
const isAgentGroupSelected = (agentNames: string[]) => {
  // 如果选中的agent数量与该组合的agent数量不同，则未选中
  if (selectedAssignmentGroup.value.length !== agentNames.length) {
    return false
  }
  // 检查该组合的所有agent是否都在selectedAssignmentGroup中
  return agentNames.every(agentName => selectedAssignmentGroup.value.includes(agentName))
}

// 切换显示模式：头像或名称
const showMode = ref<'avatar' | 'name'>('avatar')

// 切换显示模式
const toggleShowMode = () => {
  showMode.value = showMode.value === 'avatar' ? 'name' : 'avatar'
}

// 获取选中agent的索引范围（竖向增长 = 选中多个agent时，虚线框从上往下延伸）
const getSelectedAgentIndexes = () => {
  const indexes: number[] = []
  agentsHeatmapData.value.forEach((agentData, index) => {
    if (selectedAgents.value.has(agentData.agentName)) {
      indexes.push(index)
    }
  })
  return indexes.sort((a, b) => a - b)
}

// 计算虚线框的样式（竖向增长：Y轴方向延伸）
const getSelectionBoxStyle = () => {
  const indexes = getSelectedAgentIndexes()
  if (indexes.length === 0) {
    return {}
  }

  const firstIndex: number = indexes[0] ?? 0
  const lastIndex: number = indexes[indexes.length - 1] ?? 0

  // X轴是维度（水平），Y轴是agent（垂直）
  // 选中框在Y轴方向延伸（竖向增长），只选中第一列（agent头像/名称列）
  const rowHeight = 40 // 每个agent行的高度
  const headerHeight = 40 // 表头高度
  const boxPadding = 4
  const agentLabelWidth = 80 // agent名称/头像列宽度

  return {
    left: '0px', // 从第一列开始
    top: `${headerHeight + firstIndex * rowHeight}px`,
    width: `${agentLabelWidth}px`, // 只覆盖第一列（agent名称/头像列）
    height: `${(lastIndex - firstIndex + 1) * rowHeight}px`,
    padding: `${boxPadding}px`
  }
}

// 计算agent的平均分
// 如果有选中的维度，使用选中的维度；否则使用所有维度
const calculateAgentAverage = (agentData: AgentHeatmapData, selectedDimensions?: string[]) => {
  const dimensionsToUse =
    selectedDimensions && selectedDimensions.length > 0 ? selectedDimensions : scoreDimensions.value

  if (dimensionsToUse.length === 0) return 0

  let total = 0
  let count = 0

  dimensionsToUse.forEach(dimension => {
    const dimensionIndex = scoreDimensions.value.indexOf(dimension)
    if (dimensionIndex !== -1 && agentData.scores[dimensionIndex] !== undefined) {
      total += agentData.scores[dimensionIndex]
      count++
    }
  })

  return count > 0 ? total / count : 0
}

// API调用 - 获取智能体评分数据
const fetchAgentScores = async () => {
  // 使用 Id 作为 key
  const taskId = currentTask.value?.Id
  if (!taskId) {
    return null
  }
  //先检查 store 中是否有该任务的评分数据
  const storedData = agentsStore.getTaskScoreData(taskId)
  if (storedData && storedData.aspectList && storedData.aspectList.length > 0) {
    return storedData
  }

  // 如果正在预加载中，等待预加载完成
  if (agentsStore.isTaskPreloading(taskId)) {
    // 等待一小段时间，让预加载完成
    await new Promise(resolve => setTimeout(resolve, 1000))
    // 再次尝试获取
    const cachedAfterPreload = agentsStore.getTaskScoreData(taskId)
    if (cachedAfterPreload) {
      return cachedAfterPreload
    }
  }

  // 检查是否已停止
  if (agentsStore.isStopping || agentsStore.hasStoppedFilling) {
    return null
  }

  // 调用 API 获取评分（如果没有缓存或预加载）
  const dbTaskId = (window as any).__CURRENT_TASK_ID__
  const agentScores = await api.agentSelectModifyInit({
    goal: agentsStore.agentRawPlan.data?.['General Goal'] || '',
    stepTask: currentTask.value,
    TaskID: dbTaskId
  })

  // 再次检查是否已停止（API 调用后）
  if (agentsStore.isStopping || agentsStore.hasStoppedFilling) {
    return null
  }

  // 从转换后的数据中提取维度列表（第一个agent的所有维度）
  const firstAgent = Object.keys(agentScores)[0]
  const aspectList = firstAgent ? Object.keys(agentScores[firstAgent] || {}) : []

  // 🆕 保存到 store（按 Id 存储）
  agentsStore.setTaskScoreData(taskId, {
    aspectList,
    agentScores
  })

  return {
    aspectList,
    agentScores
  }
}

// 初始化热力矩阵数据 - 使用接口返回的数据
const initHeatmapData = async () => {
  const agents = allAgents.value
  if (agents.length === 0 || isInitializing.value || isAddingDimension.value) return
  isInitializing.value = true
  // 先创建一个只包含agent基本信息的临时数据，让agent头像先显示
  const tempData = agents.map(agent => ({
    agentName: agent.Name,
    scores: [] as number[],
    scoreDetails: []
  }))

  // 按照排序逻辑排序：Assignment的agent在前，其他按名称排序
  tempData.sort((a, b) => {
    const aIsAssigned = currentTaskAgents.value.includes(a.agentName)
    const bIsAssigned = currentTaskAgents.value.includes(b.agentName)
    if (aIsAssigned && !bIsAssigned) return -1
    if (!aIsAssigned && bIsAssigned) return 1
    return a.agentName.localeCompare(b.agentName, 'zh-CN')
  })
  agentsHeatmapData.value = tempData
  //默认选中Assignment部分的agent（即currentTaskAgents）
  if (currentTaskAgents.value.length > 0) {
    selectedAgents.value = new Set(currentTaskAgents.value)
    selectedAssignmentGroup.value = [...currentTaskAgents.value]
  } else if (tempData.length >= 3) {
    // 如果没有Assignment的agent，默认选中前三个
    const defaultAgents = tempData.slice(0, 3).map(d => d.agentName)
    selectedAgents.value = new Set(defaultAgents)
    selectedAssignmentGroup.value = defaultAgents
  }

  try {
    // 获取接口数据
    const scoreData = await fetchAgentScores()
    if (!scoreData) {
      return
    }

    const { aspectList, agentScores } = scoreData

    scoreDimensions.value = aspectList
    const heatmapData = agents.map(agent => {
      const agentName = agent.Name
      const scores: number[] = []
      const scoreDetails: Array<{ dimension: string; score: number; reason: string }> = []

      // 按照维度顺序获取评分
      aspectList.forEach((dimension: string) => {
        const agentScoreData = agentScores[agentName]
        const scoreItem = agentScoreData ? agentScoreData[dimension] : null

        if (scoreItem) {
          scores.push(scoreItem.score)
          scoreDetails.push({
            dimension,
            score: scoreItem.score,
            reason: scoreItem.reason
          })
        } else {
          scores.push(1)
        }
      })

      return {
        agentName,
        scores,
        scoreDetails
      }
    })
    // 排序逻辑：
    // 1. Assignment部分的agent排在前面
    // 2. 其他agent按照平均分降序排列
    // 3. 同一组内也按平均分降序排列
    heatmapData.sort((a, b) => {
      const aIsAssigned = currentTaskAgents.value.includes(a.agentName)
      const bIsAssigned = currentTaskAgents.value.includes(b.agentName)

      // 如果一个是Assignment的agent，另一个不是，Assignment的agent排前面
      if (aIsAssigned && !bIsAssigned) return -1
      if (!aIsAssigned && bIsAssigned) return 1

      // 如果都是或都不是Assignment的agent，按选中的维度平均分降序排列
      const selectedDimArray = Array.from(selectedDimensions.value)
      const aAverage = calculateAgentAverage(a, selectedDimArray)
      const bAverage = calculateAgentAverage(b, selectedDimArray)
      return bAverage - aAverage
    })

    // 设置热力图数据（包含评分）
    agentsHeatmapData.value = heatmapData
  } catch (error) {
    console.error('获取智能体评分数据失败:', error)
  } finally {
    isInitializing.value = false
  }
}

//监听agent列表变化或任务切换，初始化热力矩阵
watch(
  [() => allAgents.value.length, () => currentTask.value?.Id],
  ([agentLength, taskId]) => {
    if (agentLength > 0 && taskId) {
      initHeatmapData()
    }
  },
  { immediate: true }
)

// 监听Assignment部分的agent变化，重新排序和更新选中状态
watch(
  () => currentTaskAgents.value,
  newAgents => {
    if (agentsHeatmapData.value.length > 0) {
      // 重新排序
      agentsHeatmapData.value.sort((a, b) => {
        const aIsAssigned = newAgents.includes(a.agentName)
        const bIsAssigned = newAgents.includes(b.agentName)

        if (aIsAssigned && !bIsAssigned) return -1
        if (!aIsAssigned && bIsAssigned) return 1

        // 按选中的维度平均分降序排列
        const selectedDimArray = Array.from(selectedDimensions.value)
        const aAverage = calculateAgentAverage(a, selectedDimArray)
        const bAverage = calculateAgentAverage(b, selectedDimArray)
        return bAverage - aAverage
      })

      // 更新选中状态
      if (newAgents.length > 0) {
        selectedAgents.value = new Set(newAgents)
        selectedAssignmentGroup.value = [...newAgents]
      } else if (agentsHeatmapData.value.length >= 3) {
        const defaultAgents = agentsHeatmapData.value.slice(0, 3).map(d => d.agentName)
        selectedAgents.value = new Set(defaultAgents)
        selectedAssignmentGroup.value = defaultAgents
      } else {
        selectedAgents.value = new Set()
        selectedAssignmentGroup.value = []
      }
    }
  },
  { deep: true }
)

// 初始化和任务切换处理
watch(
  () => currentTask.value,
  async newTask => {
    if (!newTask?.Id || !newTask.AgentSelection || newTask.AgentSelection.length === 0) {
      return
    }

    // 检查是否已经添加过初始组合
    const existingGroups = agentsStore.getConfirmedAgentGroups(newTask.Id)
    const hasInitialGroup = existingGroups.length > 0

    // 首次初始化：自动添加初始组合到 confirmedAgentGroups
    if (!hasInitialGroup) {
      agentsStore.addConfirmedAgentGroup(newTask.Id, [...newTask.AgentSelection])

      // 初始化时 TaskProcess 一定存在，直接存储
      selectionStore.setAgentTaskProcess(newTask.Id, newTask.AgentSelection, {
        name: newTask.StepName || '',
        content: newTask.TaskContent || '',
        inputs: newTask.InputObject_List || [],
        output: newTask.OutputObject || '',
        agents: newTask.AgentSelection,
        brief: newTask.Collaboration_Brief_frontEnd || { template: '', data: {} },
        process: newTask.TaskProcess.map(action => ({
          id: action.ID,
          type: action.ActionType,
          agent: action.AgentName,
          description: action.Description,
          inputs: action.ImportantInput
        }))
      })
    }

    // 从 store 中恢复之前选择的 agent 组合
    const savedAgentGroup = agentsStore.getSelectedAgentGroup(newTask.Id)
    if (savedAgentGroup) {
      selectedAssignmentGroup.value = [...savedAgentGroup]
      selectedAgents.value = new Set(savedAgentGroup)
    } else {
      // 没有保存的选择，默认选中初始组合
      const allGroups = agentsStore.getConfirmedAgentGroups(newTask.Id)
      if (allGroups.length > 0 && allGroups[0]) {
        selectedAssignmentGroup.value = [...allGroups[0]]
        selectedAgents.value = new Set(allGroups[0])
      }
    }
  },
  { immediate: true } // 立即执行一次
)
// 获取热力图颜色（评分1-5，颜色从浅到深）
const getHeatmapColor = (score: number) => {
  const colors = [
    '#C8D9FC', // 1分 - 最浅
    '#9CB7F0', // 2分
    '#6C8ED7', // 3分
    '#4A71C7', // 4分
    '#1D59DC' // 5分 - 最深
  ]
  return colors[score - 1] || colors[0]
}

// 删除维度弹窗相关状态
const deleteDialogVisible = ref(false)
const dimensionToDelete = ref<string | null>(null)

// 删除分组弹窗相关状态
const groupToDelete = ref<{ index: number; agents: string[] } | null>(null)

// 删除维度（显示确认对话框）
const handleDeleteDimension = (dimension: string, event: Event) => {
  event.stopPropagation() // 阻止冒泡，避免触发维度选择
  dimensionToDelete.value = dimension
  deleteDialogVisible.value = true
}

// 删除分组（显示确认对话框）
const handleDeleteGroup = (groupIndex: number, agents: string[], event: Event) => {
  event.stopPropagation() // 阻止冒泡，避免触发分组选择
  groupToDelete.value = { index: groupIndex, agents }
  deleteDialogVisible.value = true
}

// 确认删除维度
const confirmDeleteDimension = async () => {
  if (!dimensionToDelete.value) return

  const dimension = dimensionToDelete.value

  // 先获取要删除的维度索引（在修改数据之前）
  const dimensionIndex = scoreDimensions.value.indexOf(dimension)
  if (dimensionIndex === -1) {
    // 维度不存在，不需要删除
    return
  }

  // 从 scoreDimensions 中移除该维度
  scoreDimensions.value.splice(dimensionIndex, 1)

  // 从每个 agent 的评分数据中移除该维度（使用之前保存的索引）
  agentsHeatmapData.value.forEach(agentData => {
    if (agentData.scores.length > dimensionIndex) {
      agentData.scores.splice(dimensionIndex, 1)
    }
    if (agentData.scoreDetails && agentData.scoreDetails.length > dimensionIndex) {
      agentData.scoreDetails.splice(dimensionIndex, 1)
    }
  })

  // 同步更新 store 中的数据
  const taskId = currentTask.value?.Id
  if (taskId) {
    const existingTaskData = agentsStore.getTaskScoreData(taskId)
    if (existingTaskData) {
      // 从 aspectList 中移除该维度
      const storeAspectIndex = existingTaskData.aspectList.indexOf(dimension)
      if (storeAspectIndex > -1) {
        existingTaskData.aspectList.splice(storeAspectIndex, 1)
      }
      // 从每个 agent 的评分中移除该维度
      for (const agentName in existingTaskData.agentScores) {
        if (existingTaskData.agentScores[agentName]?.[dimension]) {
          delete existingTaskData.agentScores[agentName][dimension]
        }
      }
      // 保存到 store
      agentsStore.setTaskScoreData(taskId, existingTaskData)
    }
  }

  // 兼容旧版本：更新全局存储
  const currentStoreData = agentsStore.IAgentSelectModifyAddRequest
  if (currentStoreData && currentStoreData.aspectList) {
    const globalAspectIndex = currentStoreData.aspectList.indexOf(dimension)
    if (globalAspectIndex > -1) {
      currentStoreData.aspectList.splice(globalAspectIndex, 1)
    }
    for (const agentName in currentStoreData.agentScores) {
      if (currentStoreData.agentScores[agentName]?.[dimension]) {
        delete currentStoreData.agentScores[agentName][dimension]
      }
    }
  }

  // 同步删除数据库中的维度数据
  const dbTaskId = (window as any).__CURRENT_TASK_ID__
  const stepTaskId = currentTask.value?.Id
  if (dbTaskId && stepTaskId) {
    try {
      // 同时传入大任务ID和步骤ID，只删除当前步骤的该维度
      await api.agentSelectModifyDeleteAspect(dbTaskId, dimension, stepTaskId)
      console.log(
        `[confirmDeleteDimension] 已同步删除数据库中的维度: ${dimension}, step_id: ${stepTaskId}`
      )
    } catch (error) {
      console.error('同步删除数据库维度失败:', error)
    }
  }
}

// 确认删除分组
const confirmDeleteGroup = async () => {
  if (!groupToDelete.value || !currentTask.value?.Id) return

  const { index, agents: deletedAgents } = groupToDelete.value
  const taskId = currentTask.value.Id

  // 从 store 中删除分组
  agentsStore.removeConfirmedAgentGroup(taskId, index)

  // 从 selectionStore 中删除对应的 TaskProcess 数据
  selectionStore.removeAgentTaskProcess(taskId, deletedAgents)

  // 同步到数据库
  const dbTaskId = (window as any).__CURRENT_TASK_ID__
  if (dbTaskId && taskId) {
    try {
      const updatedGroups = agentsStore.getConfirmedAgentGroups(taskId)
      // 获取更新后的所有组合的 TaskProcess 数据
      const agentCombinations: Record<string, { process: any; brief: any }> = {}
      updatedGroups.forEach(group => {
        const processData = selectionStore.getAgentTaskProcess(taskId, group)
        if (processData) {
          const groupKey = selectionStore.getAgentGroupKey(group)
          agentCombinations[groupKey] = {
            process: processData.process || [],
            brief: processData.brief || {}
          }
        }
      })
      await api.updateAssignedAgents({
        task_id: dbTaskId,
        step_id: taskId,
        agents: [],
        confirmed_groups: updatedGroups,
        agent_combinations: agentCombinations
      })
    } catch (error) {
      console.error('❌ 保存删除后的 confirmed_groups 失败:', error)
    }
  }

  // 如果删除的分组是当前选中的分组，清除选中状态
  if (isAgentGroupSelected(groupToDelete.value.agents)) {
    selectedAssignmentGroup.value = []
    selectedAgents.value = new Set()
  }
}

// 统一确认删除处理
const handleConfirmDelete = async () => {
  if (dimensionToDelete.value) {
    await confirmDeleteDimension()
  } else if (groupToDelete.value) {
    await confirmDeleteGroup()
  }
  // 关闭对话框并清理状态
  deleteDialogVisible.value = false
  dimensionToDelete.value = null
  groupToDelete.value = null
}
</script>

<template>
  <div class="agent-allocation-container">
    <!-- 最左侧区域 - 任务大纲流程 -->
    <div class="allocation-task-outline">
      <div class="section-card">
        <div class="section-title">任务大纲-流程</div>
        <div class="task-outline-list">
          <div
            v-for="(task, index) in taskOutlineList"
            :key="index"
            class="task-outline-item"
            :class="{ 'is-selected': isTaskOutlineSelected(task) }"
            :title="task.StepName"
            @click="selectTaskOutline(task)"
          >
            <span class="task-name">{{ task.StepName }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 左侧缝隙 - 1% -->
    <div class="allocation-gap"></div>

    <!-- 左侧区域 - 智能体 -->
    <div class="allocation-left">
      <div class="section-card" v-loading="isLoadingSelectGroup">
        <div class="section-title">分配</div>
        <!-- 所有 agent 组合卡片（包括初始组合和用户创建的组合） -->
        <div
          v-for="(group, groupIndex) in confirmedAgentGroups"
          :key="groupIndex"
          class="agent-group"
        >
          <!-- 分组标题（包裹列表） -->
          <div class="agent-group-title">
            <div class="agent-group-header" @click="selectAgentGroup(group)">
              <span class="agent-group-title-text"> 分组 {{ groupIndex + 1 }} </span>
              <svg-icon
                class="agent-group-delete"
                icon-class="close"
                size="14px"
                color="var(--color-text-secondary)"
                @click="handleDeleteGroup(groupIndex, group, $event)"
              />
            </div>
            <!-- 智能体列表 -->
            <div
              class="agent-list-content"
              :class="{ 'agent-list-selected': isAgentGroupSelected(group) }"
              @click="selectAgentGroup(group)"
            >
              <div v-for="agent in group" :key="agent" class="agent-item">
                <el-tooltip
                  effect="light"
                  placement="top"
                  :teleported="false"
                  :show-after="500"
                  popper-class="agent-allocation-tooltip-popper"
                >
                  <template #content>
                    <div class="agent-tooltip">
                      <div class="agent-tooltip-name">{{ agent }}</div>
                      <div class="agent-tooltip-separator"></div>
                      <div class="agent-tooltip-description">
                        {{ agentsStore.agents.find(a => a.Name === agent)?.Profile || '暂无描述' }}
                      </div>
                    </div>
                  </template>
                  <div class="agent-info">
                    <div class="agent-icon" :style="{ background: getAgentMapIcon(agent).color }">
                      <svg-icon
                        :icon-class="getAgentMapIcon(agent).icon"
                        color="#fff"
                        size="16px"
                      />
                    </div>
                    <span class="agent-name">{{ agent }}</span>
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间缝隙 - 1% -->
    <div class="allocation-gap"></div>

    <!-- 右侧区域 - 79% -->
    <div class="allocation-right">
      <div class="section-card">
        <div class="section-title">智能体</div>
        <div
          v-if="allAgents.length > 0"
          class="comparison-content"
          v-loading="isInitializing || isLoadingConfirm"
        >
          <!-- 热力矩阵图 + 触发器列包装容器 -->
          <div v-if="agentsHeatmapData.length > 0" class="heatmap-wrapper">
            <div class="heatmap-container">
              <!-- 虚线选择框 - 包裹选中的agent评分（竖向增长） -->
              <div
                v-if="selectedAgents.size > 0"
                class="selection-box"
                :style="getSelectionBoxStyle()"
              >
                <!-- 确定按钮 - 位于选中框底部居中 -->
                <div
                  class="confirm-button"
                  :class="{ 'is-loading': isLoadingConfirm }"
                  @click="confirmAgentSelection"
                >
                  <svg-icon icon-class="Check" color="#328621" size="12px" />
                </div>
              </div>
              <!-- 第一行：维度名称（X轴） -->
              <div class="heatmap-dimension-header">
                <!-- 第一个单元格：显示模式切换 "名称|头像" -->
                <div class="heatmap-corner">
                  <span :class="{ 'is-active': showMode === 'name' }" @click="showMode = 'name'"
                    >名称</span
                  >
                  <span class="separator">|</span>
                  <span :class="{ 'is-active': showMode === 'avatar' }" @click="showMode = 'avatar'"
                    >头像</span
                  >
                </div>
                <!-- 其他单元格：维度名称 -->
                <div
                  v-for="(dimension, index) in scoreDimensions"
                  :key="dimension"
                  class="dimension-header-cell"
                  :class="{
                    'is-selected': isDimensionSelected(dimension),
                    'is-odd': (index + 1) % 2 === 1,
                    'is-even': (index + 1) % 2 === 0
                  }"
                  :title="dimension"
                  @click="toggleDimensionSelection(dimension)"
                >
                  <span class="dimension-name">{{ dimension }}</span>
                  <div
                    class="dimension-delete-btn"
                    title="删除维度"
                    @click="handleDeleteDimension(dimension, $event)"
                  >
                    <svg-icon icon-class="close" size="10px" />
                  </div>
                </div>
              </div>

              <!-- 按agent行组织数据（Y轴） -->
              <div
                v-for="(agentData, agentIndex) in agentsHeatmapData"
                :key="agentData.agentName"
                class="heatmap-agent-row"
                :class="{
                  'is-odd-row': (agentIndex + 1) % 2 === 1,
                  'is-even-row': (agentIndex + 1) % 2 === 0
                }"
              >
                <!-- 第一列：agent头像/名称 -->
                <div
                  class="agent-label-cell"
                  :class="{
                    'is-odd-row': (agentIndex + 1) % 2 === 1,
                    'is-even-row': (agentIndex + 1) % 2 === 0
                  }"
                >
                  <el-tooltip
                    effect="light"
                    placement="top"
                    :teleported="false"
                    :show-after="500"
                    popper-class="agent-allocation-tooltip-popper"
                  >
                    <template #content>
                      <div class="agent-tooltip">
                        <div class="agent-tooltip-name">{{ agentData.agentName }}</div>
                        <div class="agent-tooltip-separator"></div>
                        <div class="agent-tooltip-description">
                          {{
                            agentsStore.agents.find(a => a.Name === agentData.agentName)?.Profile ||
                            '暂无描述'
                          }}
                        </div>
                      </div>
                    </template>
                    <div
                      class="agent-label-content"
                      @click="toggleAgentSelection(agentData.agentName)"
                    >
                      <!-- 显示头像模式 -->
                      <template v-if="showMode === 'avatar'">
                        <div
                          class="agent-avatar"
                          :style="{ background: getAgentMapIcon(agentData.agentName).color }"
                        >
                          <svg-icon
                            :icon-class="getAgentMapIcon(agentData.agentName).icon"
                            color="#fff"
                            size="16px"
                          />
                        </div>
                      </template>
                      <!-- 显示名称模式 -->
                      <template v-else>
                        <div
                          class="agent-name-display"
                          :title="
                            (agentsStore.agents.find(a => a.Name === agentData.agentName)
                              ?.Classification || '未知') +
                            ' - ' +
                            agentData.agentName
                          "
                        >
                          {{ agentData.agentName }}
                        </div>
                      </template>
                    </div>
                  </el-tooltip>
                </div>

                <!-- 该agent在各维度的评分 -->
                <div
                  v-for="(score, dimensionIndex) in agentData.scores"
                  :key="dimensionIndex"
                  class="heatmap-cell-wrapper"
                >
                  <el-tooltip
                    effect="light"
                    placement="top"
                    :teleported="false"
                    :show-after="500"
                    popper-class="agent-allocation-tooltip-popper"
                  >
                    <template #content>
                      <div class="score-tooltip">
                        <div class="score-tooltip-reason">
                          评分原因：{{
                            agentData.scoreDetails?.[dimensionIndex]?.reason ||
                            '该智能体在此维度表现良好'
                          }}
                        </div>
                      </div>
                    </template>
                    <div
                      class="heatmap-cell"
                      :style="{
                        backgroundColor: getHeatmapColor(score),
                        color: '#000'
                      }"
                      @click="toggleAgentSelection(agentData.agentName)"
                    >
                      {{ score }}
                    </div>
                  </el-tooltip>
                </div>
              </div>
            </div>

            <!-- 新增维度触发器列 - 放在heatmap-container外部 -->
            <div class="add-dimension-trigger-column" @click="toggleDimensionInput">
              <svg-icon icon-class="plus" size="14px" />

              <!-- 输入框区域 - 相对于触发器列定位 -->
              <div
                v-if="showDimensionInput"
                class="external-input-container"
                v-loading="isAddingDimension"
                @click.stop
              >
                <div class="branch-input-container">
                  <el-input
                    v-model="searchValue"
                    placeholder="请输入新维度"
                    size="small"
                    class="branch-input"
                    @keydown.enter="searchValue && handleSubmit()"
                  />
                  <span
                    class="submit-icon"
                    :class="{ 'is-disabled': !searchValue.trim() }"
                    @click="searchValue && handleSubmit()"
                  >
                    <svg-icon icon-class="paper-plane" size="14px" color="#fff" />
                  </span>
                </div>
              </div>
            </div>
          </div>
          <!-- heatmap-wrapper -->
        </div>
        <div v-else class="placeholder-text">暂无智能体</div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <DeleteConfirmDialog
      v-model="deleteDialogVisible"
      :title="groupToDelete ? '确认删除该分组 ?' : '确认删除该维度 ?'"
      :content="
        groupToDelete
          ? '删除后，该分组的智能体数据将无法恢复 !'
          : '删除后，该维度的评分数据将无法恢复 !'
      "
      @confirm="handleConfirmDelete"
    />
  </div>
</template>

<style scoped lang="scss">
.agent-allocation-container {
  display: flex;
  width: 100%;
  min-height: 100%;
  gap: 0;

  // 最左侧区域 - 任务大纲流程 - 18%
  .allocation-task-outline {
    width: 18%;
    min-height: 100%;
    padding-left: 8px;
    padding-top: 8px;
    padding-bottom: 8px;
    box-sizing: border-box;
  }

  // 缝隙 - 1%
  .allocation-gap {
    width: 1%;
    min-height: 100%;
  }

  // 左侧区域 - 智能体 - 15%
  .allocation-left {
    width: 15%;
    min-height: 100%;
    padding-top: 8px;
    padding-bottom: 8px;
    box-sizing: border-box;
  }

  // 右侧区域 - 智能体对比 - 65%
  .allocation-right {
    width: 65%;
    min-height: 100%;
    padding-right: 8px;
    padding-top: 8px;
    padding-bottom: 8px;
    box-sizing: border-box;
  }

  .section-card {
    width: 100%;
    min-height: 100%;
    background-color: var(--color-task-outline-bg);
    border-radius: 8px;
    padding: 16px;
    box-sizing: border-box;
    overflow: visible;
    display: flex;
    flex-direction: column;

    .section-title {
      font-size: 18px;
      font-weight: bold;
      color: var(--color-text-title-header);
      margin-bottom: 16px;
      padding-bottom: 8px;
      flex-shrink: 0;
    }
  }

  // 任务大纲列表样式
  .task-outline-list {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 8px;

    .task-outline-item {
      padding: 10px 12px;
      border: 2px solid transparent;
      border-radius: 8px;
      font-size: 14px;
      color: var(--color-text-title-header);
      cursor: pointer;
      transition: all 0.2s ease;
      background-color: var(--color-flow-list-bg);
      box-sizing: border-box;
      overflow: hidden;

      .task-name {
        display: block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      &:hover {
        background-color: var(--color-card-bg-task-hover);
        box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.5);
        border: 2px solid transparent;
      }

      // 选中状态 - 渐变边框样式
      &.is-selected {
        border: 2px solid transparent;
        background: linear-gradient(
              var(--color-card-bg-task-hover),
              var(--color-card-bg-task-hover)
            )
            padding-box,
          linear-gradient(to right, var(--color-accent), var(--color-accent-secondary)) border-box;
        font-weight: 600;
      }
    }
  }

  // 智能体分组样式
  .agent-group {
    margin-bottom: 12px;

    // 分组标题（包裹列表）
    .agent-group-title {
      border-radius: 8px;
      overflow: hidden;
      background-color: var(--color-task-outline-bg);

      // 标题头部
      .agent-group-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 4px 8px;
        font-size: 12px;
        font-weight: 600;
        color: var(--color-text-title-header);
        cursor: pointer;
      }

      .agent-group-title-text {
        flex: 1;
      }

      .agent-group-delete {
        cursor: pointer;
        padding: 2px;
        border-radius: 4px;
        background-color: var(--color-group-delete-bg);
        color: var(--color-group-delete-icon);
        transition: all 0.2s ease;

        &:hover {
          background-color: var(--color-group-delete-bg-hover);
          color: var(--color-group-delete-icon);
          transform: rotate(180deg);
        }
      }

      // 智能体列表内容
      .agent-list-content {
        display: flex;
        flex-direction: column;
        border-radius: 8px;
        overflow: hidden;
        transition: background-color 0.2s ease;

        // 悬浮任意智能体时，整个列表变色
        &:has(.agent-item:hover) {
          background-color: var(--color-card-bg-task-hover);
        }

        // 选中状态 - 渐变边框
        &.agent-list-selected {
          border: 2px solid transparent;
          background: linear-gradient(
                var(--color-card-bg-task-hover),
                var(--color-card-bg-task-hover)
              )
              padding-box,
            linear-gradient(to right, var(--color-accent), var(--color-accent-secondary)) border-box;
        }
      }
    }

    .agent-item {
      display: flex;
      align-items: center;
      padding: 8px 12px;
      cursor: pointer;

      &:last-child {
        border-bottom: none;
      }

      .agent-info {
        display: flex;
        align-items: center;
        gap: 8px;

        .agent-icon {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
        }

        .agent-name {
          font-size: 13px;
          color: var(--color-text-title-header);
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }

  .comparison-content {
    flex: 1;
    overflow: visible;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 10px;
  }

  // 热力矩阵包装容器 - 包含矩阵和触发器列
  .heatmap-wrapper {
    display: flex;
    flex-direction: row;
    position: relative;
    flex-shrink: 0;
    min-width: max-content;
    align-items: stretch;

    // 新增维度触发器列 - 右侧固定宽度，随矩阵高度拉伸
    .add-dimension-trigger-column {
      width: 20px;
      min-height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      background-color: var(--color-bg-list);
      transition: all 0.2s ease;
      box-sizing: border-box;
      flex-shrink: 0;
      position: relative;
      border: 1px solid var(--color-border-separate);
      border-left: none;
      border-radius: 0 10px 10px 0;

      .svg-icon {
        color: rgba(216, 216, 216, 0.6);
        transition: all 0.2s ease;
      }

      &:hover .svg-icon {
        color: rgba(216, 216, 216, 1);
      }
    }
  }

  .heatmap-container {
    display: flex;
    flex-direction: column;
    gap: 0;
    position: relative;
    align-content: flex-start;
    flex-shrink: 0;
    min-width: max-content;
    border-radius: 10px 0 0 10px;
    background-color: var(--color-card-bg-task);
    // border: 1px solid var(--color-border-separate);
    border-right: none;
    overflow: visible;

    // 虚线选择框（竖向增长 = Y轴方向延伸）
    .selection-box {
      position: absolute;
      border: 2px solid transparent;
      border-radius: 6px;
      pointer-events: none;
      box-sizing: border-box;
      border-image: linear-gradient(to bottom, var(--color-accent), var(--color-accent-secondary)) 1;
      z-index: 10;

      // 确定按钮 - 位于选中框底部居中
      .confirm-button {
        position: absolute;
        left: 50%;
        bottom: -8px;
        transform: translateX(-50%);
        width: 20px;
        height: 20px;
        background-color: var(--color-card-bg-task);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        pointer-events: auto;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        transition: all 0.2s ease;
        z-index: 11;

        &:hover {
          transform: translateX(-50%) scale(1.1);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
        }

        &.is-loading {
          opacity: 0.6;
          cursor: not-allowed;
          pointer-events: none;

          svg {
            animation: spin 1s linear infinite;
          }
        }
      }

      @keyframes spin {
        from {
          transform: translateX(-50%) rotate(0deg);
        }
        to {
          transform: translateX(-50%) rotate(360deg);
        }
      }
    }

    // 维度名称行（X轴 = 水平方向）
    .heatmap-dimension-header {
      display: flex;
      flex-direction: row;
      gap: 0;
      flex-shrink: 0;
      overflow: visible;

      // 角落格子：显示模式切换
      .heatmap-corner {
        width: 80px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: rgba(255, 255, 255, 0.05);
        border: 1px solid var(--color-border-separate);
        font-size: 12px;
        color: var(--color-text-secondary);
        cursor: pointer;
        transition: all 0.2s ease;
        flex-shrink: 0;
        box-sizing: border-box;
        gap: 4px;

        .separator {
          color: var(--color-border-separate);
        }

        span {
          cursor: pointer;
          border-radius: 4px;
          transition: all 0.2s ease;

          &.is-active {
            color: var(--color-accent);
            font-weight: 600;
          }
        }

        &:hover {
          background-color: #50555d;
        }
      }

      // 维度名称单元格
      .dimension-header-cell {
        width: 80px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        font-size: 10px;
        font-weight: 600;
        color: var(--color-text-title-header);
        text-align: center;
        cursor: pointer;
        user-select: none;
        transition: all 0.2s ease;
        border: 1px solid var(--color-border-separate);
        background-color: var(--color-card-bg-task);
        flex-shrink: 0;
        box-sizing: border-box;
        padding: 2px;
        word-break: break-all;
        line-height: 1.2;

        // 单数列
        &.is-odd {
          background-color: #3a4049;
        }
        // 双数列
        &.is-even {
          background-color: #2f353e;
        }

        &:hover {
          color: #409eff;
          background-color: #50555d;
        }

        &.is-selected {
          color: #409eff;
          font-weight: 700;
          background-color: rgba(64, 158, 255, 0.1);
        }

        .dimension-name {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .dimension-delete-btn {
          position: absolute;
          top: -6px;
          right: -6px;
          width: 14px;
          height: 14px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          cursor: pointer;
          opacity: 0;
          transition: opacity 0.2s ease;
          color: #fff;
          background-color: #2d2d2d;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
          z-index: 10;

          &:hover {
            background-color: #000;
            transform: scale(1.1);
          }
        }

        &:hover .dimension-delete-btn {
          opacity: 1;
        }
      }
    }

    // agent数据行（Y轴 = 垂直方向）
    .heatmap-agent-row {
      display: flex;
      flex-direction: row;
      gap: 0;
      flex-shrink: 0;

      // agent名称/头像标签
      .agent-label-cell {
        width: 80px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        box-sizing: border-box;
        border: 1px solid var(--color-border-separate);
        background-color: var(--color-card-bg-task);

        // 单数行
        &.is-odd-row {
          background-color: #3a4049;
        }
        // 双数行
        &.is-even-row {
          background-color: #2f353e;
        }

        .agent-label-content {
          width: 80px;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.2s ease;

          &:hover {
            background-color: #50555d;
          }

          .agent-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .agent-name-display {
            font-size: 10px;
            color: var(--color-text-title-header);
            text-align: center;
            white-space: nowrap;
            line-height: 1.2;
            max-width: 76px;
            overflow: hidden;
            text-overflow: ellipsis;
            padding: 0 4px;
          }
        }
      }

      // 评分单元格
      .heatmap-cell-wrapper {
        width: 80px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        box-sizing: border-box;
        .heatmap-cell {
          width: 80px;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          font-weight: bold;
          cursor: pointer;
          transition: all 0.2s ease;
          box-sizing: border-box;

          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            z-index: 1;
          }
        }
      }
    }
  }

  .placeholder-text {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    font-size: 16px;
    color: var(--color-text-secondary);
  }

  // 新增维度输入框区域 - BranchInput 样式复用
  .external-input-container {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 100%;
    margin-right: 10px;
    width: 260px;
    background: linear-gradient(var(--color-card-bg-task), var(--color-card-bg-task)) padding-box,
      linear-gradient(to right, var(--color-accent), var(--color-accent-secondary)) border-box;
    border: 2px solid transparent;
    border-radius: 30px;
    padding: 10px 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    z-index: 100;
  }

  .branch-input-container {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .branch-input {
    width: 100%;

    :deep(.el-input__wrapper) {
      background: transparent;
      border: none;
      box-shadow: none;

      &:hover {
        border: none;
      }

      &.is-focus {
        border: none;
        box-shadow: none;
      }

      .el-input__inner {
        font-size: 14px;
        color: var(--color-text-taskbar);
      }
    }
  }

  .submit-icon {
    cursor: pointer;
    transition: all 0.2s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: linear-gradient(to right, var(--color-accent), var(--color-accent-secondary));

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

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

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

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

  @keyframes slideRight {
    from {
      opacity: 0;
      transform: translateX(10px);
    }
    to {
      opacity: 1;
      transform: translateX(0);
    }
  }

  // 搜索输入框区域
  .search-input-container {
    margin-top: 16px;
    width: 50%;
    flex-basis: 50%;

    .search-input {
      width: 100%;

      :deep(.el-input__wrapper) {
        padding-right: 8px;
      }

      :deep(.el-input__inner) {
        font-size: 14px;
      }

      .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;
        }

        &.is-loading {
          opacity: 0.7;
          animation: spin 1s linear infinite;
        }
      }
    }
  }
}

.agent-tooltip {
  width: 150px;
  .agent-tooltip-name {
    font-size: 16px;
    font-weight: bold;
  }

  .agent-tooltip-separator {
    height: 1px;
    width: 100%;
    background: #494b51;
    margin: 4px 0;
  }

  .agent-tooltip-description {
    font-size: 12px;
    white-space: pre-wrap;
    word-break: break-word;
  }
}

.score-tooltip {
  width: 250px;
  .score-tooltip-reason {
    font-size: 12px;
    white-space: pre-wrap;
    word-break: break-word;
    line-height: 1.4;
  }
}
</style>

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