<template>
  <!-- 求职助手准备向导 — 第1步到第4步 -->
  <div class="agent-page__wizard">
    <!-- 个人资料编辑抽屉 -->
    <ProfileEditDrawer
      v-model="showEditDrawer"
      :module="editModule"
      :initial-data="editInitialData"
      @save="handleSaveEdit"
    />

    <!-- 顶部步骤导航条 -->
    <div class="agent-page__steps">
      <template v-for="(step, index) in steps" :key="index">
        <div
          class="agent-page__step"
          :class="{ 'agent-page__step--active': currentStep === index + 1 }"
        >
          <span class="agent-page__step-number">{{ index + 1 }}</span>
          <span class="agent-page__step-label">{{ step }}</span>
        </div>
        <span v-if="index < steps.length - 1" class="agent-page__step-arrow">
          <svg viewBox="0 0 16 16" fill="none">
            <path d="M6 4l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </span>
      </template>
    </div>

    <!-- 主体内容区域 -->
    <div class="agent-page__main">
      <!-- ========== 第1步：确认个人资料 ========== -->
      <template v-if="currentStep === 1">
        <div class="agent-page__left">
          <div class="agent-page__intro-card">
            <div class="agent-page__intro-header">
              <div class="agent-page__intro-icon">
                <svg viewBox="0 0 24 24" fill="none"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z" fill="currentColor"/></svg>
              </div>
              <h2 class="agent-page__intro-title">在开始之前请先确认你的个人资料是否无误</h2>
            </div>
            <p class="agent-page__intro-desc">请仔细对你的资料评估（包括个人信息、教育背景、工作履历及技能），确保资料齐全，让我能顺利为你开启求职之旅。</p>
            <div class="agent-page__import-row">
              <div class="agent-page__import-icon">
                <svg viewBox="0 0 24 24" fill="none"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 2v6h6M16 13H8M16 17H8M10 9H8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
              </div>
              <span class="agent-page__import-text">{{ profile.name }}的个人资料</span>
            </div>
            <div class="dflex-center aliite-c">
              <button class="agent-page__confirm-btn" @click="handleNext">确认并进入</button>
            </div>
          </div>
        </div>
        <div class="agent-page__right">
          <div class="agent-page__profile-wrapper">
            <div class="agent-page__profile-title">个人档案</div>
            <ProfilePageContent :profile="profile" @edit="handleEdit" />
          </div>
        </div>
      </template>

      <!-- ========== 第2步：确认目标 ========== -->
      <template v-if="currentStep === 2">
        <div class="agent-page__step2">
          <div class="agent-page__chat">
            <div class="agent-page__chat-row">
              <div class="agent-page__chat-avatar"><svg viewBox="0 0 24 24" fill="none"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z" fill="currentColor"/></svg></div>
              <span class="agent-page__chat-text">接下来，我想确认一下我为你搜寻的职位方向是否准确。</span>
            </div>
            <div class="p20 bg-f border-ra10">
              <div class="agent-page__pref-card">
                <p class="agent-page__pref-desc">这些是你之前设定的求职偏好。如有需要，请随时修改。</p>
                <div class="agent-page__pref-tags">
                  <span v-for="name in intentionCategoryNames" :key="'cat-' + name" class="agent-page__pref-tag">{{ name }}</span>
                  <span v-for="name in intentionIndustryNames" :key="'ind-' + name" class="agent-page__pref-tag">{{ name }}</span>
                  <span v-for="name in intentionRegionNames" :key="'reg-' + name" class="agent-page__pref-tag">{{ name }}</span>
                  <span class="agent-page__pref-tag">{{ intentionEmploymentLabel }}</span>
                </div>
                <div class="agent-page__pref-actions">
                  <button class="agent-page__pref-btn agent-page__pref-btn--edit" @click="showJobGoalDialog = true">编辑</button>
                  <button class="agent-page__pref-btn agent-page__pref-btn--confirm" @click="handleNext">确认并继续</button>
                </div>
              </div>
            </div>
            <div v-if="loadingMatchJobs" class="agent-page__chat-row">
              <div class="agent-page__chat-avatar"><svg viewBox="0 0 24 24" fill="none"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z" fill="currentColor"/></svg></div>
              <div class="agent-page__chat-typing"><span></span><span></span><span></span></div>
            </div>
            <div v-if="matchedJobs.length > 0" class="p20 bg-f border-ra10">
              <div class="agent-page__match-card">
                <p class="agent-page__match-desc">这些是为你匹配的岗位，请选择你想投递的岗位，如对某个岗位不满意请告诉我。</p>
                <div v-for="(job, i) in matchedJobs" :key="i" class="agent-page__match-item">
                  <div class="agent-page__match-info">
                    <div class="agent-page__match-icon"><svg viewBox="0 0 24 24" fill="none"><path d="M3 21h18M3 7v14M9 3v4M15 3v4M9 3h6M5 7h14a2 2 0 012 2v10H3V9a2 2 0 012-2z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg></div>
                    <div class="agent-page__match-detail">
                      <div class="agent-page__match-company">{{ job.companyShortName || job.companyName }}</div>
                      <div class="agent-page__match-position">{{ job.title }}</div>
                      <div class="agent-page__match-tags"><span v-for="(t, j) in job.tags" :key="j" class="agent-page__match-tag">{{ t }}</span></div>
                    </div>
                  </div>
                  <div class="agent-page__match-score">
                    <svg viewBox="0 0 40 40" class="agent-page__match-ring"><circle cx="20" cy="20" r="16" fill="none" stroke="#E8E8E8" stroke-width="3"/><circle cx="20" cy="20" r="16" fill="none" stroke="#000" stroke-width="3" :stroke-dasharray="100.53" :stroke-dashoffset="100.53 * (1 - job.matchScore / 100)" stroke-linecap="round" transform="rotate(-90 20 20)"/></svg>
                    <span class="agent-page__match-score-text">{{ job.matchScore }}%</span>
                  </div>
                  <div class="agent-page__match-feedback">
                    <button class="agent-page__match-fb-btn" :class="{ 'agent-page__match-fb-btn--active': job.feedback === 'like' }" @click="job.feedback = job.feedback === 'like' ? '' : 'like'"><svg viewBox="0 0 24 24" fill="none"><path d="M7 22V11l5-9 1.5 1 -1 5h6.5a2 2 0 012 2.2l-1.5 8A2 2 0 0117.6 20H7z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><path d="M4 11H2v11h2a1 1 0 001-1V12a1 1 0 00-1-1z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/></svg></button>
                    <button class="agent-page__match-fb-btn" :class="{ 'agent-page__match-fb-btn--active': job.feedback === 'dislike' }" @click="handleDislike(i)"><svg viewBox="0 0 24 24" fill="none"><path d="M17 2v11l-5 9-1.5-1 1-5H5a2 2 0 01-2-2.2l1.5-8A2 2 0 016.4 4H17z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><path d="M20 13h2V2h-2a1 1 0 00-1 1v9a1 1 0 001 1z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/></svg></button>
                  </div>
                </div>
                <div v-if="showDislikeInput" class="agent-page__dislike-input"><input v-model="dislikeReason" type="text" placeholder="你为什么对这个岗位不满意？" /></div>
              </div>
            </div>
            <div v-if="matchedJobs.length > 0" class="agent-page__step2-footer"><button class="agent-page__optimize-btn" @click="loadMatchedJobs">优化我的岗位匹配</button></div>
          </div>
        </div>
      </template>

      <!-- ========== 第3步：网申常见问题 + 插件安装 ========== -->
      <template v-if="currentStep === 3">
        <!-- 上半部分：网申常见问题 -->
        <div v-if="step3Sub === 1" class="agent-page__step3">
          <div class="agent-page__left">
            <div class="agent-page__intro-card">
              <div class="agent-page__intro-header"><div class="agent-page__intro-icon"><svg viewBox="0 0 24 24" fill="none"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z" fill="currentColor"/></svg></div><h2 class="agent-page__intro-title">现在我们来开启自动投递吧</h2></div>
              <p class="agent-page__intro-desc">以下是校招网申常见填写信息。<br/>现在填写一次，我即可在自动申请时帮你填写信息。</p>
              <div class="dflex-center aliite-c"><button class="agent-page__confirm-btn" @click="step3Sub = 2">确认并继续</button></div>
            </div>
          </div>
          <div class="agent-page__right">
            <div class="agent-page__form-wrapper">
              <div class="agent-page__form-title">网申常见问题</div>
              <div class="agent-page__form-group"><div class="agent-page__form-label">是否愿意接受部门调剂？</div><div class="agent-page__form-options"><button class="agent-page__form-option" :class="{ 'agent-page__form-option--active': step3Form.acceptDeptTransfer === '是，服从调剂' }" @click="step3Form.acceptDeptTransfer = '是，服从调剂'">是，服从调剂</button><button class="agent-page__form-option" :class="{ 'agent-page__form-option--active': step3Form.acceptDeptTransfer === '否，不调剂' }" @click="step3Form.acceptDeptTransfer = '否，不调剂'">否，不调剂</button></div></div>
              <div class="agent-page__form-group"><div class="agent-page__form-label">是否接受地点调剂？</div><div class="agent-page__form-options"><button class="agent-page__form-option" :class="{ 'agent-page__form-option--active': step3Form.acceptLocationTransfer === '是' }" @click="step3Form.acceptLocationTransfer = '是'">是</button><button class="agent-page__form-option" :class="{ 'agent-page__form-option--active': step3Form.acceptLocationTransfer === '否' }" @click="step3Form.acceptLocationTransfer = '否'">否</button></div></div>
              <div class="agent-page__form-group"><div class="agent-page__form-label">可以参加面试的方式？</div><div class="agent-page__form-options"><button class="agent-page__form-option" :class="{ 'agent-page__form-option--active': step3Form.interviewType.includes('线下面试') }" @click="toggleInterviewType('线下面试')">线下面试</button><button class="agent-page__form-option" :class="{ 'agent-page__form-option--active': step3Form.interviewType.includes('线上远程') }" @click="toggleInterviewType('线上远程')">线上远程</button></div></div>
              <div class="agent-page__form-group"><div class="agent-page__form-label">你的语言能力？</div><div class="agent-page__form-selects"><el-select v-model="step3Form.languages[0].language" placeholder="语种" class="agent-page__form-select"><el-option v-for="lang in languageOptions" :key="lang" :label="lang" :value="lang" /></el-select><el-select v-model="step3Form.languages[0].proficiency" placeholder="掌握程度" class="agent-page__form-select"><el-option v-for="p in proficiencyOptions" :key="p" :label="p" :value="p" /></el-select></div></div>
              <div class="agent-page__form-group"><div class="agent-page__form-label">预计到岗时间？</div><div class="agent-page__form-selects"><el-select v-model="step3Form.availableDate" placeholder="请选择" class="agent-page__form-select"><el-option v-for="d in availableDateOptions" :key="d" :label="d" :value="d" /></el-select></div></div>
              <template v-if="isInternship">
                <div class="agent-page__form-group"><div class="agent-page__form-label">每周可实习天数？</div><div class="agent-page__form-selects"><el-select v-model="step3Form.internDaysPerWeek" placeholder="请选择" class="agent-page__form-select"><el-option v-for="d in internDaysOptions" :key="d" :label="d" :value="d" /></el-select></div></div>
                <div class="agent-page__form-group"><div class="agent-page__form-label">预计实习时长？</div><div class="agent-page__form-selects"><el-select v-model="step3Form.internDuration" placeholder="请选择" class="agent-page__form-select"><el-option v-for="d in internDurationOptions" :key="d" :label="d" :value="d" /></el-select></div></div>
              </template>
            </div>
          </div>
        </div>
        <!-- 下半部分：插件安装 -->
        <div v-if="step3Sub === 2" class="agent-page__step3">
          <div class="agent-page__left">
            <div class="agent-page__intro-card">
              <div class="agent-page__intro-header"><div class="agent-page__intro-icon"><svg viewBox="0 0 24 24" fill="none"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z" fill="currentColor"/></svg></div><h2 class="agent-page__intro-title">现在我们来开启自动投递吧</h2></div>
              <p class="agent-page__intro-desc">简单三步安装 Chrome 扩展程序<br/>实现自动填表，并一站式追踪所有申请进度。</p>
              <div class="agent-page__install-steps"><p>1. 点击 [ 安装扩展程序 ]，前往 Chrome 应用商店。</p><p>2. 点击 "添加至 Chrome" 并完成安装。</p><p>3. 刷新本页，然后点击下方按钮完成同步。</p></div>
              <div class="dflex-center aliite-c"><button class="agent-page__confirm-btn" @click="handleNext">我已安装</button></div>
            </div>
          </div>
          <div class="agent-page__right">
            <div class="agent-page__form-wrapper">
              <div class="agent-page__form-title">自动填写插件</div>
              <div class="agent-page__plugin-section">
                <h3 class="agent-page__plugin-title">自动填写插件</h3>
                <div class="agent-page__browser-btns"><button v-for="b in browserList" :key="b.key" class="agent-page__browser-btn" @click="openBrowserGuide(b.key)">{{ b.label }}</button></div>
                <div class="dflex-center aliite-c" style="margin-top: 0.24rem;"><button class="agent-page__confirm-btn" @click="downloadExtension">下载插件</button></div>
              </div>
            </div>
          </div>
        </div>
        <!-- 浏览器安装指引弹窗 -->
        <el-dialog v-model="showBrowserGuide" :title="currentBrowserLabel + ' 安装指引'" width="80%" top="5vh" destroy-on-close>
          <el-carousel :autoplay="false" indicator-position="outside" height="70vh" arrow="always">
            <el-carousel-item v-for="(img, i) in currentBrowserImages" :key="i"><div class="agent-page__guide-slide"><img :src="img" :alt="currentBrowserLabel + ' 安装步骤 ' + (i + 1)" /></div></el-carousel-item>
          </el-carousel>
        </el-dialog>
      </template>

      <!-- ========== 第4步：配置求职助手 ========== -->
      <template v-if="currentStep === 4">
        <div v-if="!setupComplete" class="agent-page__step3">
          <div class="agent-page__left">
            <div class="agent-page__intro-card">
              <div class="agent-page__intro-header"><div class="agent-page__intro-icon"><svg viewBox="0 0 24 24" fill="none"><path d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v2h20v-2c0-3.3-6.7-5-10-5z" fill="currentColor"/></svg></div><h2 class="agent-page__intro-title">马上就好啦！请选择你想要的投递模式</h2></div>
              <p class="agent-page__intro-desc">我已为你准备了关于自动化程度、简历生成及求职目标的灵活选项。请完成配置并确认。</p>
              <div class="dflex-center aliite-c"><button class="agent-page__confirm-btn" @click="handleStep4Complete">设置完成</button></div>
            </div>
          </div>
          <div class="agent-page__right">
            <div class="agent-page__form-wrapper">
              <div class="agent-page__form-title">Agent设置</div>
              <AgentSettingsPanel ref="settingsPanelRef" :initial-config="initialConfig" />
            </div>
          </div>
        </div>
        <div v-else class="agent-page__complete">
          <div class="agent-page__complete-icon"><svg viewBox="0 0 80 80" fill="none"><rect x="8" y="8" width="64" height="64" rx="8" fill="#E8E8E8"/><circle cx="40" cy="32" r="8" fill="#BFBFBF"/><path d="M20 60 L32 44 L44 52 L56 36 L64 44 L64 64 L20 64Z" fill="#BFBFBF"/></svg></div>
          <h2 class="agent-page__complete-title">恭喜你！你的求职助手已经准备好。</h2>
          <p class="agent-page__complete-desc">启用求职助手后你可以随时调整求职偏好及简历信息。</p>
          <button class="agent-page__complete-btn" @click="handleLaunchAgent">启用求职助手开始投递</button>
        </div>
      </template>
    </div>

    <!-- 求职目标设置弹窗 -->
    <JobGoalDialog v-model="showJobGoalDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useStore } from 'vuex'
import ProfilePageContent from '@/components/ProfilePageContent.vue'
import ProfileEditDrawer from '@/components/ProfileEditDrawer.vue'
import JobGoalDialog from '@/components/JobGoalDialog.vue'
import AgentSettingsPanel from '@/components/AgentSettingsPanel.vue'
import { saveProfile, saveEducation, saveWork, saveInternship, saveProject, saveCompetition, fetchProfile, fetchEducation, fetchWork, fetchInternship, fetchProject, fetchCompetition } from '@/api/profile'
import type { SaveEducationItem, SaveWorkItem, SaveProjectItem, SaveCompetitionItem } from '@/api/profile'
import { fetchJobList } from '@/api/jobs'
import type { JobListItem } from '@/api/jobs'
import { resolveRegionName } from '@/utils/region'
import { resolveIndustryName } from '@/utils/industry'
import { resolveJobCategoryName } from '@/utils/jobCategory'
import type { AgentConfig } from '@/api/agent'

const store = useStore()

/** 组件 Props — 接收父组件传入的初始配置数据 */
const props = defineProps<{
  /** 从接口查询到的初始配置，可能为空 */
  initialConfig?: AgentConfig | null
}>()

/** 组件事件 — complete: 设置完成时传回完整配置数据；launch: 点击启用按钮 */
const emit = defineEmits<{
  (e: 'complete', data: Record<string, any>): void
  (e: 'launch'): void
}>()

// ==================== 步骤导航 ====================
const steps = ['确认个人资料', '确认目标', '开启自动申请', '配置求职助手']
const currentStep = ref(1)

/** 进入下一步 */
function handleNext() {
  if (currentStep.value < steps.length) currentStep.value++
}

// ==================== 编辑抽屉状态 ====================
const showEditDrawer = ref(false)
const editModule = ref('info')
const editInitialData = ref<Record<string, any>>({})

// ==================== 个人档案数据 ====================
onMounted(async () => {
  if (!store.state.regions.length) store.dispatch('loadCommonData')
  store.dispatch('loadJobIntention')
  await loadProfile()
  await loadEducation()
  await loadWork()
  await loadInternship()
  await loadProject()
  await loadCompetition()
})

async function loadProfile() {
  try {
    const res = await fetchProfile()
    if (res.code === '0' && res.data) {
      const d = res.data
      profile.value.name = d.name || ''; profile.value.phone = d.mobileNumber || ''
      profile.value.email = d.email || ''; profile.value.idNumber = d.idCard || ''
      profile.value.regionCode = d.regionCode || ''; profile.value.wechat = d.wechatNumber || ''
      profile.value.skills = d.skills || []; profile.value.certificates = d.certificates || []
      profile.value.portfolioUrl = d.portfolioUrl || ''
    }
  } catch { console.error('[AgentSetupWizard] 加载个人资料失败') }
}
async function loadEducation() {
  try {
    const res = await fetchEducation()
    if (res.code === '0' && res.data) {
      profile.value.education = res.data.map(item => ({ school: item.school || '', major: item.major || '', studyType: item.studyType ?? 0, degree: item.degree ?? 2, startDate: item.startDate || '', endDate: item.endDate || '', description: (item.description || []).map(d => ({ id: d.id || '', text: d.text || '' })) }))
    }
  } catch { console.error('[AgentSetupWizard] 加载教育经历失败') }
}
async function loadWork() {
  try {
    const res = await fetchWork()
    if (res.code === '0' && res.data) {
      profile.value.works = res.data.map(item => ({ companyName: item.companyName || '', position: item.position || '', startDate: item.startDate || '', endDate: item.endDate || '', description: (item.description || []).map(d => ({ id: d.id || '', text: d.text || '' })) }))
    }
  } catch { console.error('[AgentSetupWizard] 加载工作经历失败') }
}
async function loadInternship() {
  try {
    const res = await fetchInternship()
    if (res.code === '0' && res.data) {
      profile.value.internships = res.data.map(item => ({ companyName: item.companyName || '', position: item.position || '', startDate: item.startDate || '', endDate: item.endDate || '', description: (item.description || []).map(d => ({ id: d.id || '', text: d.text || '' })) }))
    }
  } catch { console.error('[AgentSetupWizard] 加载实习经历失败') }
}
async function loadProject() {
  try {
    const res = await fetchProject()
    if (res.code === '0' && res.data) {
      profile.value.projects = res.data.map(item => ({ projectName: item.projectName || '', companyName: item.companyName || '', role: item.role || '', startDate: item.startDate || '', endDate: item.endDate || '', description: (item.description || []).map(d => ({ id: d.id || '', text: d.text || '' })) }))
    }
  } catch { console.error('[AgentSetupWizard] 加载项目经历失败') }
}
async function loadCompetition() {
  try {
    const res = await fetchCompetition()
    if (res.code === '0' && res.data) {
      profile.value.competitions = res.data.map(item => ({ competitionName: item.competitionName || '', award: item.award || '', awardDate: item.awardDate || '', description: (item.description || []).map(d => ({ id: d.id || '', text: d.text || '' })) }))
    }
  } catch { console.error('[AgentSetupWizard] 加载竞赛经历失败') }
}

const profile = ref({
  name: '', phone: '', email: '', idNumber: '', regionCode: '', portfolioUrl: '', wechat: '',
  skills: [] as string[], certificates: [] as string[],
  education: [] as Array<{ school: string; major: string; studyType: number; degree: number; startDate: string; endDate: string; description: Array<{ id: string; text: string }> }>,
  works: [] as Array<{ companyName: string; position: string; startDate: string; endDate: string; description: Array<{ id: string; text: string }> }>,
  internships: [] as Array<{ companyName: string; position: string; startDate: string; endDate: string; description: Array<{ id: string; text: string }> }>,
  projects: [] as Array<{ projectName: string; companyName: string; role: string; startDate: string; endDate: string; description: Array<{ id: string; text: string }> }>,
  competitions: [] as Array<{ competitionName: string; award: string; awardDate: string; description: Array<{ id: string; text: string }> }>,
})

// ==================== 编辑抽屉事件处理 ====================
function handleEdit(section: string) {
  editModule.value = section
  if (section === 'info') { editInitialData.value = { name: profile.value.name, email: profile.value.email, phone: profile.value.phone, location: profile.value.regionCode, wechat: profile.value.wechat } }
  else if (section === 'education') { editInitialData.value = { education: profile.value.education.map(edu => ({ ...edu, description: edu.description.map(d => ({ ...d })) })) } }
  else if (section === 'work') { editInitialData.value = { works: profile.value.works.map(exp => ({ ...exp, description: exp.description.map(d => ({ ...d })) })) } }
  else if (section === 'internship') { editInitialData.value = { internships: (profile.value.internships || []).map(exp => ({ ...exp, description: exp.description.map(d => ({ ...d })) })) } }
  else if (section === 'project') { editInitialData.value = { projects: (profile.value.projects || []).map(proj => ({ ...proj, description: proj.description.map(d => ({ ...d })) })) } }
  else if (section === 'competition') { editInitialData.value = { competitions: profile.value.competitions.map(comp => ({ ...comp, description: comp.description.map(d => ({ ...d })) })) } }
  else if (section === 'portfolio') { editInitialData.value = { portfolioUrl: profile.value.portfolioUrl } }
  else if (section === 'skills') { editInitialData.value = { skills: [...profile.value.skills] } }
  else if (section === 'certificate') { editInitialData.value = { certificates: [...(profile.value.certificates || [])] } }
  else { editInitialData.value = {} }
  showEditDrawer.value = true
}

/** 保存中的加载状态 */
const saving = ref(false)

/** 保存编辑数据 — 调用接口持久化 */
async function handleSaveEdit(data: Record<string, any>) {
  if (editModule.value === 'info') {
    try { saving.value = true; await saveProfile({ name: data.name, email: data.email, mobileNumber: data.phone, regionCode: data.location, wechatNumber: data.wechat }); profile.value.name = data.name; profile.value.email = data.email; profile.value.phone = data.phone; profile.value.wechat = data.wechat; profile.value.regionCode = data.location || ''; ElMessage.success('个人信息保存成功') } catch { ElMessage.error('个人信息保存失败，请重试') } finally { saving.value = false }
  } else if (editModule.value === 'education') {
    try { saving.value = true; const payload: SaveEducationItem[] = data.education.map((edu: any) => ({ school: edu.school, major: edu.major, degree: edu.degree, studyType: edu.studyType, startDate: edu.startDate, endDate: edu.endDate, description: edu.description.map((d: any) => ({ id: d.id, text: d.text })) })); await saveEducation(payload); profile.value.education = data.education.map((edu: any) => ({ school: edu.school, major: edu.major, studyType: edu.studyType, degree: edu.degree, startDate: edu.startDate, endDate: edu.endDate, description: edu.description.map((d: any) => ({ ...d })) })); ElMessage.success('教育经历保存成功') } catch { ElMessage.error('教育经历保存失败，请重试') } finally { saving.value = false }
  } else if (editModule.value === 'work') {
    try { saving.value = true; const payload: SaveWorkItem[] = data.works.map((w: any) => ({ companyName: w.companyName, position: w.position, startDate: w.startDate, endDate: w.endDate || '', description: w.description.map((d: any) => ({ id: d.id, text: d.text })) })); await saveWork(payload); profile.value.works = data.works.map((w: any) => ({ companyName: w.companyName, position: w.position, startDate: w.startDate, endDate: w.endDate, description: w.description.map((d: any) => ({ ...d })) })); ElMessage.success('工作经历保存成功') } catch { ElMessage.error('工作经历保存失败，请重试') } finally { saving.value = false }
  } else if (editModule.value === 'internship') {
    try { saving.value = true; const payload: SaveWorkItem[] = data.internships.map((i: any) => ({ companyName: i.companyName, position: i.position, startDate: i.startDate, endDate: i.endDate || '', description: i.description.map((d: any) => ({ id: d.id, text: d.text })) })); await saveInternship(payload); profile.value.internships = data.internships.map((i: any) => ({ companyName: i.companyName, position: i.position, startDate: i.startDate, endDate: i.endDate, description: i.description.map((d: any) => ({ ...d })) })); ElMessage.success('实习经历保存成功') } catch { ElMessage.error('实习经历保存失败，请重试') } finally { saving.value = false }
  } else if (editModule.value === 'project') {
    try { saving.value = true; const payload: SaveProjectItem[] = data.projects.map((p: any) => ({ projectName: p.projectName, companyName: p.companyName || '', role: p.role || '', startDate: p.startDate, endDate: p.endDate || '', description: p.description.map((d: any) => ({ id: d.id, text: d.text })) })); await saveProject(payload); profile.value.projects = data.projects.map((p: any) => ({ projectName: p.projectName, companyName: p.companyName, role: p.role, startDate: p.startDate, endDate: p.endDate, description: p.description.map((d: any) => ({ ...d })) })); ElMessage.success('项目经历保存成功') } catch { ElMessage.error('项目经历保存失败，请重试') } finally { saving.value = false }
  } else if (editModule.value === 'competition') {
    try { saving.value = true; const payload: SaveCompetitionItem[] = data.competitions.map((c: any) => ({ competitionName: c.competitionName, award: c.award || '', awardDate: c.awardDate || '', description: c.description.map((d: any) => ({ id: d.id, text: d.text })) })); await saveCompetition(payload); profile.value.competitions = data.competitions.map((c: any) => ({ competitionName: c.competitionName, award: c.award, awardDate: c.awardDate, description: c.description.map((d: any) => ({ ...d })) })); ElMessage.success('竞赛经历保存成功') } catch { ElMessage.error('竞赛经历保存失败，请重试') } finally { saving.value = false }
  } else if (editModule.value === 'portfolio') {
    try { saving.value = true; await saveProfile({ name: profile.value.name, email: profile.value.email, mobileNumber: profile.value.phone, regionCode: profile.value.regionCode, wechatNumber: profile.value.wechat, skills: profile.value.skills, certificates: profile.value.certificates, portfolioUrl: data.portfolioUrl }); profile.value.portfolioUrl = data.portfolioUrl; ElMessage.success('作品集保存成功') } catch { ElMessage.error('作品集保存失败，请重试') } finally { saving.value = false }
  } else if (editModule.value === 'skills') {
    try { saving.value = true; await saveProfile({ name: profile.value.name, email: profile.value.email, mobileNumber: profile.value.phone, regionCode: profile.value.regionCode, wechatNumber: profile.value.wechat, skills: [...data.skills], certificates: profile.value.certificates }); profile.value.skills = [...data.skills]; ElMessage.success('技能保存成功') } catch { ElMessage.error('技能保存失败，请重试') } finally { saving.value = false }
  } else if (editModule.value === 'certificate') {
    try { saving.value = true; await saveProfile({ name: profile.value.name, email: profile.value.email, mobileNumber: profile.value.phone, regionCode: profile.value.regionCode, wechatNumber: profile.value.wechat, skills: profile.value.skills, certificates: [...data.certificates] }); profile.value.certificates = [...data.certificates]; ElMessage.success('证书保存成功') } catch { ElMessage.error('证书保存失败，请重试') } finally { saving.value = false }
  }
}

// ==================== 第2步：确认目标 ====================
const showJobGoalDialog = ref(false)
const intentionCategoryNames = computed(() => (store.state.jobIntention.categoryIds || []).map((id: number) => resolveJobCategoryName(id)))
const intentionIndustryNames = computed(() => (store.state.jobIntention.industryIds || []).map((id: number) => resolveIndustryName(id)))
const intentionRegionNames = computed(() => (store.state.jobIntention.regionCodes || []).map((code: string) => resolveRegionName(code)))
const intentionEmploymentLabel = computed(() => store.state.jobIntention.employmentType === 1 ? '实习' : '全职')

interface MatchedJobItem extends JobListItem { feedback: string }
const matchedJobs = ref<MatchedJobItem[]>([])
const loadingMatchJobs = ref(false)
const showDislikeInput = ref(false)
const dislikeReason = ref('')

watch(showJobGoalDialog, (n, o) => { if (o === true && n === false) loadMatchedJobs() })
watch(currentStep, (val) => { if (val === 2) loadMatchedJobs() })

async function loadMatchedJobs() {
  loadingMatchJobs.value = true; matchedJobs.value = []
  try {
    const intention = store.state.jobIntention
    const res = await fetchJobList({ pageNum: 1, pageSize: 30, regionCodes: intention.regionCodes?.length ? intention.regionCodes : undefined, categoryIds: intention.categoryIds?.length ? intention.categoryIds : undefined, industryIds: intention.industryIds?.length ? intention.industryIds : undefined, employmentType: intention.employmentType ?? undefined })
    if (res.code === '0' && res.data && res.data.list.length > 0) {
      const shuffled = [...res.data.list].sort(() => Math.random() - 0.5)
      matchedJobs.value = shuffled.slice(0, 3).map(item => ({ ...item, feedback: '' }))
    }
  } catch (e) { console.error('[AgentSetupWizard] 加载匹配岗位失败', e) }
  finally { loadingMatchJobs.value = false }
}

function handleDislike(index: number) {
  const job = matchedJobs.value[index]
  if (job.feedback === 'dislike') { job.feedback = ''; showDislikeInput.value = false }
  else { job.feedback = 'dislike'; showDislikeInput.value = true }
}

// ==================== 第3步：网申常见问题 ====================
const isInternship = computed(() => store.state.jobIntention.employmentType === 1)
const step3Sub = ref(1)
const step3Form = reactive({
  acceptDeptTransfer: '', acceptLocationTransfer: '',
  interviewType: [] as string[],
  languages: [{ language: '', proficiency: '' }] as Array<{ language: string; proficiency: string }>,
  availableDate: '', internDaysPerWeek: '', internDuration: '',
})

/** 监听初始配置数据 — 填充第3步表单 */
watch(() => props.initialConfig, (cfg) => {
  if (!cfg) return
  step3Form.acceptDeptTransfer = cfg.acceptDeptTransfer || ''
  step3Form.acceptLocationTransfer = cfg.acceptLocationTransfer || ''
  step3Form.interviewType = cfg.interviewType ? [...cfg.interviewType] : []
  step3Form.languages = cfg.languages?.length ? cfg.languages.map(l => ({ language: l.language || '', proficiency: l.proficiency || '' })) : [{ language: '', proficiency: '' }]
  step3Form.availableDate = cfg.availableDate || ''
  step3Form.internDaysPerWeek = cfg.internDaysPerWeek || ''
  step3Form.internDuration = cfg.internDuration || ''
}, { immediate: true })
const languageOptions = ['英语', '日语', '法语', '德语', '韩语', '西班牙语', '俄语']
const proficiencyOptions = ['入门', '日常会话', '商务会话', '无障碍沟通', '母语']
const availableDateOptions = ['一周以内', '两周以内', '一个月以内', '一个月以上']
const internDaysOptions = ['3天及以上', '4天及以上', '5天及以上']
const internDurationOptions = ['3个月', '4个月', '5个月', '6个月及以上']
function toggleInterviewType(type: string) { const idx = step3Form.interviewType.indexOf(type); idx >= 0 ? step3Form.interviewType.splice(idx, 1) : step3Form.interviewType.push(type) }

// ==================== 第3步下半部分：插件安装 ====================
const extensionDownloadUrl = 'https://offerpie.oss-cn-guangzhou.aliyuncs.com/extension/chrome-mv3-prod.rar'
const browserList = [{ key: 'chrome', label: 'Chrome浏览器' }, { key: 'edge', label: 'Edge浏览器' }, { key: 'safari', label: 'Safari浏览器' }, { key: '360', label: '360浏览器' }, { key: 'qq', label: 'QQ浏览器' }]
const browserImageCount: Record<string, number> = { chrome: 3, edge: 3, safari: 3, '360': 3, qq: 3 }
const guidanceImageBase = 'http://offerpie.oss-cn-guangzhou.aliyuncs.com/extension/guidance_image'
const showBrowserGuide = ref(false)
const currentBrowserKey = ref('')
const currentBrowserLabel = computed(() => browserList.find(b => b.key === currentBrowserKey.value)?.label || '')
const currentBrowserImages = computed(() => { const key = currentBrowserKey.value; if (!key) return []; const count = browserImageCount[key] || 3; return Array.from({ length: count }, (_, i) => `${guidanceImageBase}/guidance-image-${key}-${String(i + 1).padStart(2, '0')}.png`) })
function openBrowserGuide(key: string) { currentBrowserKey.value = key; showBrowserGuide.value = true }
function downloadExtension() { window.open(extensionDownloadUrl, '_blank') }

// ==================== 第4步：配置求职助手 ====================
const settingsPanelRef = ref<InstanceType<typeof AgentSettingsPanel> | null>(null)
const setupComplete = ref(false)

/** 设置完成 — 收集第3步+第4步数据，通过 emit 传回父组件 */
function handleStep4Complete() {
  const step4Data = settingsPanelRef.value?.getData()
  const allSettings = {
    jobType: store.state.jobIntention.employmentType === 1 ? 1 : 2,
    agentMode: step4Data?.agentMode ?? 1,
    weeklyTarget: step4Data?.weeklyTarget ?? 2,
    autoOptimizeResume: step4Data?.autoOptimizeResume ?? 1,
    acceptDeptTransfer: step3Form.acceptDeptTransfer,
    acceptLocationTransfer: step3Form.acceptLocationTransfer,
    interviewType: [...step3Form.interviewType],
    languages: step3Form.languages.filter(l => l.language),
    availableDate: step3Form.availableDate,
    internDaysPerWeek: step3Form.internDaysPerWeek,
    internDuration: step3Form.internDuration,
    status:1,
  }
  emit('complete', allSettings)
  setupComplete.value = true
}

/** 启用求职助手 */
function handleLaunchAgent() { emit('launch') }
</script>

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