<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { useAgentsStore, useSelectionStore } from '@/stores'
import { getAgentMapIcon } from '@/layout/components/config'
import SvgIcon from '@/components/SvgIcon/index.vue'
import api from '@/api'
const agentsStore = useAgentsStore()
const selectionStore = useSelectionStore()

// 获取当前选中的任务
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的热力图数据
const agentsHeatmapData = ref<AgentHeatmapData[]>([])

// 选中的agent集合（用于Comparison部分）
const selectedAgents = ref<Set<string>>(new Set())

// 当前选中的Assignment组合的agents（用于Assignment卡片的边框显示）
const selectedAssignmentGroup = ref<string[]>([])

// 选中的维度集合
const selectedDimensions = ref<Set<string>>(new Set())

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

// 搜索框的值
const searchValue = ref('')

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

// 处理搜索提交
const handleSubmit = async () => {
  if (!searchValue.value.trim() || isAddingDimension.value) return

  const newDimension = searchValue.value.trim()

  // 检查维度是否已存在
  if (scoreDimensions.value.includes(newDimension)) {
    console.log(`维度"${newDimension}"已存在，跳过添加`)
    searchValue.value = ''
    return
  }

  try {
    isAddingDimension.value = true

    // 使用 Mock API 进行测试（开发阶段）
    // 切换到真实API时，只需将 mockAgentSelectModifyAddAspect 改为 agentSelectModifyAddAspect
    const response = await api.agentSelectModifyAddAspect({
      aspectList: [...scoreDimensions.value, newDimension]
    })

    console.log('Mock API - 添加新维度成功:', response)

    // 1. 先添加新维度到本地维度列表（立即显示）
    scoreDimensions.value.push(response.aspectName)

    // 2. 为每个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
        })
      }
    })

    console.log(`已添加新维度"${response.aspectName}"到热力图`)

    // 3. 异步更新 store（等前端显示完成后再更新，避免触发重新初始化）
    await nextTick()

    const currentStoreData = agentsStore.IAgentSelectModifyAddRequest
    if (currentStoreData && currentStoreData.aspectList) {
      // 检查维度是否已存在（防止store中已存在）
      if (!currentStoreData.aspectList.includes(response.aspectName)) {
        currentStoreData.aspectList.push(response.aspectName)
      }
      // 更新评分数据
      // response.agentScores: { agentName: { score, reason } }
      // 转换为 agentScores[agentName][aspectName] = { score, reason }
      for (const [agentName, scoreInfo] of Object.entries(response.agentScores)) {
        if (!currentStoreData.agentScores[agentName]) {
          currentStoreData.agentScores[agentName] = {}
        }
        currentStoreData.agentScores[agentName][response.aspectName] = scoreInfo
      }
      console.log(`已更新 store`)
    }

    // 清空输入框
    searchValue.value = ''
  } 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) {
      // 找到重复的组合，只选中该卡片，不添加重复
      console.log('该agent组合已存在，只选中卡片，不添加重复')
      const existingGroup = existingGroups[existingDuplicateIndex]!
      selectedAssignmentGroup.value = [...existingGroup]
      selectedAgents.value = new Set(existingGroup)
      return
    }

    // 该组合不存在，添加新组合
    // 使用 store 的方法添加，按任务ID存储（不持久化到localStorage）
    agentsStore.addConfirmedAgentGroup(currentTask.value.Id, agentArray)
    console.log(`已确认 agent 组合 [任务 ${currentTask.value.Id}]:`, agentArray)

    // 调用 Mock API 填充任务流程
    try {
      isLoadingConfirm.value = true
      console.log('=== 开始调用 fillStepTaskTaskProcess Mock API ===')
      console.log('1. 当前任务数据 (IRawStepTask 格式):', currentTask.value)
      console.log('2. 选中的 agents:', agentArray)

      // 将 IRawStepTask 转换为 IApiStepTask 格式
      const stepTaskForApi = {
        name: currentTask.value.StepName || '',
        content: currentTask.value.TaskContent || '',
        inputs: currentTask.value.InputObject_List || [],
        output: currentTask.value.OutputObject || '',
        agents: agentArray,
        brief: currentTask.value.Collaboration_Brief_frontEnd || {
          template: '',
          data: {}
        },
        process: []
      }

      console.log('3. 转换后的 API 请求参数 (IApiStepTask 格式):', stepTaskForApi)

      // 获取 goal（从 agentRawPlan 中获取）
      const goal = agentsStore.agentRawPlan.data?.['General Goal'] || '开发智能协作系统'
      console.log('4. General Goal:', goal)

      // 调用 Mock API
      const filledTask = await api.fillStepTaskTaskProcess({
        goal,
        stepTask: stepTaskForApi,
        agents: agentArray
      })

      console.log('=== Mock API 返回成功 ===')
      console.log('5. 返回的完整数据 (IApiStepTask 格式):', filledTask)
      console.log('6. TaskProcess 流程数量:', filledTask.process?.length || 0)
      console.log('7. TaskProcess 详情:', filledTask.process)
      console.log('8. Collaboration Brief:', filledTask.brief)

      // 存储到 selectionStore
      selectionStore.setAgentTaskProcess(currentTask.value.Id, agentArray, filledTask)
      console.log('✅ Mock API 调用成功，数据已存储到 selectionStore')
    } catch (error) {
      console.error('❌ Mock API 调用失败:', error)
    } finally {
      isLoadingConfirm.value = false
    }
  }
}

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

  // 更新Comparison部分的选中状态
  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) {
    console.log('🔄 开始联动更新 currentTask 的 agent 组合:', agentNames)

    // 从 selectionStore 获取该 agent 组合对应的 TaskProcess 数据
    let taskProcessData = selectionStore.getAgentTaskProcess(currentTask.value.Id, agentNames)

    // 🆕 如果 selectionStore 中没有数据，自动调用 API 加载
    if (!taskProcessData) {
      console.log('⚠️ selectionStore 中没有该组合的 TaskProcess 数据，开始加载...')
      console.log('📋 当前任务信息:', {
        taskId: currentTask.value.Id,
        taskName: currentTask.value.StepName,
        agents: agentNames
      })

      try {
        isLoadingSelectGroup.value = true
        // 将 IRawStepTask 转换为 IApiStepTask 格式
        const stepTaskForApi = {
          name: currentTask.value.StepName || '',
          content: currentTask.value.TaskContent || '',
          inputs: currentTask.value.InputObject_List || [],
          output: currentTask.value.OutputObject || '',
          agents: agentNames,
          brief: currentTask.value.Collaboration_Brief_frontEnd || {
            template: '',
            data: {}
          },
          process: []
        }

        const goal = agentsStore.agentRawPlan.data?.['General Goal'] || '开发智能协作系统'

        console.log('📤 准备调用 API:', {
          goal,
          stepTask: stepTaskForApi,
          agents: agentNames
        })

        // 调用 Mock API 加载数据
        const filledTask = await api.fillStepTaskTaskProcess({
          goal,
          stepTask: stepTaskForApi,
          agents: agentNames
        })

        console.log('🔍 API 返回的完整响应:', filledTask)
        console.log('🔍 process 数据:', filledTask.process)
        console.log('🔍 process 长度:', filledTask.process?.length)
        console.log('✅ TaskProcess 数据加载成功:', {
          agents: agentNames,
          processCount: filledTask.process?.length || 0,
          processDetail: filledTask.process,
          briefDetail: filledTask.brief
        })

        // 存储到 selectionStore
        selectionStore.setAgentTaskProcess(currentTask.value.Id, agentNames, filledTask)

        console.log('💾 数据已存储到 selectionStore，验证存储是否成功...')
        // 验证存储
        const storedData = selectionStore.getAgentTaskProcess(currentTask.value.Id, agentNames)
        console.log('📦 验证存储结果:', storedData ? '成功' : '失败', storedData)

        taskProcessData = filledTask
      } catch (error) {
        console.error('❌ 加载 TaskProcess 数据失败:', error)
        return
      } finally {
        isLoadingSelectGroup.value = false
      }
    }

    if (taskProcessData) {
      console.log('✅ 找到 TaskProcess 数据，开始更新 currentTask:', {
        taskId: currentTask.value.Id,
        agents: agentNames,
        processCount: taskProcessData.process?.length || 0,
        processDetail: taskProcessData.process,
        briefDetail: taskProcessData.brief
      })

      // 🆕 数据格式转换：IApiAgentAction[] → TaskProcess[]
      const convertedTaskProcess = (taskProcessData.process || []).map(action => ({
        ID: action.id,
        ActionType: action.type,
        AgentName: action.agent,
        Description: action.description,
        ImportantInput: action.inputs || []
      }))

      console.log('🔄 数据格式转换完成:', {
        original: taskProcessData.process,
        converted: convertedTaskProcess
      })

      // 更新 currentTask 的 AgentSelection 和 TaskProcess
      // 使用 updateCurrentAgentSelection 强制更新，避免被 setCurrentTask 的"智能保留"逻辑阻止
      agentsStore.updateCurrentAgentSelection(
        [...agentNames],
        convertedTaskProcess,
        taskProcessData.brief || currentTask.value.Collaboration_Brief_frontEnd
      )

      console.log('✅ currentTask 已更新，新的 AgentSelection:', agentNames)
      console.log('📋 验证更新结果:', agentsStore.currentTask)
    }
  }

  // 重新排序：被选中的agent排在前面，其他agent按平均分降序
  if (agentsHeatmapData.value.length > 0) {
    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
    })
  }

  console.log('选中 agent 组合:', Array.from(selectedAgents.value))
}

// 切换维度选中状态
const toggleDimensionSelection = (dimension: string) => {
  if (selectedDimensions.value.has(dimension)) {
    selectedDimensions.value.delete(dimension)
  } else {
    selectedDimensions.value.add(dimension)
  }
  // 触发响应式更新
  selectedDimensions.value = new Set(selectedDimensions.value)

  // 重新排序agent
  if (agentsHeatmapData.value.length > 0) {
    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 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)

  // 重新排序：被选中的agent排在前面，其他agent按平均分降序
  if (agentsHeatmapData.value.length > 0) {
    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
    })
  }
}

// 判断agent是否被选中
const isAgentSelected = (agentName: string) => {
  return selectedAgents.value.has(agentName)
}

// 判断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))
}

// 获取选中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)
}

// 计算虚线框的样式
const getSelectionBoxStyle = () => {
  const indexes = getSelectedAgentIndexes()
  if (indexes.length === 0) {
    return {}
  }

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

  // 每列的宽度为40px (heatmap-column和heatmap-column-header的宽度)
  const columnWidth = 40
  const headerHeight = 40
  const boxPadding = 4

  return {
    left: `${firstIndex * columnWidth}px`,
    top: '0px',
    width: `${(lastIndex - firstIndex + 1) * columnWidth}px`,
    height: `${headerHeight}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 () => {
  // 先检查 store 中是否已有数据
  const storedData = agentsStore.IAgentSelectModifyAddRequest
  if (storedData && storedData.aspectList && storedData.aspectList.length > 0) {
    console.log('使用 store 中的评分数据')
    return {
      aspectList: storedData.aspectList,
      agentScores: storedData.agentScores
    }
  }

  // TODO: 切换到真实API时，取消注释下面这行
  const agentScores = await api.agentSelectModifyInit({
    goal: agentsStore.agentRawPlan.data?.['General Goal'] || '',
    stepTask: currentTask.value
  })

  // 🆕 使用 Mock API（开发阶段），传递当前任务的 AgentSelection 以获取对应的维度
  const goal = agentsStore.agentRawPlan.data?.['General Goal'] || '开发智能协作系统'
  console.log('📤 调用 mockAgentSelectModifyInit，参数:', {
    goal,
    stepTask: currentTask.value,
    agentSelection: currentTask.value?.AgentSelection
  })

  // const agentScores = await api.mockAgentSelectModifyInit()

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

  console.log('✅ 获取到的维度列表:', aspectList)

  // 保存到 store
  agentsStore.setAgentScoreData({
    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 { aspectList, agentScores } = await fetchAgentScores()

    // 设置评分维度
    scoreDimensions.value = aspectList

    // 转换数据结构：为每个agent生成评分数据
    const heatmapData = agents.map(agent => {
      const agentName = agent.Name
      const scores: number[] = []
      const scoreDetails: Array<{ dimension: string; score: number; reason: string }> = []

      // 按照维度顺序获取评分
      aspectList.forEach(dimension => {
        // 数据结构：agentScores[agentName][dimension]
        const agentScoreData = agentScores[agentName]
        const scoreData = agentScoreData ? agentScoreData[dimension] : null

        if (scoreData) {
          scores.push(scoreData.score)
          scoreDetails.push({
            dimension,
            score: scoreData.score,
            reason: scoreData.reason
          })
        } else {
          // 如果没有评分数据，默认为1
          scores.push(1)
        }
      })

      return {
        agentName,
        scores,
        scoreDetails
      }
    })

    // 排序逻辑：
    // 1. Assignment部分的agent（currentTaskAgents）排在前面
    // 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)
    // 降级处理：使用默认维度列表和随机数据
    const defaultAspects = ['能力', '可用性', '专业性', '效率', '准确性', '协作性']
    scoreDimensions.value = defaultAspects
    agentsHeatmapData.value = tempData.map(item => ({
      ...item,
      scores: Array.from(
        { length: defaultAspects.length },
        () => Math.floor(Math.random() * 5) + 1
      ),
      scoreDetails: []
    }))
  } finally {
    isInitializing.value = false
  }
}

// 监听agent列表变化，初始化热力矩阵
watch(
  () => allAgents.value.length,
  newLength => {
    if (newLength > 0) {
      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 }
)

// 初始化和任务切换处理
// 1. 首次加载时，自动将初始 agent 组合添加到 confirmedAgentGroups
// 2. 恢复之前的选择状态
// 3. 加载 TaskProcess 数据
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

    // 首次初始化：自动添加初始组合（相当于系统自动执行了 confirmAgentSelection）
    if (!hasInitialGroup) {
      console.log('🎯 首次初始化，自动添加初始 agent 组合到 Assignment')
      agentsStore.addConfirmedAgentGroup(newTask.Id, [...newTask.AgentSelection])

      // 调用 API 获取初始 agent 组合的 TaskProcess 数据
      console.log('🔄 开始加载初始 agent 组合的 TaskProcess...')

      // 检查是否已有数据
      if (!selectionStore.hasAgentTaskProcess(newTask.Id, newTask.AgentSelection)) {
        try {
          isLoadingInitialTask.value = true
          console.log('=== 开始加载初始 agent 组合的 TaskProcess ===')
          console.log('1. 任务ID:', newTask.Id)
          console.log('2. 初始 agents:', newTask.AgentSelection)

          // 将 IRawStepTask 转换为 IApiStepTask 格式
          const stepTaskForApi = {
            name: newTask.StepName || '',
            content: newTask.TaskContent || '',
            inputs: newTask.InputObject_List || [],
            output: newTask.OutputObject || '',
            agents: newTask.AgentSelection,
            brief: newTask.Collaboration_Brief_frontEnd || {
              template: '',
              data: {}
            },
            process: []
          }

          console.log('3. 转换后的 API 请求参数:', stepTaskForApi)

          const goal = agentsStore.agentRawPlan.data?.['General Goal'] || '开发智能协作系统'
          console.log('4. General Goal:', goal)

          // 调用 Mock API 获取 TaskProcess
          const filledTask = await api.fillStepTaskTaskProcess({
            goal,
            stepTask: stepTaskForApi,
            agents: newTask.AgentSelection
          })

          console.log('=== 初始 agent 组合 TaskProcess 加载成功 ===')
          console.log('5. TaskProcess 流程数量:', filledTask.process?.length || 0)

          // 存储到 selectionStore
          selectionStore.setAgentTaskProcess(newTask.Id, newTask.AgentSelection, filledTask)
          console.log('✅ 初始 agent 组合的 TaskProcess 已加载并存储')
        } catch (error) {
          console.error('❌ 加载初始 agent 组合的 TaskProcess 失败:', error)
        } finally {
          isLoadingInitialTask.value = false
        }
      } else {
        console.log('ℹ️ 初始 agent 组合已有 TaskProcess 数据，跳过加载')
      }
    }

    // 从 store 中恢复之前选择的 agent 组合（如果有）
    const savedAgentGroup = agentsStore.getSelectedAgentGroup(newTask.Id)
    if (savedAgentGroup) {
      console.log('📂 恢复之前选择的 agent 组合:', savedAgentGroup)
      selectedAssignmentGroup.value = [...savedAgentGroup]
      selectedAgents.value = new Set(savedAgentGroup)
    } else {
      // 没有保存的选择，默认选中第一个组合（即初始组合）
      const allGroups = agentsStore.getConfirmedAgentGroups(newTask.Id)
      if (allGroups.length > 0 && allGroups[0]) {
        console.log('🔄 默认选中第一个组合（初始组合）:', allGroups[0])
        selectedAssignmentGroup.value = [...allGroups[0]]
        selectedAgents.value = new Set(allGroups[0])
      }
    }
  },
  { immediate: true } // 立即执行一次
)

// 获取热力图颜色（评分1-5，颜色从浅到深）
const getHeatmapColor = (score: number) => {
  const colors = [
    '#f7f7f7', // 1分 - 最浅
    '#d4e5f7', // 2分
    '#89b4e8', // 3分
    '#4575b4', // 4分
    '#313695' // 5分 - 最深
  ]
  return colors[score - 1] || colors[0]
}
</script>

<template>
  <div class="agent-allocation-container">
    <!-- 左侧区域 - 20% -->
    <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="agents-grid"
          :class="{ 'agent-group-selected': isAgentGroupSelected(group) }"
          :style="{ marginTop: groupIndex > 0 ? '12px' : '0' }"
          @click="selectAgentGroup(group)"
        >
          <el-tooltip
            v-for="agent in group"
            :key="agent"
            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-item">
              <div class="agent-icon" :style="{ background: getAgentMapIcon(agent).color }">
                <svg-icon :icon-class="getAgentMapIcon(agent).icon" color="#fff" size="20px" />
              </div>
            </div>
          </el-tooltip>
        </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 || isLoadingInitialTask || isLoadingConfirm"
        >
          <!-- 热力矩阵图 -->
          <div v-if="agentsHeatmapData.length > 0" 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>

            <!-- 按agent列组织数据 -->
            <div
              v-for="(agentData, index) in agentsHeatmapData"
              :key="agentData.agentName"
              class="heatmap-column"
            >
              <!-- Agent头像作为列标题 -->
              <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="heatmap-column-header"
                  :data-agent-index="index"
                  @click="toggleAgentSelection(agentData.agentName)"
                >
                  <div
                    class="agent-avatar"
                    :style="{ background: getAgentMapIcon(agentData.agentName).color }"
                  >
                    <svg-icon
                      :icon-class="getAgentMapIcon(agentData.agentName).icon"
                      color="#fff"
                      size="16px"
                    />
                  </div>
                </div>
              </el-tooltip>

              <!-- 该agent在各维度的评分（只在有数据时显示） -->
              <template v-if="agentData.scores.length > 0">
                <el-tooltip
                  v-for="(score, scoreIndex) in agentData.scores"
                  :key="scoreIndex"
                  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?.[scoreIndex]?.reason || '该智能体在此维度表现良好'
                        }}
                      </div>
                    </div>
                  </template>
                  <div
                    class="heatmap-cell"
                    :style="{
                      backgroundColor: getHeatmapColor(score),
                      color: score <= 2 ? '#333' : '#fff'
                    }"
                  >
                    {{ score }}
                  </div>
                </el-tooltip>
              </template>
            </div>

            <!-- 维度名称标签（在最右侧，只在有数据时显示） -->
            <div v-if="scoreDimensions.length > 0" class="dimension-labels">
              <div
                v-for="dimension in scoreDimensions"
                :key="dimension"
                class="dimension-label"
                :class="{ 'is-selected': isDimensionSelected(dimension) }"
                @click="toggleDimensionSelection(dimension)"
              >
                {{ dimension }}
              </div>
            </div>
          </div>

          <!-- 输入框区域 -->
          <div class="search-input-container" v-loading="isAddingDimension">
            <el-input
              v-model="searchValue"
              placeholder="请输入新维度"
              size="large"
              class="search-input"
            >
              <template #suffix>
                <svg-icon
                  icon-class="paper-plane"
                  size="16px"
                  color="#409eff"
                  class="submit-icon"
                  :class="{ 'is-disabled': !searchValue, 'is-loading': isAddingDimension }"
                  @click="searchValue && handleSubmit()"
                />
              </template>
            </el-input>
          </div>
        </div>
        <div v-else class="placeholder-text">暂无智能体</div>
      </div>
    </div>
  </div>
</template>

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

  // 左侧区域 - 30%
  .allocation-left {
    width: 20%;
    height: 100%;
  }

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

  // 右侧区域 - 69%
  .allocation-right {
    width: 79%;
    height: 100%;
  }

  .section-card {
    width: 100%;
    height: 100%;
    background-color: var(--color-card-bg-task);
    border: 1px solid var(--color-card-border-task);
    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;
      border-bottom: 1px solid var(--color-border-separate);
      flex-shrink: 0;
    }
  }

  .agents-grid {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px;
    min-height: 48px;
    max-height: 48px;
    border: 1px solid var(--color-card-border-task);
    border-radius: 10px;
    overflow-x: auto;
    overflow-y: hidden;

    .agent-item {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s ease;
      flex-shrink: 0;

      .agent-icon {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s ease;
        border: 3px solid transparent;
      }
    }
  }

  // Assignment卡片选中效果
  .agents-grid.agent-group-selected {
    border: 2px solid var(--color-accent);
    box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
  }

  .comparison-content {
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .heatmap-container {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    gap: 0;
    position: relative;
    align-content: flex-start;
    flex-shrink: 0;
    min-width: max-content;

    // 虚线选择框
    .selection-box {
      position: absolute;
      border: 2px dashed var(--color-accent);
      border-radius: 8px;
      pointer-events: none;
      box-sizing: border-box;
      background-color: rgba(64, 158, 255, 0.05);
      z-index: 10;

      // 确定按钮
      .confirm-button {
        position: absolute;
        right: -8px;
        bottom: -8px;
        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: 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: rotate(0deg);
        }
        to {
          transform: rotate(360deg);
        }
      }
    }

    .heatmap-column {
      display: flex;
      flex-direction: column;
      gap: 0;
      transition: all 0.2s ease;
      position: relative;
      padding: 0;
      border-radius: 6px;

      &:hover {
        background-color: rgba(0, 0, 0, 0.02);
      }

      .heatmap-column-header {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        cursor: pointer;
        transition: all 0.2s ease;

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

      .heatmap-cell {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        font-weight: bold;
        cursor: default;
        transition: all 0.2s ease;
        flex-shrink: 0;

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

    .dimension-labels {
      position: sticky;
      left: 0;
      margin-left: 8px;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      padding-top: 40px; // 对齐第一个评分单元格
      flex-shrink: 0;
      max-width: 200px; //

      .dimension-label {
        min-width: 60px; // 改为最小宽度，允许根据内容自适应
        width: auto; // 宽度自适应
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        padding-left: 8px;
        padding-right: 8px; // 添加右侧内边距，确保文字不会紧贴边缘
        font-size: 12px;
        font-weight: 600;
        color: var(--color-text-title-header);
        text-align: left;
        cursor: pointer;
        user-select: none;
        transition: all 0.2s ease;
        white-space: nowrap; // 防止文字换行

        &:hover {
          color: #409eff;
        }

        &.is-selected {
          color: #409eff;
          font-weight: 700;
        }
      }
    }
  }

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

  // 搜索输入框区域
  .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>
