<template>
  <!-- 求职助手页面 -->
  <div class="agent-page dflex">
    <!-- 左侧导航栏 -->
    <SideNav />

    <!-- 主内容区域 -->
    <div class="agent-page__content" v-loading="pageLoading" element-loading-text="加载中...">
      <!-- 准备向导 — 第1步到第4步 -->
      <AgentSetupWizard
        v-if="!pageLoading && showSetupWizard"
        :initial-config="agentConfig"
        @complete="handleSetupComplete"
        @launch="handleLaunch"
      />

      <!-- 求职助手正式内容区域 -->
      <div v-else-if="!pageLoading" class="agent-main" :class="{ 'agent-main--with-panel': showRightPanel }">
        <!-- 左侧主区域 -->
        <div class="agent-main__left">
          <!-- 顶部固定设置栏 -->
          <div class="agent-main__top-bar">
            <!-- 用户头像 -->
            <div class="agent-main__avatar">
              <svg viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="8" r="4" stroke="currentColor" stroke-width="1.5" />
                <path d="M4 20c0-3.3 3.6-6 8-6s8 2.7 8 6" stroke="currentColor" stroke-width="1.5" />
              </svg>
            </div>
            <!-- 状态标签 -->
            <span class="agent-main__status-tag">准备就绪</span>
            <!-- 提示文字 -->
            <span class="agent-main__status-text">已添加一个岗位，随时可以开始投递</span>
            <!-- 开始按钮 -->
            <button class="agent-main__start-btn">开始 ▸</button>
            <!-- 右侧工具按钮 -->
            <div class="agent-main__tools">
              <!-- 设置按钮 -->
              <button class="agent-main__tool-btn" title="设置">
                <svg viewBox="0 0 24 24" fill="none">
                  <path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                </svg>
              </button>
              <!-- 齿轮按钮 -->
              <button class="agent-main__tool-btn" title="配置">
                <svg viewBox="0 0 24 24" fill="none">
                  <circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="1.5" />
                  <path d="M12 1v2m0 18v2m-9-11h2m18 0h2m-3.3-7.7-1.4 1.4M4.7 19.3l1.4-1.4m0-11.8L4.7 4.7m14.6 14.6-1.4-1.4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                </svg>
              </button>
            </div>
          </div>

          <!-- 中间聊天记录区域（可滚动） -->
          <div ref="chatAreaRef" class="agent-main__chat-area">
            <!-- 遍历对话消息列表 -->
            <template v-for="msg in chatMessages" :key="msg.id">
              <!-- 用户消息 — 右对齐 -->
              <div v-if="msg.type === 'user'" class="agent-main__chat-row agent-main__chat-row--user">
                <div class="agent-main__chat-bubble agent-main__chat-bubble--user">{{ msg.content }}</div>
              </div>

              <!-- AI 助手消息 — 左对齐 -->
              <div v-else-if="msg.type === 'assistant'" class="agent-main__chat-row">
                <div class="agent-main__chat-bubble">{{ msg.content }}</div>
              </div>

              <!-- 推荐岗位消息 — 渲染岗位列表组件 -->
              <div v-else-if="msg.type === 'recommend'" class="agent-main__chat-row">
                <!-- 如果 extra 里有岗位数据，用岗位列表组件展示 -->
                <AgentChatJobList
                  v-if="getRecommendJobsFromExtra(msg.extra).length > 0"
                  :summary="getRecommendSummaryFromExtra(msg.extra)"
                  :jobs="getRecommendJobsFromExtra(msg.extra)"
                  @view-all="handleOpenRecommendPanel(msg.id)"
                />
              </div>

              <!-- 投递进度消息 -->
              <div v-else-if="msg.type === 'apply_progress'" class="agent-main__chat-row">
                <div class="agent-main__chat-bubble">{{ msg.content }}</div>
              </div>
            </template>

            <!-- 会话岗位列表组件（来自推荐接口，非历史消息） -->

            <!-- AI 正在回复的加载指示器 -->
            <AiThinkingIndicator v-if="isSending" text="AI正在思考中" />
          </div>

          <!-- 底部固定输入框 -->
          <div class="agent-main__input-bar">
            <input
              v-model="chatInput"
              class="agent-main__input"
              placeholder="告诉我你想找什么样的工作"
              :disabled="isSending"
              @keyup.enter="handleSendMessage"
            />
            <button class="agent-main__send-btn" :disabled="isSending" @click="handleSendMessage">
              <svg viewBox="0 0 24 24" fill="none">
                <path d="M5 12h14M12 5l7 7-7 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
              </svg>
            </button>
          </div>
        </div>

        <!-- 右侧匹配岗位添加面板 -->
        <div v-if="showRightPanel" class="agent-main__right">
          <AgentMatchJobAdd
            :jobs="activeRecommendJobs"
            :loading-job-ids="loadingJobIds"
            :panel-loading="panelLoading"
            @close="handleCloseRecommendPanel"
            @view-more="handleViewMoreJobs"
            @toggle="handleToggleJobApply"
            @add-all="handleAddAllJobs"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import SideNav from '@/components/SideNav.vue'
import AgentSetupWizard from '@/components/AgentSetupWizard.vue'
import AgentChatJobList from '@/components/AgentChatJobList.vue'
import AgentMatchJobAdd from '@/components/AgentMatchJobAdd.vue'
import { fetchAgentConfig, saveAgentConfig, fetchAgentRecommend, fetchAgentChatMessages, addAgentChatMessage, applyJob, cancelApplyJob, fetchApplyByJobIds, sendAgentChat } from '@/api/agent'
import type { AgentConfig, AgentRecommendJob, AgentChatMessage, AgentChatHistoryItem } from '@/api/agent'
import { fetchApplyList } from '@/api/jobs'
import type { JobListItem } from '@/api/jobs'
import { fetchResumeList } from '@/api/resume'
import store from '@/stores'
import AiThinkingIndicator from '@/components/tools/AiThinkingIndicator.vue'

/** 页面初始加载状态 */
const pageLoading = ref(true)

/** 是否显示准备向导 */
const showSetupWizard = ref(true)

/** 从接口查询到的配置数据 — 传给向导组件做初始值 */
const agentConfig = ref<AgentConfig | null>(null)

/** 是否显示右侧匹配岗位面板 */
const showRightPanel = ref(false)

/** 当前右侧面板展示的 recommend 消息 ID */
const activeRecommendMsgId = ref<number | null>(null)

/** 对话消息列表 */
const chatMessages = ref<AgentChatMessage[]>([])

/** 根据当前选中的 recommend 消息 ID，解析其 extra 中的岗位列表 */
const activeRecommendJobs = computed(() => {
  if (activeRecommendMsgId.value === null) return [] as AgentRecommendJob[]
  const msg = chatMessages.value.find(m => m.id === activeRecommendMsgId.value)
  if (!msg || !msg.extra) return [] as AgentRecommendJob[]
  return getRecommendJobsFromExtra(msg.extra)
})

/** 聊天输入框内容 */
const chatInput = ref('')

/** 投递列表数据 */
const applyJobList = ref<JobListItem[]>([])

/** 正在请求中的岗位 ID 列表（传给子组件控制按钮 loading） */
const loadingJobIds = ref<number[]>([])

/** 右侧面板加载状态（查询投递记录期间显示 loading） */
const panelLoading = ref(false)

/** 默认简历 ID — 发送 AI 对话时需要（字符串避免大整数精度丢失） */
const defaultResumeId = ref('')

/** 是否正在发送消息（防止重复发送 + 显示等待状态） */
const isSending = ref(false)/** 聊天区域 DOM 引用 */
const chatAreaRef = ref<HTMLElement | null>(null)

/** 滚动聊天区域到底部（平滑滚动） */
function scrollChatToBottom() {
  if (chatAreaRef.value) {
    chatAreaRef.value.scrollTo({ top: chatAreaRef.value.scrollHeight, behavior: 'smooth' })
  }
}

/** 页面挂载时查询配置 */
onMounted(async () => {
  await loadAgentConfig()
})

/** 查询求职助手配置 */
async function loadAgentConfig() {
  pageLoading.value = true
  try {
    const res = await fetchAgentConfig()
    pageLoading.value = false
    if (res.code === '0' && res.data) {
      agentConfig.value = res.data
      /* 如果已启用（status=1），直接进入正式内容 */
      if (res.data.status === 1) {
        showSetupWizard.value = false
        await loadChatMessages()
        await loadApplyList()
        await loadDefaultResumeId()
        /* 没有历史消息时才自动请求推荐岗位 */
        if (chatMessages.value.length === 0) {
          await loadRecommendJobs()
        }
      }
    }
  } catch {
    console.error('[Agent] 查询求职助手配置失败')
  } finally {

  }
}

/** 加载推荐岗位列表 — 请求后将结果作为 recommend 消息存入对话记录 */
async function loadRecommendJobs() {
  try {
    const res = await fetchAgentRecommend()
    if (res.code === '0' && res.data && res.data.list?.length > 0) {
      const summary = res.data.summary || ''
      const jobList = res.data.list
      /* 将完整岗位数据序列化为 extra JSON */
      const extraJson = JSON.stringify({ summary, list: jobList })

      /* 调接口持久化这条 recommend 消息 */
      try {
        await addAgentChatMessage({
          type: 'recommend',
          content: '',
          extra: extraJson,
        })
      } catch {
        console.error('[Agent] 保存推荐消息失败')
      }

      /* 追加到本地对话消息列表 */
      const now = Math.floor(Date.now() / 1000)
      chatMessages.value.push({
        id: Date.now(),
        type: 'recommend',
        content: '',
        extra: extraJson,
        createTime: { seconds: now, nanos: 0 },
      })

      /* 滚动到底部 */
      await nextTick()
      scrollChatToBottom()
    }
  } catch {
    console.error('[Agent] 加载推荐岗位失败')
  }
}

/** 加载 Agent 对话消息列表 */
async function loadChatMessages() {
  try {
    const res = await fetchAgentChatMessages(50)
    if (res.code === '0' && res.data) {
      chatMessages.value = res.data
      /* 加载完成后滚动到底部 */
      await nextTick()
      scrollChatToBottom()
    }
  } catch {
    console.error('[Agent] 加载对话消息失败')
  }
}

/** 加载岗位投递列表 */
async function loadApplyList() {
  try {
    const res = await fetchApplyList({ pageNum: 1, pageSize: 100,status:0 })
    if (res.code === '0' && res.data) {
      applyJobList.value = res.data.list || []
    }
  } catch {
    console.error('[Agent] 加载投递列表失败')
  }
}

/** 加载默认简历 ID */
async function loadDefaultResumeId() {
  try {
    const res = await fetchResumeList()
    if (res.code === '0' && res.data && res.data.length > 0) {
      const defaultResume = res.data.find(r => r.isDefault === 1)
      const id = defaultResume?.id || res.data[0]?.id || ''
      defaultResumeId.value = id
    }
  } catch {
    console.error('[Agent] 加载默认简历失败')
  }
}

/**
 * 将 chatMessages 组装为 AI 对话接口需要的 history 格式
 * user / assistant → content 取 chatMessages.content
 * recommend / apply_progress → content 取 chatMessages.extra
 */
function buildChatHistory(): AgentChatHistoryItem[] {
  return chatMessages.value.map(msg => {
    const role = (msg.type === 'user') ? 'user' : 'assistant'
    let content = ''
    if (msg.type === 'user' || msg.type === 'assistant') {
      content = msg.content || ''
    } else {
      /* recommend / apply_progress — 用 extra 作为内容 */
      content = msg.extra || msg.content || ''
    }
    return { role, content }
  })
}

/**
 * 从 store 中获取意向岗位类型名称列表
 * 根据 jobIntention.categoryIds 在 jobCategories 树中查找名称
 */
function getIntentionCategoryNames(): string[] {
  const ids = store.state.jobIntention.categoryIds || []
  if (ids.length === 0) return []
  const names: string[] = []
  for (const group of store.state.jobCategories) {
    for (const child of group.children || []) {
      for (const leaf of child.children || []) {
        if (ids.includes(Number(leaf.id))) names.push(leaf.name)
      }
    }
  }
  return names
}

/**
 * 从 store 中获取意向城市名称列表
 * 根据 jobIntention.regionCodes 在 regions 树中查找名称
 */
function getIntentionRegionNames(): string[] {
  const codes = store.state.jobIntention.regionCodes || []
  if (codes.length === 0) return []
  const names: string[] = []
  for (const province of store.state.regions) {
    if (codes.includes(province.code)) { names.push(province.name); continue }
    for (const city of province.children || []) {
      if (codes.includes(city.code)) names.push(city.name)
    }
  }
  return names
}

/**
 * 从 store 中获取意向行业名称列表
 * 根据 jobIntention.industryIds 在 industries 树中查找名称
 */
function getIntentionIndustryNames(): string[] {
  const ids = store.state.jobIntention.industryIds || []
  if (ids.length === 0) return []
  const names: string[] = []
  for (const group of store.state.industries) {
    if (ids.includes(Number(group.id))) { names.push(group.name); continue }
    for (const child of group.children || []) {
      if (ids.includes(Number(child.id))) names.push(child.name)
    }
  }
  return names
}

/**
 * 从消息的 extra JSON 中解析推荐岗位列表
 * extra 格式预期为 JSON 字符串，包含 list 字段
 */
function getRecommendJobsFromExtra(extra: string): AgentRecommendJob[] {
  if (!extra) return []
  try {
    const parsed = JSON.parse(extra)
    return Array.isArray(parsed.list) ? parsed.list : (Array.isArray(parsed) ? parsed : [])
  } catch {
    return []
  }
}

/** 从消息的 extra JSON 中解析推荐说明文字 */
function getRecommendSummaryFromExtra(extra: string): string {
  if (!extra) return ''
  try {
    const parsed = JSON.parse(extra)
    return parsed.summary || ''
  } catch {
    return ''
  }
}

/**
 * 收集 chatMessages 中所有 recommend 消息里的岗位 ID
 * 返回字符串数组，避免大整数精度丢失
 */
function collectExcludeJobIds(): string[] {
  const ids: string[] = []
  for (const msg of chatMessages.value) {
    if (msg.type !== 'recommend' || !msg.extra) continue
    const jobs = getRecommendJobsFromExtra(msg.extra)
    for (const job of jobs) {
      ids.push(String(job.id))
    }
  }
  return ids
}

/** 准备向导设置完成 — 调用接口保存配置 */
async function handleSetupComplete(data: Record<string, any>) {
  try {
    await saveAgentConfig(data as AgentConfig)
    ElMessage.success('配置保存成功')
  } catch {
    ElMessage.error('配置保存失败，请重试')
  }
}

/** 启用求职助手 */
async function handleLaunch() {
  showSetupWizard.value = false
  ElMessage.success('求职助手已启用')
  /* 进入正式内容后加载对话消息和推荐岗位 */
  await loadChatMessages()
  await loadApplyList()
  await loadDefaultResumeId()
  /* 没有历史消息时才自动请求推荐岗位 */
  if (chatMessages.value.length === 0) {
    await loadRecommendJobs()
  }
}

/**
 * 更新对话消息中 recommend 消息里对应岗位的 applicationStatus
 */
function updateJobStatusInMessages(jobId: number, newStatus: number | null) {
  for (const msg of chatMessages.value) {
    if (msg.type !== 'recommend' || !msg.extra) continue
    try {
      const parsed = JSON.parse(msg.extra)
      const list: AgentRecommendJob[] = Array.isArray(parsed.list) ? parsed.list : (Array.isArray(parsed) ? parsed : [])
      const job = list.find(j => j.id === jobId)
      if (job) {
        job.applicationStatus = newStatus
        if (parsed.list) {
          parsed.list = list
          msg.extra = JSON.stringify(parsed)
        } else {
          msg.extra = JSON.stringify(list)
        }
      }
    } catch { /* 解析失败跳过 */ }
  }
}

/**
 * 单个岗位添加/移除 — 由子组件 toggle 事件触发
 * 未投递(null) → POST 添加到待投递(-1)
 * 待投递(-1) → DELETE 移除
 */
async function handleToggleJobApply(job: AgentRecommendJob) {
  if (loadingJobIds.value.includes(job.id)) return

  const isRemoving = job.applicationStatus === -1
  loadingJobIds.value.push(job.id)
  try {
    if (isRemoving) {
      await cancelApplyJob(job.id)
    } else {
      await applyJob({ jobId: job.id, status: -1 })
    }
    /* 更新对话消息中的岗位状态 */
    updateJobStatusInMessages(job.id, isRemoving ? null : -1)
    ElMessage.success(isRemoving ? '岗位已从待投递移除' : '岗位已添加到待投递')
  } catch {
    ElMessage.error('操作失败，请重试')
  } finally {
    loadingJobIds.value = loadingJobIds.value.filter(id => id !== job.id)
  }
}

/**
 * 全部添加 — 由子组件 addAll 事件触发
 * 将当前面板中所有未添加的岗位批量设为待投递
 */
async function handleAddAllJobs() {
  const pendingJobs = activeRecommendJobs.value.filter(j => j.applicationStatus === null || j.applicationStatus === undefined)
  if (pendingJobs.length === 0) {
    ElMessage.info('所有岗位已添加到待投递')
    return
  }
  for (const job of pendingJobs) {
    if (loadingJobIds.value.includes(job.id)) continue
    loadingJobIds.value.push(job.id)
    try {
      await applyJob({ jobId: job.id, status: -1 })
      updateJobStatusInMessages(job.id, -1)
    } catch { /* 单个失败不阻断后续 */ }
    finally {
      loadingJobIds.value = loadingJobIds.value.filter(id => id !== job.id)
    }
  }
  ElMessage.success('已全部添加到待投递')
}

/** 查看更多岗位 — 可扩展为加载下一批 */
function handleViewMoreJobs() {
  // TODO: 后续可对接分页加载更多岗位
}

/** 打开右侧匹配岗位面板 — 先查询投递记录更新岗位状态再显示 */
async function handleOpenRecommendPanel(msgId: number) {
  activeRecommendMsgId.value = msgId
  showRightPanel.value = true
  panelLoading.value = true

  try {
    /* 取出当前 recommend 消息中的岗位 ID 列表 */
    const msg = chatMessages.value.find(m => m.id === msgId)
    if (!msg || !msg.extra) return

    const jobs = getRecommendJobsFromExtra(msg.extra)
    const jobIds = jobs.map(j => j.id)
    if (jobIds.length === 0) return

    /* 调接口批量查询投递记录 */
    const res = await fetchApplyByJobIds(jobIds)
    if (res.code === '0' && res.data) {
      /* 构建 jobId → status 映射 */
      const statusMap = new Map<number, number>()
      for (const record of res.data) {
        statusMap.set(record.jobId, record.status)
      }
      /* 更新 extra 中每个岗位的 applicationStatus */
      const parsed = JSON.parse(msg.extra)
      const list: AgentRecommendJob[] = Array.isArray(parsed.list) ? parsed.list : (Array.isArray(parsed) ? parsed : [])
      for (const job of list) {
        if (statusMap.has(job.id)) {
          job.applicationStatus = statusMap.get(job.id)!
        } else {
          /* 接口没有返回该岗位记录 — 说明没有投递记录，设为 null */
          job.applicationStatus = null
        }
      }
      /* 回写 extra */
      if (parsed.list) {
        parsed.list = list
        msg.extra = JSON.stringify(parsed)
      } else {
        msg.extra = JSON.stringify(list)
      }
    }
  } catch {
    console.error('[Agent] 查询岗位投递记录失败')
  } finally {
    panelLoading.value = false
  }
}

/** 关闭右侧匹配岗位面板 */
function handleCloseRecommendPanel() {
  showRightPanel.value = false
  activeRecommendMsgId.value = null
}

/** 发送聊天消息 */
async function handleSendMessage() {
  const text = chatInput.value.trim()
  if (!text || isSending.value) return

  /* 1. 先把用户消息追加到 chatMessages */
  const now = Math.floor(Date.now() / 1000)
  const userMsg: AgentChatMessage = {
    id: Date.now(),
    type: 'user',
    content: text,
    extra: '',
    createTime: { seconds: now, nanos: 0 },
  }
  chatMessages.value.push(userMsg)
  chatInput.value = ''

  /* 滚动到底部 */
  await nextTick()
  scrollChatToBottom()

  /* 2. 同步持久化用户消息到后端 */
  try {
    await addAgentChatMessage({ type: 'user', content: text })
  } catch {
    console.error('[Agent] 保存用户消息失败')
  }

  /* 3. 组装参数调 AI 对话接口 */
  isSending.value = true

  /* 等待 loading 指示器渲染后滚动到底部 */
  await nextTick()
  scrollChatToBottom()

  try {
    const history = buildChatHistory()
    const res = await sendAgentChat({
      message: text,
      resumeId: defaultResumeId.value,
      history,
      jobCategories: getIntentionCategoryNames(),
      regions: getIntentionRegionNames(),
      industries: getIntentionIndustryNames(),
    })

    /* 处理 AI 回复 */
    if (res.code === 0 && res.data?.message) {
      const aiContent = res.data.message
      const tool = res.data.tool
      const toolParams = res.data.toolParams

      if (tool === 'recommend') {
        /* AI 要求推荐岗位 — 先插入 AI 的过渡消息 */
        const aiNow = Math.floor(Date.now() / 1000)
        chatMessages.value.push({
          id: Date.now() + 1,
          type: 'assistant',
          content: aiContent,
          extra: '',
          createTime: { seconds: aiNow, nanos: 0 },
        })
        try {
          await addAgentChatMessage({ type: 'assistant', content: aiContent })
        } catch { /* 静默 */ }

        await nextTick()
        scrollChatToBottom()

        /* 调用岗位推荐接口 */
        const preference = toolParams?.preference || ''
        const excludeJobIds = collectExcludeJobIds()
        try {
          const recRes = await fetchAgentRecommend({ preference, excludeJobIds })
          if (recRes.code === '0' && recRes.data && recRes.data.list?.length > 0) {
            const summary = recRes.data.summary || ''
            const jobList = recRes.data.list
            const extraJson = JSON.stringify({ summary, list: jobList })

            /* 持久化 recommend 消息 */
            try {
              await addAgentChatMessage({ type: 'recommend', content: '', extra: extraJson })
            } catch { /* 静默 */ }

            /* 追加到本地对话消息列表 */
            const recNow = Math.floor(Date.now() / 1000)
            chatMessages.value.push({
              id: Date.now() + 2,
              type: 'recommend',
              content: '',
              extra: extraJson,
              createTime: { seconds: recNow, nanos: 0 },
            })

            await nextTick()
            scrollChatToBottom()
          }
        } catch {
          console.error('[Agent] 推荐岗位请求失败')
        }
      } else {
        /* 普通 AI 回复 — 直接插入 assistant 消息 */
        const aiNow = Math.floor(Date.now() / 1000)
        chatMessages.value.push({
          id: Date.now() + 1,
          type: 'assistant',
          content: aiContent,
          extra: '',
          createTime: { seconds: aiNow, nanos: 0 },
        })

        try {
          await addAgentChatMessage({ type: 'assistant', content: aiContent })
        } catch {
          console.error('[Agent] 保存 AI 回复消息失败')
        }

        await nextTick()
        scrollChatToBottom()
      }
    }
  } catch (err) {
    console.error('[Agent] AI 对话请求失败', err)
    ElMessage.error('消息发送失败，请重试')
  } finally {
    isSending.value = false
  }
}
</script>

<style scoped lang="scss">
@use '../assets/styles/pages/agent';
</style>
