<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, reactive, nextTick } from 'vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import { useAgentsStore, useConfigStore, useSelectionStore } from '@/stores'
import api from '@/api'
import websocket from '@/utils/websocket'
import { changeBriefs } from '@/utils/collaboration_Brief_FrontEnd.ts'
import { useNotification } from '@/composables/useNotification'
import AssignmentButton from './TaskTemplate/TaskSyllabus/components/AssignmentButton.vue'
import { withRetry } from '@/utils/retry'
import UnifiedSettingsPanel from './TaskTemplate/UnifiedSettingsPanel.vue'
import { Setting } from '@element-plus/icons-vue'

const emit = defineEmits<{
  (e: 'search-start'): void
  (e: 'search', value: string): void
  (e: 'open-history'): void
}>()

const agentsStore = useAgentsStore()
const configStore = useConfigStore()
const selectionStore = useSelectionStore()
const { success, warning, error: notifyError } = useNotification()
const searchValue = ref('')
const triggerOnFocus = ref(true)
const isFocus = ref(false)
const hasAutoSearched = ref(false)
const isExpanded = ref(false)
const isFillingSteps = ref(false)
const isStopping = ref(false)
const isStopPending = ref(false)
const currentStepAbortController = ref<{ cancel: () => void } | null>(null)
const currentGenerationId = ref('')
const currentTaskID = ref('') // 后端数据库主键

// 监听 currentTaskID 变化，同步到全局变量（供分支保存使用）
watch(currentTaskID, newVal => {
  ;(window as any).__CURRENT_TASK_ID__ = newVal || ''
})

const currentPlanOutline = ref<any>(null) // 用于恢复的完整大纲数据

// 解析URL参数
function getUrlParam(param: string): string | null {
  const urlParams = new URLSearchParams(window.location.search)
  return urlParams.get(param)
}

const planReady = computed(() => {
  return agentsStore.agentRawPlan.data !== undefined
})
const openAgentAllocationDialog = () => {
  agentsStore.openAgentAllocationDialog()
}
// 自动搜索函数
async function autoSearchFromUrl() {
  const query = getUrlParam('q')
  if (query && !hasAutoSearched.value) {
    // 解码URL参数
    const decodedQuery = decodeURIComponent(query)
    searchValue.value = decodedQuery
    hasAutoSearched.value = true

    // 延迟执行搜索，确保组件已完全渲染
    setTimeout(() => {
      handleSearch()
    }, 100)
  }
}

// 处理获取焦点事件
function handleFocus() {
  isFocus.value = true
  isExpanded.value = true // 搜索框展开
}

const taskContainerRef = ref<HTMLDivElement | null>(null)

// 处理失去焦点事件
function handleBlur() {
  isFocus.value = false
  setTimeout(() => {
    isExpanded.value = false
    resetTextareaHeight()
  }, 200)
}

// 预加载所有任务的智能体评分数据
async function preloadAllTaskAgentScores(outlineData: any, goal: string, TaskID: string) {
  const tasks = outlineData['Collaboration Process'] || []

  if (tasks.length === 0) {
    return
  }

  for (const task of tasks) {
    // 检查是否已停止
    if (agentsStore.isStopping || agentsStore.hasStoppedFilling) {
      return
    }

    // 确保任务有唯一ID
    if (!task.Id) {
      task.Id = `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    }

    // 调用初始化接口获取评分数据
    try {
      const agentScores = await api.agentSelectModifyInit({
        goal: goal,
        stepTask: {
          Id: task.Id, // 小任务步骤ID，用于数据库存储
          StepName: task.StepName,
          TaskContent: task.TaskContent,
          InputObject_List: task.InputObject_List,
          OutputObject: task.OutputObject
        },
        TaskID: TaskID // 后端数据库主键（大任务ID）
      })

      // 提取维度列表并存储
      const firstAgent = Object.keys(agentScores)[0]
      const aspectList = firstAgent ? Object.keys(agentScores[firstAgent] || {}) : []

      agentsStore.setTaskScoreData(task.Id, {
        aspectList,
        agentScores
      })
    } catch (error) {
      console.error(`❌ 任务 "${task.StepName}" 的评分数据预加载失败:`, error)
    }
  }
}

// 重置文本区域高度到最小行数
function resetTextareaHeight() {
  nextTick(() => {
    // 获取textarea元素
    const textarea =
      document.querySelector('#task-container .el-textarea__inner') ||
      document.querySelector('#task-container textarea')

    if (textarea instanceof HTMLElement) {
      // 强制设置最小高度
      textarea.style.height = 'auto'
      textarea.style.minHeight = '56px'
      textarea.style.overflowY = 'hidden'
    }
  })
}

// 停止填充数据的处理函数
async function handleStop() {
  // 检查是否有正在进行的生成任务
  if (!isFillingSteps.value) {
    warning('提示', '没有正在进行的生成任务')
    return
  }

  // 先设置停止状态（立即显示"停止中..."）
  agentsStore.setIsStopping(true)
  isStopping.value = true
  isStopPending.value = true
  success('提示', '正在停止，请稍候...')

  // 发送停止请求（不等待响应，后端设置 should_stop = True）
  if (websocket.connected && currentGenerationId.value) {
    websocket
      .send('stop_generation', {
        generation_id: currentGenerationId.value
      })
      .then((result: any) => {
        console.log('停止生成响应:', result)
      })
      .catch((error: any) => {
        console.log('停止生成请求失败（可能已经停止）:', error?.message)
      })
  }
  // 不清空 currentGenerationId，让 fillStepTask 循环检查 isStopping 来停止
}

// 监听后端发送的停止完成事件（备用，如果后端有发送）
function onGenerationStopped() {
  isStopping.value = false
  isStopPending.value = false
  currentGenerationId.value = ''
  success('成功', '已停止生成')
}

// 处理按钮点击事件
function handleButtonClick() {
  if (isFillingSteps.value) {
    handleStop()
  } else {
    handleSearch()
  }
}

// 处理搜索函数
async function handleSearch() {
  triggerOnFocus.value = false
  if (!searchValue.value) {
    warning('提示', '请输入搜索内容')
    return
  }
  emit('search-start')

  // 重置所有状态（处理可能的上一次未完成的停止操作）
  isStopping.value = false
  isStopPending.value = false
  agentsStore.setIsStopping(false)
  agentsStore.setHasStoppedFilling(false)

  agentsStore.resetAgent()
  agentsStore.setAgentRawPlan({ loading: true })

  // 重置 generation_id
  currentGenerationId.value = ''

  // 获取大纲
  const response = await api.generateBasePlan({
    goal: searchValue.value,
    inputs: []
  })

  // WebSocket 返回格式: { data: { task_id, generation_id, basePlan }, generation_id, execution_id }
  // REST API 返回格式: {...}
  // 提取真正的outline数据
  let outlineData: any
  if (response?.data?.basePlan) {
    // WebSocket新格式：数据嵌套在basePlan中
    outlineData = response.data.basePlan
    currentGenerationId.value = response.data.generation_id || ''
    currentTaskID.value = response.data.task_id || ''
    console.log(
      '📋 WebSocket格式: 从basePlan提取数据, generation_id:',
      currentGenerationId.value,
      'TaskID:',
      currentTaskID.value
    )
  } else if (response?.data) {
    // 可能是WebSocket旧格式或REST API格式
    outlineData = response.data
    currentGenerationId.value = response.generation_id || ''
    currentTaskID.value = ''
    console.log('📋 直接格式: generation_id:', currentGenerationId.value)
  } else {
    outlineData = response
    currentGenerationId.value = ''
    currentTaskID.value = ''
  }

  // 处理简报数据格式
  outlineData['Collaboration Process'] = changeBriefs(outlineData['Collaboration Process'])

  // 立即显示大纲
  agentsStore.setAgentRawPlan({ data: outlineData, loading: false })
  emit('search', searchValue.value)

  // 预加载所有任务的智能体评分数据
  preloadAllTaskAgentScores(outlineData, searchValue.value, currentTaskID.value)

  // 填充步骤详情
  isFillingSteps.value = true
  const steps = outlineData['Collaboration Process'] || []

  // 保存 generation_id 和 TaskID 到本地变量，用于 fillStepTask 调用
  // 这样即使前端停止时清空了 currentGenerationId，当前的 fillStepTask 仍能正确停止
  const fillTaskGenerationId = currentGenerationId.value
  const fillTaskTaskID = currentTaskID.value

  console.log('📋 开始填充步骤详情', {
    generationId: fillTaskGenerationId,
    TaskID: fillTaskTaskID,
    stepsCount: steps.length
  })

  // 串行填充所有步骤的详情
  try {
    for (const step of steps) {
      // 检查是否已停止
      if (!isFillingSteps.value || agentsStore.isStopping) {
        break
      }

      await withRetry(
        async () => {
          console.log(`📤 调用 fillStepTask: 步骤=${step.StepName}, TaskID=${fillTaskTaskID}`)
          const detailedStep = await api.fillStepTask({
            goal: searchValue.value,
            stepTask: {
              StepName: step.StepName,
              TaskContent: step.TaskContent,
              InputObject_List: step.InputObject_List,
              OutputObject: step.OutputObject,
              Id: step.Id // 传递步骤ID用于后端定位
            },
            generation_id: fillTaskGenerationId,
            TaskID: fillTaskTaskID // 后端数据库主键
          })
          console.log(`📥 fillStepTask 返回完成: 步骤=${step.StepName}`)
          updateStepDetail(step.StepName, detailedStep)
        },
        {
          maxRetries: 2, // 减少重试次数，因为是串行填充
          initialDelayMs: 1000, // 使用较小的延迟
          shouldRetry: () => isFillingSteps.value && !agentsStore.isStopping // 可取消的重试
        }
      )
    }
  } finally {
    // 重置状态（确保即使出错也会执行）
    triggerOnFocus.value = true
    if (isStopPending.value) {
      isStopping.value = false
      isStopPending.value = false
      agentsStore.setIsStopping(false)
      agentsStore.setHasStoppedFilling(true)
    }
    isFillingSteps.value = false
    currentStepAbortController.value = null
    // 只有在没有停止请求时才清空 generation_id
    if (!isStopPending.value) {
      currentGenerationId.value = ''
    }
  }
}

//更新单个步骤的详情
function updateStepDetail(stepId: string, detailedStep: any) {
  const planData = agentsStore.agentRawPlan.data
  if (!planData) return

  const collaborationProcess = planData['Collaboration Process']
  if (!collaborationProcess) return

  const index = collaborationProcess.findIndex((s: any) => s.StepName === stepId)
  if (index !== -1 && collaborationProcess[index]) {
    // 保持响应式更新
    Object.assign(collaborationProcess[index], {
      AgentSelection: detailedStep.AgentSelection || [],
      TaskProcess: detailedStep.TaskProcess || [],
      Collaboration_Brief_frontEnd: detailedStep.Collaboration_Brief_frontEnd || {
        template: '',
        data: {}
      }
    })
  }
}

const querySearch = (queryString: string, cb: (v: { value: string }[]) => void) => {
  const results = queryString
    ? configStore.config.taskPromptWords.filter(createFilter(queryString))
    : configStore.config.taskPromptWords
  // 调用回调函数返回建议列表
  cb(results.map(item => ({ value: item })))
}

const createFilter = (queryString: string) => {
  return (restaurant: string) => {
    return restaurant.toLowerCase().includes(queryString.toLowerCase())
  }
}

// 组件挂载时检查URL参数
onMounted(() => {
  autoSearchFromUrl()
  websocket.on('generation_stopped', onGenerationStopped)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  websocket.off('generation_stopped', onGenerationStopped)
})

// 打开历史记录弹窗
const openHistoryDialog = () => {
  emit('open-history')
}

// 从历史记录恢复任务
const restoreFromHistory = (plan: any) => {
  // 1. 设置搜索值为历史任务的目标
  searchValue.value = plan.general_goal

  // 3. 设置当前任务的 task_id（供分支保存使用）
  currentTaskID.value = plan.id || ''
  if (plan.id) {
    ;(window as any).__CURRENT_TASK_ID__ = plan.id
    console.log('♻️ [Task] 已设置 currentTaskID:', currentTaskID.value)
  }

  // 4. 设置分支初始化标记，告诉 PlanModification.vue 这是从历史记录恢复
  // 这样 initializeFlow 会走"恢复分支"逻辑，而不是"首次初始化"
  sessionStorage.setItem('plan-modification-branches-initialized', 'true')

  // 4. 保存完整的任务大纲数据
  currentPlanOutline.value = plan.task_outline || null

  // 4. 如果有 agents_info，更新到 store
  if (plan.agents_info && Array.isArray(plan.agents_info)) {
    agentsStore.setAgents(plan.agents_info)
  }

  // 5. 如果有智能体评分数据，更新到 store
  if (plan.agent_scores && currentPlanOutline.value) {
    const tasks = currentPlanOutline.value['Collaboration Process'] || []
    console.log(
      '🔍 [Task] 所有步骤名称:',
      tasks.map((t: any) => t.StepName)
    )
    console.log('🔍 [Task] agent_scores 的 key:', Object.keys(plan.agent_scores))

    for (const task of tasks) {
      // 使用 task.Id 作为 key
      const taskId = task.Id
      console.log(`🔍 [Task] 步骤使用 taskId: ${taskId}`)
      console.log(`🔍 [Task] plan.agent_scores[taskId] =`, plan.agent_scores[taskId])

      if (taskId && plan.agent_scores[taskId]) {
        const stepScores = plan.agent_scores[taskId]
        console.log(`✅ [Task] 找到步骤 ${taskId} 的评分数据`)

        // 后端返回格式: { aspectList: [...], agentScores: { "Agent1": { "Aspect1": {...} } } }
        // 解构获取 aspectList 和 agentScores
        const { aspectList, agentScores } = stepScores

        // agentScores 格式: { "Agent1": { "Aspect1": { score, reason } } }
        // 直接使用，无需转换（已经是前端期望的格式）
        console.log(`🔍 [Task] 步骤 ${taskId} 的 agentScores:`, agentScores)
        console.log(`🔍 [Task] 步骤 ${taskId} 的维度列表:`, aspectList)

        // 使用 taskId 作为 key 存储
        console.log(`🔍 [Task] 调用 setTaskScoreData: taskId=${taskId}`)
        agentsStore.setTaskScoreData(taskId, {
          aspectList,
          agentScores
        })
        console.log(`🔍 [Task] setTaskScoreData 完成，检查存储结果:`)
        const storedData = agentsStore.getTaskScoreData(taskId)
        console.log(`  taskId=${taskId} 的存储结果:`, storedData)
      } else {
        console.log(`❌ [Task] 未找到步骤 "${taskId}" 的评分数据，尝试用 StepName 查找`)
        // 兼容处理：如果找不到，尝试用 StepName
        const stepName = task.StepName
        if (stepName && plan.agent_scores[stepName]) {
          console.log(`✅ [Task] 兼容模式：使用 StepName ${stepName} 找到评分数据`)
          const stepScores = plan.agent_scores[stepName]
          // 后端返回格式: { aspectList: [...], agentScores: {...} }
          const { aspectList, agentScores } = stepScores
          agentsStore.setTaskScoreData(taskId, {
            aspectList,
            agentScores
          })
        }
      }
    }
  }

  // 6. 将完整的大纲数据设置到 store（跳过重新生成）
  if (currentPlanOutline.value) {
    agentsStore.setAgentRawPlan({
      data: currentPlanOutline.value,
      loading: false
    })
  }

  // 7. 如果有分支数据，恢复到 selection store
  if (plan.branches && Array.isArray(plan.branches)) {
    // 旧格式：数组，恢复任务大纲探索分支
    console.log('♻️ [Task] 恢复分支数据:', { count: plan.branches.length })
    selectionStore.restoreBranchesFromDB(plan.branches)
  } else if (plan.branches && typeof plan.branches === 'object') {
    // 新格式：对象，可能包含 flow_branches 和 task_process_branches
    // 恢复任务大纲探索分支
    if (plan.branches.flow_branches && Array.isArray(plan.branches.flow_branches)) {
      console.log('♻️ [Task] 恢复任务大纲探索分支:', { count: plan.branches.flow_branches.length })
      selectionStore.restoreBranchesFromDB(plan.branches.flow_branches)
    }

    // 恢复任务过程分支
    if (
      plan.branches.task_process_branches &&
      typeof plan.branches.task_process_branches === 'object'
    ) {
      console.log('♻️ [Task] 恢复任务过程分支:', {
        stepCount: Object.keys(plan.branches.task_process_branches).length
      })
      selectionStore.restoreTaskProcessBranchesFromDB(plan.branches.task_process_branches)
    }
  }

  // 8. 如果有 agent 组合数据，恢复到 selection store
  if (plan.assigned_agents && typeof plan.assigned_agents === 'object') {
    console.log('♻️ [Task] 恢复 agent 组合数据:', plan.assigned_agents)
    selectionStore.restoreAgentCombinationsFromDB(plan.assigned_agents, plan.id)
  }

  // 9. 如果有 rehearsal_log，恢复执行结果
  if (plan.rehearsal_log && Array.isArray(plan.rehearsal_log)) {
    console.log('♻️ [Task] 恢复执行结果:', { count: plan.rehearsal_log.length })
    // rehearsal_log 本身就是 IExecuteRawResponse 格式的数组
    agentsStore.setExecutePlan(plan.rehearsal_log)
  }

  // 10. 触发搜索事件
  emit('search', plan.general_goal)

  success('成功', '已恢复历史任务')
}

// 设置面板引用
const unifiedSettingsPanelRef = ref<InstanceType<typeof UnifiedSettingsPanel> | null>(null)

// 打开设置面板
const openSettingsPanel = () => {
  unifiedSettingsPanelRef.value?.open()
}

// 暴露给父组件
defineExpose({
  currentTaskID,
  openHistoryDialog,
  restoreFromHistory,
  openSettingsPanel
})
</script>

<template>
  <el-tooltip
    content="请先点击智能体库右侧的按钮上传智能体信息"
    placement="top"
    effect="light"
    :disabled="agentsStore.agents.length > 0"
  >
    <div class="task-root-container">
      <div
        class="task-container"
        ref="taskContainerRef"
        id="task-container"
        :class="{ expanded: isExpanded }"
      >
        <span class="text-[var(--color-text-task)] font-bold task-title">任务</span>
        <el-autocomplete
          ref="autocompleteRef"
          v-model.trim="searchValue"
          class="task-input"
          size="large"
          :rows="1"
          :autosize="{ minRows: 1, maxRows: 10 }"
          placeholder="请输入您的任务"
          type="textarea"
          :append-to="taskContainerRef"
          :fetch-suggestions="querySearch"
          @change="agentsStore.setSearchValue"
          :disabled="!(agentsStore.agents.length > 0)"
          :debounce="0"
          :clearable="true"
          :trigger-on-focus="triggerOnFocus"
          @focus="handleFocus"
          @blur="handleBlur"
          @select="isFocus = false"
        >
        </el-autocomplete>
        <el-button
          class="task-button"
          color="linear-gradient(to right, #00C7D2, #315AB4)"
          size="large"
          :title="isFillingSteps && !isStopping ? '点击停止生成' : '点击搜索任务'"
          circle
          :loading="agentsStore.agentRawPlan.loading || isStopping"
          :disabled="!searchValue || isStopping"
          @click.stop="handleButtonClick"
        >
          <SvgIcon
            v-if="!agentsStore.agentRawPlan.loading && !isFillingSteps && !isStopping"
            icon-class="paper-plane"
            size="18px"
            color="#ffffff"
          />
          <SvgIcon
            v-if="!agentsStore.agentRawPlan.loading && isFillingSteps && !isStopping"
            icon-class="stoprunning"
            size="30px"
            color="#ffffff"
          />
        </el-button>
      </div>
      <AssignmentButton v-if="planReady" @click="openAgentAllocationDialog" />
      <!-- 设置按钮 -->
      <el-button class="setting-button" circle title="设置" @click="openSettingsPanel">
        <el-icon size="18px"><Setting /></el-icon>
      </el-button>
      <!-- 统一设置面板 -->
      <UnifiedSettingsPanel ref="unifiedSettingsPanelRef" />
    </div>
  </el-tooltip>
</template>

<style scoped lang="scss">
.task-root-container {
  height: 60px;
  margin-bottom: 24px;
  position: relative;
}
.task-container {
  width: 40%;
  margin: 0 auto;
  border: 2px solid transparent;
  background: linear-gradient(var(--color-bg-taskbar), var(--color-bg-taskbar)) padding-box,
    linear-gradient(to right, #00c8d2, #315ab4) border-box;
  border-radius: 30px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  z-index: 998;
  min-height: 100%;
  overflow: hidden;
  padding: 0 55px 0 47px;
  transition: all 0.3s ease;

  /* 搜索框展开时的样式 */
  &.expanded {
    box-shadow: var(--color-task-shadow);
    :deep(.el-autocomplete .el-textarea .el-textarea__inner) {
      overflow-y: auto !important;
      min-height: 56px !important;
    }
  }

  /* 非展开状态时，确保文本区域高度固定 */
  &:not(.expanded) {
    :deep(.el-textarea__inner) {
      height: 56px !important;
      overflow-y: hidden !important;
      min-height: 56px !important;
    }
  }

  :deep(.el-popper) {
    position: static !important;
    width: calc(100% + 102px); /*增加左右padding的总和 */
    min-width: calc(100% + 102px); /* 确保最小宽度也增加 */
    margin-left: -47px; /* 向左偏移左padding的值 */
    margin-right: -55px; /*向右偏移右padding的值 */
    background: var(--color-bg-taskbar);
    border: none;
    transition: height 0s ease-in-out;
    border-top: 1px solid var(--color-border);
    border-radius: 0;
    box-shadow: none;

    li {
      height: 45px;
      box-sizing: border-box;
      line-height: 45px;
      font-size: 14px;
      padding-left: 27px;

      &:hover {
        background: var(--color-bg-hover);
        color: var(--color-text-hover);
      }
    }

    .el-popper__arrow {
      display: none;
    }
  }

  :deep(.el-autocomplete) {
    min-height: 56px;
    width: 100%;

    .task-input {
      height: 100%;
    }

    .el-textarea__inner {
      border-radius: 0;
      box-shadow: none;
      font-size: 14px;
      height: 100%;
      line-height: 1.5;
      padding: 18px 0 0 18px;
      resize: none;
      color: var(--color-text-taskbar);

      /* 聚焦时的样式 */
      .expanded & {
        overflow-y: auto;
      }

      &::placeholder {
        line-height: 1.2;
        font-size: 18px;
        vertical-align: middle;
      }

      .el-icon.is-loading {
        & + span {
          display: none;
        }
      }
    }
  }

  .task-title {
    position: absolute;
    top: 28px;
    left: 27px;
    z-index: 999;
    transform: translateY(-50%);
  }

  .task-button {
    background: linear-gradient(to right, #00c7d2, #315ab4);
    border: none; // 如果需要移除边框
    position: absolute;
    top: 28px;
    right: 10px;
    transform: translateY(-50%);
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0;
  }

  .task-button.is-loading {
    :deep(span) {
      display: none !important;
    }
  }
}

// 设置按钮
.setting-button {
  position: absolute;
  right: 70px;
  top: 28px;
  transform: translateY(-50%);
  z-index: 999;
  background: var(--color-bg-taskbar);
  border: 1px solid var(--color-border);
  color: var(--color-text-taskbar);

  &:hover {
    background: var(--color-bg-hover);
    color: var(--color-text-taskbar);
  }
}
</style>
