<template>
  <!-- Agent设置面板 — 右侧常驻面板 -->
  <div class="agent-setting-panel">
    <!-- 头部标题 -->
    <div class="agent-setting-panel__header">
      <div class="agent-setting-panel__title">投递助手设置</div>
      <div class="agent-setting-panel__subtitle">调整你的投递偏好</div>
    </div>

    <!-- 分隔线1 -->
    <div class="agent-setting-panel__divider"></div>

    <!-- ========== 个人信息 ========== -->
    <div class="agent-setting-panel__section mb20">
      <div class="agent-setting-panel__section-header">
        <span class="agent-setting-panel__section-title">个人信息</span>
        <span class="agent-setting-panel__edit-btn" @click="handleEditProfile">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M8.5 2.5L11.5 5.5M1.5 12.5L2.5 9L10.5 1L13 3.5L5 11.5L1.5 12.5Z" stroke="#52CAD1" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <span>编辑</span>
        </span>
      </div>
      <!-- 一行简要信息：姓名 · 电话 · 城市 -->
      <div class="agent-setting-panel__info-text">
        {{ profileSummaryText }}
      </div>
    </div>

    <!-- ========== 求职偏好 ========== -->
    <div class="agent-setting-panel__section">
      <div class="agent-setting-panel__section-header">
        <span class="agent-setting-panel__section-title">求职偏好</span>
        <span class="agent-setting-panel__edit-btn" @click="showJobGoalDialog = true">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M8.5 2.5L11.5 5.5M1.5 12.5L2.5 9L10.5 1L13 3.5L5 11.5L1.5 12.5Z" stroke="#52CAD1" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <span>编辑</span>
        </span>
      </div>
      <!-- 求职偏好内容：多行文字展示 -->
      <div class="agent-setting-panel__goal-content">
        <p v-if="intentionRegionText">{{ intentionRegionText }}</p>
        <p v-if="intentionCategoryText">{{ intentionCategoryText }}</p>
        <p v-if="intentionIndustryText">{{ intentionIndustryText }}</p>
        <p v-if="intentionEmpText">{{ intentionEmpText }}</p>
        <p v-if="intentionTags.length === 0" class="agent-setting-panel__empty-text">暂未设置</p>
      </div>
    </div>

    <!-- 分隔线2 -->
    <div class="agent-setting-panel__divider"></div>

    <!-- ========== 投递简历 ========== -->
    <div class="agent-setting-panel__section">
      <div class="agent-setting-panel__section-title">投递简历</div>
      <div class="agent-setting-panel__resume-dropdown" @click="showResumeDropdown = !showResumeDropdown">
        <span class="agent-setting-panel__resume-name">{{ selectedResumeName || '请选择简历' }}</span>
        <svg class="agent-setting-panel__resume-arrow" :class="{ 'agent-setting-panel__resume-arrow--open': showResumeDropdown }" width="14" height="14" viewBox="0 0 14 14" fill="none">
          <path d="M4 6L7 9L10 6" stroke="#6A7282" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </div>
      <!-- 下拉选项 -->
      <div v-if="showResumeDropdown" class="agent-setting-panel__resume-options">
        <div
          v-for="r in resumeList"
          :key="r.id"
          class="agent-setting-panel__resume-option"
          :class="{ 'agent-setting-panel__resume-option--active': selectedResumeId === r.id }"
          @click="handleSelectResume(r)"
        >{{ r.resumeName }}</div>
      </div>
    </div>

    <!-- 分隔线3 -->
    <div class="agent-setting-panel__divider"></div>

    <!-- ========== 投递偏好 ========== -->
    <div class="agent-setting-panel__section">
      <div class="agent-setting-panel__section-title">投递偏好</div>
      <!-- 开启简历针对性优化 -->
      <div class="agent-setting-panel__switch-item">
        <div class="agent-setting-panel__switch-text">
          <span class="agent-setting-panel__switch-label">开启简历针对性优化</span>
          <span class="agent-setting-panel__switch-desc">结合岗位要求，自动优化简历表达</span>
        </div>
        <div class="agent-setting-panel__toggle" :class="{ 'agent-setting-panel__toggle--on': autoOptimizeSwitch }" @click="toggleOptimize">
          <div class="agent-setting-panel__toggle-dot"></div>
        </div>
      </div>
      <!-- 开启深度人岗匹配分析 -->
      <div class="agent-setting-panel__switch-item">
        <div class="agent-setting-panel__switch-text">
          <span class="agent-setting-panel__switch-label">开启深度人岗匹配分析</span>
          <span class="agent-setting-panel__switch-desc">分析你的匹配优势与差距</span>
        </div>
        <div class="agent-setting-panel__toggle" :class="{ 'agent-setting-panel__toggle--on': autoMatchAnalysisSwitch }" @click="toggleMatch">
          <div class="agent-setting-panel__toggle-dot"></div>
        </div>
      </div>
    </div>

    <!-- 分隔线4 -->
    <div class="agent-setting-panel__divider"></div>

    <!-- ========== 浏览器插件 ========== -->
    <div class="agent-setting-panel__section">
      <div class="agent-setting-panel__section-title">浏览器插件</div>
      <div class="agent-setting-panel__browser-btns">
        <button class="agent-setting-panel__browser-btn" @click="openBrowserGuide('chrome')">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <g clip-path="url(#clip0_498_4683)">
              <path d="M8.00014 12.4507C10.4586 12.4507 12.4515 10.4577 12.4515 7.99929C12.4515 5.54085 10.4586 3.54785 8.00014 3.54785C5.54171 3.54785 3.54871 5.54085 3.54871 7.99929C3.54871 10.4577 5.54164 12.4507 8.00008 12.4507" fill="white"/>
              <path d="M2.24315 5.81204C1.91106 5.23683 1.52073 4.63314 1.07215 4.00098C0.369879 5.21706 0.000145925 6.59661 0.000122071 8.0009C9.82178e-05 9.4052 0.369785 10.7848 1.07201 12.0009C1.77424 13.217 2.78426 14.2268 4.00052 14.9288C5.21678 15.6307 6.59641 16.0001 8.00071 15.9998C8.737 14.9671 9.23692 14.2225 9.50046 13.766C10.0066 12.8893 10.6613 11.6341 11.4644 10.0004V9.99941C11.1135 10.6077 10.6087 11.113 10.0006 11.4643C9.39254 11.8156 8.70268 12.0006 8.00042 12.0007C7.29817 12.0008 6.60826 11.816 6.00008 11.4649C5.3919 11.1138 4.88689 10.6087 4.53584 10.0005C3.44509 7.96623 2.68086 6.57004 2.24315 5.81204Z" fill="#229342"/>
              <path d="M8.00046 16.0002C9.05106 16.0004 10.0914 15.7936 11.0621 15.3916C12.0327 14.9896 12.9147 14.4003 13.6575 13.6574C14.4004 12.9145 14.9896 12.0325 15.3915 11.0619C15.7935 10.0912 16.0002 9.05084 16 8.00024C15.9997 6.59593 15.6297 5.21644 14.9273 4.00043C13.4118 3.85105 12.2933 3.77637 11.5719 3.77637C10.7539 3.77637 9.56323 3.85105 7.9999 4.00043L7.99902 4.00105C8.7013 4.00071 9.39128 4.18529 9.99958 4.53623C10.6079 4.88717 11.113 5.39211 11.4643 6.00024C11.8155 6.60838 12.0004 7.29828 12.0004 8.00056C12.0004 8.70284 11.8155 9.39274 11.4642 10.0009L8.00046 16.0002Z" fill="#FBC116"/>
              <path d="M8.00013 11.1677C9.74913 11.1677 11.1669 9.74992 11.1669 8.00086C11.1669 6.2518 9.74913 4.83398 8.00006 4.83398C6.25113 4.83398 4.83325 6.25186 4.83325 8.00086C4.83325 9.74986 6.25113 11.1677 8.00013 11.1677Z" fill="#1A73E8"/>
              <path d="M8.00014 4.00027H14.9275C14.2255 2.78399 13.2157 1.77397 11.9995 1.07176C10.7834 0.369547 9.40384 -9.50021e-05 7.99953 1.83149e-08C6.59522 9.50388e-05 5.21569 0.369924 3.99965 1.0723C2.78362 1.77467 1.77394 2.78484 1.07214 4.00121L4.53583 10.0006L4.53677 10.0011C4.18536 9.39306 4.00025 8.70322 4.00004 8.00095C3.99984 7.29868 4.18455 6.60873 4.53559 6.0005C4.88664 5.39226 5.39165 4.88718 5.99983 4.53605C6.60802 4.18491 7.29794 4.0001 8.00021 4.00021L8.00014 4.00027Z" fill="#E33B2E"/>
            </g>
            <defs>
              <clipPath id="clip0_498_4683">
                <rect width="16" height="16" fill="white"/>
              </clipPath>
            </defs>
          </svg>
          <span>Chrome浏览器</span>
        </button>
        <button class="agent-setting-panel__browser-btn" @click="openBrowserGuide('edge')">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <g clip-path="url(#clip0_498_4700)">
              <path d="M14.4375 11.9059C14.225 12.0184 14.0062 12.1184 13.7812 12.1996C13.0625 12.4684 12.3062 12.6059 11.5375 12.6059C8.5812 12.6059 6.0062 10.5746 6.0062 7.96211C6.01245 7.24961 6.4062 6.59336 7.0312 6.25586C4.3562 6.36836 3.6687 9.15586 3.6687 10.7871C3.6687 15.4059 7.92495 15.8746 8.8437 15.8746C9.33745 15.8746 10.0812 15.7309 10.5312 15.5871L10.6125 15.5621C12.3375 14.9684 13.8 13.8059 14.775 12.2621C14.85 12.1434 14.8125 11.9934 14.7 11.9184C14.6187 11.8684 14.5187 11.8621 14.4375 11.9059Z" fill="url(#paint0_linear_498_4700)"/>
              <path opacity="0.35" d="M14.4375 11.9059C14.225 12.0184 14.0062 12.1184 13.7812 12.1996C13.0625 12.4684 12.3062 12.6059 11.5375 12.6059C8.5812 12.6059 6.0062 10.5746 6.0062 7.96211C6.01245 7.24961 6.4062 6.59336 7.0312 6.25586C4.3562 6.36836 3.6687 9.15586 3.6687 10.7871C3.6687 15.4059 7.92495 15.8746 8.8437 15.8746C9.33745 15.8746 10.0812 15.7309 10.5312 15.5871L10.6125 15.5621C12.3375 14.9684 13.8 13.8059 14.775 12.2621C14.85 12.1434 14.8125 11.9934 14.7 11.9184C14.6187 11.8684 14.5187 11.8621 14.4375 11.9059Z" fill="url(#paint1_radial_498_4700)"/>
              <path d="M6.60629 15.0877C6.05004 14.7439 5.56879 14.2877 5.18754 13.7564C3.54379 11.5064 4.03754 8.3502 6.28754 6.70645C6.52504 6.5377 6.76879 6.38145 7.03129 6.25645C7.22504 6.1627 7.55629 6.0002 8.00004 6.00645C8.63129 6.0127 9.22504 6.3127 9.60629 6.81895C9.85629 7.15645 10 7.5627 10.0063 7.9877C10.0063 7.9752 11.5375 3.0127 5.00629 3.0127C2.26254 3.0127 0.00628588 5.61895 0.00628588 7.9002C-0.00621412 9.10645 0.256286 10.3064 0.762536 11.4002C2.48754 15.0752 6.68754 16.8752 10.5375 15.5939C9.21879 16.0064 7.78129 15.8252 6.60629 15.0877Z" fill="url(#paint2_linear_498_4700)"/>
              <path opacity="0.41" d="M6.60629 15.0877C6.05004 14.7439 5.56879 14.2877 5.18754 13.7564C3.54379 11.5064 4.03754 8.3502 6.28754 6.70645C6.52504 6.5377 6.76879 6.38145 7.03129 6.25645C7.22504 6.1627 7.55629 6.0002 8.00004 6.00645C8.63129 6.0127 9.22504 6.3127 9.60629 6.81895C9.85629 7.15645 10 7.5627 10.0063 7.9877C10.0063 7.9752 11.5375 3.0127 5.00629 3.0127C2.26254 3.0127 0.00628588 5.61895 0.00628588 7.9002C-0.00621412 9.10645 0.256286 10.3064 0.762536 11.4002C2.48754 15.0752 6.68754 16.8752 10.5375 15.5939C9.21879 16.0064 7.78129 15.8252 6.60629 15.0877Z" fill="url(#paint3_radial_498_4700)"/>
              <path d="M9.51875 9.30625C9.46875 9.36875 9.3125 9.4625 9.3125 9.6625C9.3125 9.825 9.41875 9.98125 9.60625 10.1125C10.5062 10.7375 12.2 10.6562 12.2063 10.6562C12.875 10.6562 13.525 10.475 14.1 10.1375C15.275 9.45 16 8.19375 16 6.83125C16.0187 5.43125 15.5 4.5 15.2937 4.0875C13.9688 1.49375 11.1062 0 8 0C3.625 0 0.0625 3.5125 0 7.8875C0.03125 5.60625 2.3 3.7625 5 3.7625C5.21875 3.7625 6.46875 3.78125 7.625 4.39375C8.64375 4.93125 9.18125 5.575 9.55 6.21875C9.9375 6.8875 10.0063 7.725 10.0063 8.0625C10.0063 8.39375 9.8375 8.89375 9.51875 9.30625Z" fill="url(#paint4_radial_498_4700)"/>
              <path d="M9.51875 9.30625C9.46875 9.36875 9.3125 9.4625 9.3125 9.6625C9.3125 9.825 9.41875 9.98125 9.60625 10.1125C10.5062 10.7375 12.2 10.6562 12.2063 10.6562C12.875 10.6562 13.525 10.475 14.1 10.1375C15.275 9.45 16 8.19375 16 6.83125C16.0187 5.43125 15.5 4.5 15.2937 4.0875C13.9688 1.49375 11.1062 0 8 0C3.625 0 0.0625 3.5125 0 7.8875C0.03125 5.60625 2.3 3.7625 5 3.7625C5.21875 3.7625 6.46875 3.78125 7.625 4.39375C8.64375 4.93125 9.18125 5.575 9.55 6.21875C9.9375 6.8875 10.0063 7.725 10.0063 8.0625C10.0063 8.39375 9.8375 8.89375 9.51875 9.30625Z" fill="url(#paint5_radial_498_4700)"/>
            </g>
            <defs>
              <linearGradient id="paint0_linear_498_4700" x1="3.66895" y1="11.0634" x2="14.8116" y2="11.0634" gradientUnits="userSpaceOnUse">
                <stop stop-color="#0C59A4"/>
                <stop offset="1" stop-color="#114A8B"/>
              </linearGradient>
              <radialGradient id="paint1_radial_498_4700" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(9.82444 11.1519) scale(5.96065 5.662)">
                <stop offset="0.72" stop-opacity="0"/>
                <stop offset="0.95" stop-opacity="0.53"/>
                <stop offset="1"/>
              </radialGradient>
              <linearGradient id="paint2_linear_498_4700" x1="9.54822" y1="6.23432" x2="2.58741" y2="13.8163" gradientUnits="userSpaceOnUse">
                <stop stop-color="#1B9DE2"/>
                <stop offset="0.16" stop-color="#1595DF"/>
                <stop offset="0.67" stop-color="#0680D7"/>
                <stop offset="1" stop-color="#0078D4"/>
              </linearGradient>
              <radialGradient id="paint3_radial_498_4700" cx="0" cy="0" r="1" gradientTransform="matrix(1.34287 -8.86118 7.162 1.0743 4.41307 12.4383)" gradientUnits="userSpaceOnUse">
                <stop offset="0.76" stop-opacity="0"/>
                <stop offset="0.95" stop-opacity="0.5"/>
                <stop offset="1"/>
              </radialGradient>
              <radialGradient id="paint4_radial_498_4700" cx="0" cy="0" r="1" gradientTransform="matrix(-0.506075 12.6493 -26.9472 -1.0119 1.61573 2.96205)" gradientUnits="userSpaceOnUse">
                <stop stop-color="#35C1F1"/>
                <stop offset="0.11" stop-color="#34C1ED"/>
                <stop offset="0.23" stop-color="#2FC2DF"/>
                <stop offset="0.31" stop-color="#2BC3D2"/>
                <stop offset="0.67" stop-color="#36C752"/>
              </radialGradient>
              <radialGradient id="paint5_radial_498_4700" cx="0" cy="0" r="1" gradientTransform="matrix(1.70345 5.83918 -4.74533 1.39926 15.0038 4.83786)" gradientUnits="userSpaceOnUse">
                <stop stop-color="#66EB6E"/>
                <stop offset="1" stop-color="#66EB6E" stop-opacity="0"/>
              </radialGradient>
              <clipPath id="clip0_498_4700">
                <rect width="16" height="16" fill="white"/>
              </clipPath>
            </defs>
          </svg>
          <span>Edge浏览器</span>
        </button>
      </div>
    </div>

    <!-- 个人信息编辑弹窗 -->
    <div v-if="showEditDialog" class="agent-setting-panel__edit-overlay" @click.self="showEditDialog = false">
      <div class="agent-setting-panel__edit-dialog">
        <!-- 弹窗头部 -->
        <div class="agent-setting-panel__edit-dialog-header">
          <span class="agent-setting-panel__edit-dialog-title">个人信息</span>
          <svg class="agent-setting-panel__edit-dialog-close" @click="showEditDialog = false" width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M6 6L18 18M18 6L6 18" stroke="#6A7282" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </div>
        <!-- 表单内容 -->
        <div class="agent-setting-panel__edit-dialog-body">
          <!-- 第一行：姓名 + 电话 -->
          <div class="agent-setting-panel__edit-row">
            <div class="agent-setting-panel__edit-field">
              <label class="agent-setting-panel__edit-label">姓名</label>
              <input class="agent-setting-panel__edit-input" v-model="editForm.name" placeholder="请输入姓名" />
            </div>
            <div class="agent-setting-panel__edit-field">
              <label class="agent-setting-panel__edit-label">电话</label>
              <input class="agent-setting-panel__edit-input" v-model="editForm.phone" placeholder="请输入电话" />
            </div>
          </div>
          <!-- 第二行：微信 + 邮箱 -->
          <div class="agent-setting-panel__edit-row">
            <div class="agent-setting-panel__edit-field">
              <label class="agent-setting-panel__edit-label">微信</label>
              <input class="agent-setting-panel__edit-input" v-model="editForm.wechat" placeholder="请输入微信号" />
            </div>
            <div class="agent-setting-panel__edit-field">
              <label class="agent-setting-panel__edit-label">邮箱</label>
              <input class="agent-setting-panel__edit-input" v-model="editForm.email" placeholder="请输入邮箱" />
            </div>
          </div>
          <!-- 第三行：所在城市 -->
          <div class="agent-setting-panel__edit-field agent-setting-panel__edit-field--full">
            <label class="agent-setting-panel__edit-label">所在城市</label>
            <div class="agent-setting-panel__edit-city">
              <RegionSelector
                :regionCodes="editLocationCodes"
                :level="2"
                :maxSelect="1"
                :triggerStyle="cityTriggerStyle"
                @update:regionCodes="onEditLocationChange"
              />
            </div>
          </div>
        </div>
        <!-- 保存按钮 -->
        <button class="agent-setting-panel__edit-dialog-save" :disabled="saving" @click="handleSaveEdit">保存</button>
      </div>
    </div>

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

    <!-- 浏览器插件安装教程抽屉 -->
    <Teleport to="body">
      <Transition name="agent-browser-guide-drawer">
        <div v-if="showBrowserGuideDrawer" class="agent-browser-guide-mask" @click.self="closeBrowserGuideDrawer">
          <div class="agent-browser-guide-drawer">
            <!-- 顶部标题栏 -->
            <div class="agent-browser-guide-drawer__header">
              <div class="agent-browser-guide-drawer__header-left">
                <div class="agent-browser-guide-drawer__close" @click="closeBrowserGuideDrawer">
                  <svg viewBox="0 0 24 24" fill="none" class="agent-browser-guide-drawer__close-icon">
                    <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </div>
                <span class="agent-browser-guide-drawer__title">安装浏览器插件教程</span>
              </div>
            </div>

            <!-- 步骤内容 -->
            <AgentBrowserInstallGuide />
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { formatEmploymentType } from '@/stores/index'
import JobGoalDialog from '@/components/JobGoalDialog.vue'
import RegionSelector from '@/components/tools/RegionSelector.vue'
import AgentBrowserInstallGuide from '@/components/AgentBrowserInstallGuide.vue'
import { saveProfile, fetchProfile, fetchEducation } from '@/api/profile'
import { resolveRegionName } from '@/utils/region'
import { resolveIndustryName } from '@/utils/industry'
import { resolveJobCategoryName } from '@/utils/jobCategory'
import { fetchResumeList, setDefaultResume } from '@/api/resume'
import type { ResumeListItem } from '@/api/resume'
import { fetchAgentConfig, saveAgentConfig } from '@/api/agent'

const store = useStore()

// ==================== 个人资料 ====================

/** 个人资料数据 */
const profile = ref({
  name: '',
  phone: '',
  email: '',
  regionCode: '',
  wechat: '',
  skills: [] as string[],
  certificates: [] as string[],
  portfolioUrl: '',
  education: [] as Array<{ school: string; major: string; degree: number }>,
})

/** 个人信息摘要文字（姓名 · 电话 · 城市） */
const profileSummaryText = computed(() => {
  const parts: string[] = []
  if (profile.value.name) parts.push(profile.value.name)
  if (profile.value.phone) parts.push(profile.value.phone)
  const cityName = resolveRegionName(profile.value.regionCode)
  if (cityName) parts.push(cityName)
  return parts.length > 0 ? parts.join(' · ') : '未填写'
})

/** 加载个人资料 */
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.regionCode = d.regionCode || ''
      profile.value.wechat = d.wechatNumber || ''
      profile.value.skills = d.skills || []
      profile.value.certificates = d.certificates || []
      profile.value.portfolioUrl = d.portfolioUrl || ''
    }
  } catch { /* 静默 */ }
}

/** 加载教育经历 */
async function loadEducation() {
  try {
    const res = await fetchEducation()
    if (res.code === '0' && res.data && res.data.length > 0) {
      profile.value.education = res.data.map(item => ({
        school: item.school || '',
        major: item.major || '',
        degree: item.degree ?? 2,
      }))
    }
  } catch { /* 静默 */ }
}

// ==================== 编辑弹窗 ====================

/** 编辑弹窗显隐 */
const showEditDialog = ref(false)
const saving = ref(false)

/** 编辑表单数据 */
const editForm = ref({
  name: '',
  phone: '',
  wechat: '',
  email: '',
  location: '',
})

/** 城市选择器当前编码 */
const editLocationCodes = ref<string[]>([])

/** 城市选择器触发按钮样式 */
const cityTriggerStyle: Record<string, string> = {
  width: '100%',
  'box-sizing': 'border-box',
  padding: '0.08rem 0.16rem',
  'font-size': '0.14rem',
  color: '#1A1A1A',
  background: '#F3F4F6',
  border: 'none',
  'border-radius': '0.08rem',
  'justify-content': 'space-between',
}

/** 打开编辑弹窗 */
function handleEditProfile() {
  editForm.value = {
    name: profile.value.name,
    phone: profile.value.phone,
    wechat: profile.value.wechat,
    email: profile.value.email,
    location: profile.value.regionCode,
  }
  editLocationCodes.value = profile.value.regionCode ? [profile.value.regionCode] : []
  showEditDialog.value = true
}

/** 城市选择回调 */
function onEditLocationChange(codes: string[]) {
  editLocationCodes.value = codes
  editForm.value.location = codes[0] || ''
}

/** 保存编辑 */
async function handleSaveEdit() {
  saving.value = true
  try {
    await saveProfile({
      name: editForm.value.name,
      email: editForm.value.email,
      mobileNumber: editForm.value.phone,
      regionCode: editForm.value.location,
      wechatNumber: editForm.value.wechat,
    })
    profile.value.name = editForm.value.name
    profile.value.email = editForm.value.email
    profile.value.phone = editForm.value.phone
    profile.value.wechat = editForm.value.wechat
    profile.value.regionCode = editForm.value.location
    showEditDialog.value = false
    ElMessage.success('个人信息保存成功')
  } catch {
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// ==================== 求职目标 ====================

const showJobGoalDialog = ref(false)

/** 求职意向标签（汇总） */
const intentionTags = computed(() => {
  const tags: string[] = []
  const catIds = store.state.jobIntention?.categoryIds || []
  const indIds = store.state.jobIntention?.industryIds || []
  const regCodes = store.state.jobIntention?.regionCodes || []
  catIds.forEach((id: number) => { const n = resolveJobCategoryName(id); if (n) tags.push(n) })
  indIds.forEach((id: number) => { const n = resolveIndustryName(id); if (n) tags.push(n) })
  regCodes.forEach((code: string) => { const n = resolveRegionName(code); if (n) tags.push(n) })
  const empLabel = formatEmploymentType(store.state.jobIntention?.recruitCategory)
  if (empLabel) tags.push(empLabel)
  return tags
})

/** 求职偏好 — 地区文字 */
const intentionRegionText = computed(() => {
  const regCodes = store.state.jobIntention?.regionCodes || []
  const names = regCodes.map((code: string) => resolveRegionName(code)).filter(Boolean)
  return names.length > 0 ? names.join('、') : ''
})

/** 求职偏好 — 岗位文字 */
const intentionCategoryText = computed(() => {
  const catIds = store.state.jobIntention?.categoryIds || []
  const names = catIds.map((id: number) => resolveJobCategoryName(id)).filter(Boolean)
  return names.length > 0 ? names.join('、') : ''
})

/** 求职偏好 — 行业文字 */
const intentionIndustryText = computed(() => {
  const indIds = store.state.jobIntention?.industryIds || []
  const names = indIds.map((id: number) => resolveIndustryName(id)).filter(Boolean)
  return names.length > 0 ? names.join('、') : ''
})

/** 求职偏好 — 招聘类型文字 */
const intentionEmpText = computed(() => {
  return formatEmploymentType(store.state.jobIntention?.recruitCategory) || ''
})

// ==================== 投递简历 ====================

const resumeList = ref<ResumeListItem[]>([])
const selectedResumeId = ref('')
const showResumeDropdown = ref(false)

/** 当前选中简历名称 */
const selectedResumeName = computed(() => {
  const found = resumeList.value.find(r => r.id === selectedResumeId.value)
  return found?.resumeName || ''
})

/** 加载简历列表 */
async function loadResumeList() {
  try {
    const res = await fetchResumeList()
    if (res.code === '0' && res.data) {
      resumeList.value = res.data
      const defaultResume = res.data.find(r => r.isDefault === 1)
      selectedResumeId.value = defaultResume?.id || (res.data[0]?.id || '')
    }
  } catch { /* 静默 */ }
}

/** 选择简历 */
function handleSelectResume(r: ResumeListItem) {
  selectedResumeId.value = r.id || ''
  showResumeDropdown.value = false
  if (r.id) {
    setDefaultResume(r.id).catch(() => { /* 静默 */ })
  }
}

// ==================== 投递偏好 ====================

const autoOptimizeSwitch = ref(false)
const autoMatchAnalysisSwitch = ref(false)

/** 切换简历优化开关 */
function toggleOptimize() {
  autoOptimizeSwitch.value = !autoOptimizeSwitch.value
  handleSavePreference()
}

/** 切换匹配分析开关 */
function toggleMatch() {
  autoMatchAnalysisSwitch.value = !autoMatchAnalysisSwitch.value
  handleSavePreference()
}

/** 加载配置 */
async function loadAgentConfigData() {
  try {
    const res = await fetchAgentConfig()
    if (res.code === '0' && res.data) {
      if (res.data.autoOptimizeResume !== undefined) autoOptimizeSwitch.value = res.data.autoOptimizeResume === 1
      // acceptDeptTransfer: "是"=开启，null/空字符串/"否"=关闭
      autoMatchAnalysisSwitch.value = res.data.acceptDeptTransfer === '是'
    }
  } catch { /* 静默 */ }
}

/** 保存偏好设置 */
async function handleSavePreference() {
  try {
    await saveAgentConfig({
      autoOptimizeResume: autoOptimizeSwitch.value ? 1 : 0,
      acceptDeptTransfer: autoMatchAnalysisSwitch.value ? '是' : '否',
    })
  } catch { /* 静默 */ }
}

// ==================== 浏览器插件 ====================

/** 浏览器插件安装教程抽屉是否显示 */
const showBrowserGuideDrawer = ref(false)

/** 打开浏览器安装指引抽屉 */
function openBrowserGuide(_browser: string) {
  showBrowserGuideDrawer.value = true
}

/** 关闭浏览器安装指引抽屉 */
function closeBrowserGuideDrawer() {
  showBrowserGuideDrawer.value = false
}

// ==================== 初始化 ====================

onMounted(async () => {
  if (!store.state.regions.length) store.dispatch('loadCommonData')
  store.dispatch('loadJobIntention')
  await loadProfile()
  await loadEducation()
  await loadResumeList()
  await loadAgentConfigData()
})
</script>

<style scoped lang="scss">
@use '../assets/styles/components/agent-setting-panel';
</style>
