<template>
  <div class="jobs-page">
    <SideNav />
    <div class="jobs-page__content">

      <div v-if="false" class="fs18 p20 bgeee">

      </div>

      <!-- 页面标题 + Tab 切换 -->
      <JobPageHeader ref="jobPageHeaderRef" v-model:activeTab="activeTab" />

      <!-- 筛选条件面板 -->
      <div v-if="isRecommendTab" class="jobs-page__filters-bar">
        <!-- 筛选面板 + 统计卡片横向排列 -->
        <div class="jobs-page__filters-row">
        <div ref="filtersPanelRef" class="jobs-page__filters-panel">
          <!-- 行业热门分类行 -->
          <div class="jobs-page__filter-row" v-if="hotIndustries.length > 0">
            <div class="jobs-page__filter-row-inner">
              <span class="jobs-page__filter-row-label">行业</span>
              <div class="jobs-page__filter-chips-wrap">
                <div class="jobs-page__filter-chips">
                  <!-- 全部按钮 -->
                  <span
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active-solid': selectedIndustryIds.length === 0 }"
                    @click="clearIndustryFilter"
                  >全部</span>
                  <!-- 热门行业chip -->
                  <span
                    v-for="item in hotIndustries"
                    :key="'hot-ind-' + item.id"
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active': selectedIndustryIds.includes(item.id) }"
                    @click="toggleHotIndustry(item.id)"
                  >{{ item.name }}</span>
                  <!-- 选择器额外选中的行业（去重热门后追加） -->
                  <span
                    v-for="item in extraIndustryChips"
                    :key="'extra-ind-' + item.id"
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active': selectedIndustryIds.includes(item.id) }"
                    @click="toggleHotIndustry(item.id)"
                  >{{ item.name }}</span>
                </div>
                <!-- 更多按钮（固定在行最右边） -->
                <IndustrySelector
                  ref="industrySelectorRef"
                  :industryIds="selectedIndustryIds"
                  :maxSelect="3"
                  :level="2"
                  :allowParentSelect="false"
                  :allowParentSelectClick="true"
                  :triggerStyle="moreBtnTriggerStyle"
                  :hoverStyle="moreBtnHoverStyle"
                  :displayStyle="selectorDisplayStyle"
                  triggerLabel="更多"
                  @update:industryIds="onIndustryChange"
                />
              </div>
            </div>
          </div>
          <!-- 岗位热门分类行 -->
          <div class="jobs-page__filter-row" v-if="hotCategories.length > 0">
            <div class="jobs-page__filter-row-inner">
              <span class="jobs-page__filter-row-label">岗位</span>
              <div class="jobs-page__filter-chips-wrap">
                <div class="jobs-page__filter-chips">
                  <!-- 全部按钮 -->
                  <span
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active-solid': selectedCategoryIds.length === 0 }"
                    @click="clearCategoryFilter"
                  >全部</span>
                  <!-- 热门岗位chip -->
                  <span
                    v-for="item in hotCategories"
                    :key="'hot-cat-' + item.id"
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active': selectedCategoryIds.includes(item.id) }"
                    @click="toggleHotCategory(item.id)"
                  >{{ item.name }}</span>
                  <!-- 选择器额外选中的岗位（去重热门后追加） -->
                  <span
                    v-for="item in extraCategoryChips"
                    :key="'extra-cat-' + item.id"
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active': selectedCategoryIds.includes(item.id) }"
                    @click="toggleHotCategory(item.id)"
                  >{{ item.name }}</span>
                </div>
                <!-- 更多按钮（固定在行最右边） -->
                <JobCategorySelector
                  ref="jobCategorySelectorRef"
                  :categoryIds="selectedCategoryIds"
                  :maxSelect="3"
                  :level="3"
                  :allowParentSelect="false"
                  :allowParentSelectClick="true"
                  :triggerStyle="moreBtnTriggerStyle"
                  :hoverStyle="moreBtnHoverStyle"
                  :displayStyle="selectorDisplayStyle"
                  triggerLabel="更多"
                  @update:categoryIds="onCategoryChange"
                />
              </div>
            </div>
          </div>
          <!-- 地点热门分类行 -->
          <div class="jobs-page__filter-row" v-if="hotCities.length > 0">
            <div class="jobs-page__filter-row-inner">
              <span class="jobs-page__filter-row-label">地点</span>
              <div class="jobs-page__filter-chips-wrap">
                <div class="jobs-page__filter-chips">
                  <!-- 全国按钮 -->
                  <span
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active-solid': selectedRegionCodes.length === 0 }"
                    @click="clearRegionFilter"
                  >全国</span>
                  <!-- 热门城市chip -->
                  <span
                    v-for="item in hotCities"
                    :key="'hot-city-' + item.code"
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active': selectedRegionCodes.includes(item.code) }"
                    @click="toggleHotCity(item.code)"
                  >{{ item.name }}</span>
                  <!-- 选择器额外选中的城市（去重热门后追加） -->
                  <span
                    v-for="item in extraCityChips"
                    :key="'extra-city-' + item.code"
                    class="jobs-page__filter-chip"
                    :class="{ 'jobs-page__filter-chip--active': selectedRegionCodes.includes(item.code) }"
                    @click="toggleHotCity(item.code)"
                  >{{ item.name }}</span>
                </div>
                <!-- 更多按钮（固定在行最右边） -->
                <RegionSelector
                  ref="regionSelectorRef"
                  :regionCodes="selectedRegionCodes"
                  :level="2"
                  :maxSelect="3"
                  :triggerStyle="moreBtnTriggerStyle"
                  :hoverStyle="moreBtnHoverStyle"
                  :displayStyle="selectorDisplayStyle"
                  triggerLabel="更多"
                  @update:regionCodes="onRegionChange"
                />
              </div>
            </div>
          </div>
          <!-- 筛选行：招聘分类 + 学历要求 + 公司类型 + 发布时间 + 清空 -->
          <div class="jobs-page__filter-row jobs-page__filter-row--bottom">
            <div class="jobs-page__filter-row-inner">
              <span class="jobs-page__filter-row-label">筛选</span>
              <div class="jobs-page__filter-dropdowns">
                <!-- 招聘分类下拉 -->
                <div class="jobs-page__dropdown-item" @click.stop="handleFilterClick(filters[3])">
                  <span>{{ filters[3].selected || '社招' }}</span>
                  <svg class="jobs-page__dropdown-arrow" viewBox="0 0 12 12" fill="none">
                    <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  <div v-if="showJobTypeDropdown" class="jobs-page__filter-dropdown" @click.stop>
                    <div
                      class="jobs-page__filter-dropdown-item"
                      v-for="option in jobTypeOptions"
                      :key="option.value"
                      :class="{ 'jobs-page__filter-dropdown-item--active': filters[3].selected === option.label }"
                      @click.stop="selectJobType(filters[3], option)"
                    >{{ option.label }}</div>
                  </div>
                </div>
                <!-- 学历要求下拉 -->
                <div class="jobs-page__dropdown-item" @click.stop="showEducationDropdown = !showEducationDropdown; showJobTypeDropdown = false; showCompanyTypeDropdown = false; showPublishTimePanel = false">
                  <span>{{ educationFilterLabel }}</span>
                  <svg class="jobs-page__dropdown-arrow" viewBox="0 0 12 12" fill="none">
                    <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  <div v-if="showEducationDropdown" class="jobs-page__filter-dropdown" @click.stop>
                    <div
                      class="jobs-page__filter-dropdown-item"
                      v-for="option in educationOptions"
                      :key="option.value"
                      :class="{ 'jobs-page__filter-dropdown-item--active': selectedEducation === option.value }"
                      @click.stop="selectEducation(option)"
                    >{{ option.label }}</div>
                  </div>
                </div>
                <!-- 公司类型下拉 -->
                <div class="jobs-page__dropdown-item" @click.stop="handleFilterClick(filters[4])">
                  <span>{{ filters[4].selected || '公司类型' }}</span>
                  <svg class="jobs-page__dropdown-arrow" viewBox="0 0 12 12" fill="none">
                    <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  <div v-if="showCompanyTypeDropdown" class="jobs-page__filter-dropdown" @click.stop>
                    <div
                      class="jobs-page__filter-dropdown-item"
                      v-for="option in companyTypeOptions"
                      :key="option.label"
                      :class="{ 'jobs-page__filter-dropdown-item--active': filters[4].selected === option.label || (!filters[4].selected && !option.value.length) }"
                      @click.stop="selectCompanyType(filters[4], option)"
                    >{{ option.label }}</div>
                  </div>
                </div>
                <!-- 发布时间选择 -->
                <div class="jobs-page__dropdown-item border-n jobs-page__dropdown-item--time">
                  <span class="">发布时间：</span>
                  <el-date-picker
                    v-model="publishTimeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    size="small"
                    :teleported="true"
                    format="MM/DD"
                    style="width: 1.8rem; height: 0.24rem; font-size: 0.12rem;"
                    @change="onPublishTimeChange"
                  />
                </div>
              </div>
            </div>
            <!-- 清空筛选条件 -->
            <span v-if="hasActiveFilters" class="jobs-page__clear-filters" @click="clearAllFilters">清空筛选条件</span>
          </div>

          <!-- 筛选数量 + 深度匹配提示条 -->
          <div  v-if="showFilterCountBar" class="jobs-page__filter-count-bar">
            <span class="jobs-page__filter-count-text">
              当前筛选共：<span class="jobs-page__filter-count-num">{{ filterJobCount }}</span> 个岗位，试试开启深度匹配，配寻找更适合你的岗位吧~
            </span>
            <button class="jobs-page__deep-match-btn" :disabled="deepMatchLoading" @click="handleDeepMatch">
              {{ deepMatchLoading ? '匹配中...' : '深度匹配' }}
            </button>
          </div>


        </div>
        <!-- 岗位概览统计卡片（固定宽度，高度跟随筛选面板） -->
        <JobStatsOverview
          title="岗位概览"
          :subtitle="'数据截至 ' + statsCurrentDate"
          :todayCount="statsDailyJobCount"
          todayLabel="今日新增"
          :totalCount="statsFormattedJobCount"
          totalLabel="累计收录"
          rateValue="92%"
          rateLabel="可投率"
          :cardHeight="filtersPanelHeight"
        />
        </div>
        <!-- 搜索框（独立在筛选面板下方） -->
        <div class="mt12 dflex aliite-c flex-warp">
          <div class="jobs-page__search-box fgrow1">
            <svg class="jobs-page__search-svg" viewBox="0 0 16 16" fill="none" @click="reloadFirstPage">
              <circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.2"/>
              <path d="M11 11L14 14" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>
            </svg>
            <input
                v-model="keyword"
                class="jobs-page__search-input"
                placeholder="搜索职位、公司..."
                @keyup.enter="reloadFirstPage"
            />
          </div>
          <div class="dflex aliite-c flex-warp ml24">
            <!-- 热门搜索标签 -->
            <span class="jobs-page__hot-search-label">热门搜索：</span>
            <span
              v-for="(tag, idx) in hotSearchTags"
              :key="idx"
              class="jobs-page__hot-search-tag"
              :class="{ 'jobs-page__hot-search-tag--active': keyword === tag }"
              @click="handleHotSearch(tag)"
            >{{ tag }}</span>
          </div>
        </div>
      </div>

      <!-- 职位列表（网格布局） -->
      <div ref="jobListRef" class="jobs-page__list pr5 scrollbar-thin" :style="restoring ? { visibility: 'hidden' } : {}" @scroll="onListScroll">
        <div class="jobs-page__grid">
          <div
            v-for="(job, index) in jobList"
            :key="index"
            class="jobs-page__job-card"
            :style="{ background: cardBgGradient(job.matchScore) }"
            @click="goToDetail(job)"
          >
            <!-- 上半部分：岗位信息 + 匹配度 -->
            <div class="jobs-page__card-top">
              <div class="jobs-page__card-top-left">
                <!-- 岗位名称 -->
                <div class="jobs-page__card-title">{{ job.title }}</div>
                <!-- 标签行：城市 + 招聘分类 + 学历 -->
                <div class="jobs-page__card-tags">
                  <span v-if="job.regionName" class="jobs-page__card-tag">{{ job.regionName }}</span>
                  <span v-if="formatEmploymentType(job.recruitCategory)" class="jobs-page__card-tag">{{ formatEmploymentType(job.recruitCategory) }}</span>
                  <span v-if="formatEducation(job.education)" class="jobs-page__card-tag">{{ formatEducation(job.education) }}</span>
                </div>
              </div>
              <!-- 右侧匹配度 -->
              <div v-if="isAuthenticated" class="jobs-page__card-match">
                <span class="jobs-page__card-match-score" :style="{ color: matchRingColor(job.matchScore) }">{{ job.matchScore }}%</span>
                <span class="jobs-page__card-match-label" :style="{ color: matchRingColor(job.matchScore) }">{{ matchLevelText(job.matchScore) }}</span>
              </div>
              <div v-else class="jobs-page__card-match jobs-page__card-match--locked">
                <svg class="jobs-page__card-lock-icon" viewBox="0 0 24 24" fill="none">
                  <rect x="5" y="11" width="14" height="10" rx="2" stroke="currentColor" stroke-width="1.5"/>
                  <path d="M8 11V7a4 4 0 118 0v4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
                </svg>
              </div>
            </div>

            <!-- 下半部分：公司信息 + 发布时间（默认显示） -->
            <div class="jobs-page__card-bottom jobs-page__card-bottom--info">
              <div class="jobs-page__card-company">
                <!-- 公司logo -->
                <img v-if="job.companyLogoUrl" class="jobs-page__card-company-logo" :src="job.companyLogoUrl" alt="" />
                <div v-else class="jobs-page__card-company-logo jobs-page__card-company-logo--default">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="12" fill="#EDF9FA"/><g clip-path="url(#clogo)"><path d="M5.99998 16.6667H6.66665V8.24001C6.66667 8.0301 6.73274 7.82552 6.8555 7.65526C6.97827 7.48499 7.15149 7.35767 7.35065 7.29134L12.684 5.51401C12.8343 5.46395 12.9943 5.45031 13.1509 5.47423C13.3076 5.49815 13.4562 5.55893 13.5848 5.65157C13.7133 5.74421 13.8179 5.86606 13.8901 6.00708C13.9623 6.1481 14 6.30425 14 6.46268V16.6667H14.6666V10.66C14.6667 10.6107 14.6776 10.562 14.6987 10.5175C14.7199 10.4729 14.7506 10.4336 14.7887 10.4024C14.8268 10.3711 14.8714 10.3487 14.9193 10.3368C14.9671 10.3249 15.017 10.3237 15.0653 10.3333L16.5293 10.6267C16.7559 10.672 16.9599 10.7944 17.1064 10.973C17.253 11.1517 17.3332 11.3756 17.3333 11.6067V16.6667H18C18.1768 16.6667 18.3464 16.7369 18.4714 16.8619C18.5964 16.987 18.6666 17.1565 18.6666 17.3333C18.6666 17.5102 18.5964 17.6797 18.4714 17.8047C18.3464 17.9298 18.1768 18 18 18H5.99998C5.82317 18 5.6536 17.9298 5.52858 17.8047C5.40355 17.6797 5.33331 17.5102 5.33331 17.3333C5.33331 17.1565 5.40355 16.987 5.52858 16.8619C5.6536 16.7369 5.82317 16.6667 5.99998 16.6667Z" fill="#52CAD1"/></g><defs><clipPath id="clogo"><rect width="16" height="16" fill="white" transform="translate(4 4)"/></clipPath></defs></svg>
                </div>
                <!-- 公司名称 -->
                <span class="jobs-page__card-company-name">{{ job.companyShortName || job.companyName }}</span>
                <!-- 公司类型标签 -->
                <span v-if="job.companyType" class="jobs-page__card-company-type">{{ job.companyType }}</span>
              </div>
              <!-- 发布时间 -->
              <span class="jobs-page__card-publish-time">{{ formatExpireAt(job.expireAt) }}</span>
            </div>

            <!-- 下半部分：hover 时显示操作按钮 -->
            <div class="jobs-page__card-bottom jobs-page__card-bottom--actions">
              <!-- 三点菜单按钮 -->
              <button class="jobs-page__card-more-btn" @click.stop="toggleCardMenu(index)" aria-label="更多">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="3" cy="8" r="1.5" fill="#6A7282"/><circle cx="8" cy="8" r="1.5" fill="#6A7282"/><circle cx="13" cy="8" r="1.5" fill="#6A7282"/></svg>
              </button>
              <!-- 问Nova按钮 -->
              <button class="jobs-page__card-ask-btn" @click.stop="askAssistant(job)">问Nova</button>
              <!-- 去投递按钮 -->
              <button class="jobs-page__card-apply-btn" @click.stop="handleReport(job)">去投递</button>

              <!-- 弹出菜单（收藏 + 不再显示） -->
              <div v-if="job.showMenu" class="jobs-page__card-popup" @click.stop>
                <div class="jobs-page__card-popup-item" @click.stop="handleCardFavorite(job)">
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M8 13.7l-1.1-1C3.6 9.8 1.5 7.9 1.5 5.7 1.5 3.9 2.9 2.5 4.7 2.5c1 0 2 .5 2.6 1.2h1.4c.6-.7 1.6-1.2 2.6-1.2 1.8 0 3.2 1.4 3.2 3.2 0 2.2-2.1 4.1-5.4 6.9L8 13.7z" stroke="#52CAD1" stroke-width="1" :fill="job.isFavorite ? '#52CAD1' : 'none'"/></svg>
                  <span>{{ job.isFavorite ? '取消收藏' : '收藏' }}</span>
                </div>
                <div class="jobs-page__card-popup-item" @click.stop="handleCardDislike(job)">
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="6.5" stroke="#6A7282" stroke-width="1"/><path d="M5 5L11 11M11 5L5 11" stroke="#6A7282" stroke-width="1" stroke-linecap="round"/></svg>
                  <span>不再显示</span>
                </div>
              </div>
            </div>

          </div>
        </div>
        <!-- 未登录时底部登录提示 -->
        <div v-if="!isAuthenticated && !loading && jobList.length > 0" class="jobs-page__login-prompt">
          <p class="jobs-page__login-prompt-title">登录后查看全部岗位</p>
          <p class="jobs-page__login-prompt-desc">登录即可解锁全部岗位及完整匹配信息</p>
          <button class="jobs-page__login-prompt-btn" @click="store.dispatch('openLogin')">立即登录</button>
        </div>
        <!-- 首次加载中提示 -->
        <div v-if="loading" class="jobs-page__loading-box">
          <div class="jobs-page__loading-spinner"></div>
          <span>加载中...</span>
        </div>
        <!-- 暂无数据提示 -->
        <div v-if="!loading && jobList.length === 0" class="jobs-page__empty">
          <img class="jobs-page__empty-img" src="@/assets/images/list-empty.png" alt="暂无数据" />
          <p class="jobs-page__empty-title">符合条件的岗位较少</p>
          <p class="jobs-page__empty-subtitle">试试 <span class="jobs-page__empty-link" @click="clearAllFilters">减少筛选条件</span> 或调整您意向的关键词哦~</p>
        </div>
        <!-- 列表结果少于5条时的提示 -->
        <div v-if="!loading && jobList.length > 0 && jobList.length < 5 && hasActiveFilters" class="jobs-page__few-results">
          <p class="jobs-page__empty-title">符合条件的岗位较少</p>
          <p class="jobs-page__empty-subtitle">试试 <span class="jobs-page__empty-link" @click="clearAllFilters">减少筛选条件</span> 或调整您意向的关键词哦~</p>
        </div>
        <!-- 加载更多提示 -->
        <div v-if="loadingMore" class="jobs-page__loading-box">
          <div class="jobs-page__loading-spinner"></div>
          <span>加载中...</span>
        </div>
        <div v-else-if="noMore && jobList.length > 0" class="jobs-page__loading-more">没有更多符合的职位了</div>
      </div>
    </div>
    <AiChat :jobId="currentAskJobId" />

    <!-- 职位不感兴趣反馈弹窗 -->
    <JobDislikeDialog ref="dislikeDialogRef" v-model="showDislikeDialog" :job-id="dislikeJobId" @disliked="removeDislikedJob" />

    <!-- 职位问题反馈弹窗 -->
    <JobFeedbackDialog ref="feedbackDialogRef" v-model="showFeedbackDialog" :job-id="feedbackJobId"  />

    <!-- 选择投递方式弹窗 -->
    <JobApplyMethodDialog
      ref="applyMethodDialogRef"
      v-model="showAgentRemindDialog"
      :source-url="pendingApplyUrl"
      :job-id="pendingApplyJobId"
      @open-member="showMemberDialog = true"
    />

    <!-- 会员购买弹窗 -->
    <MemberDialog v-model="showMemberDialog" />

    <!-- 简历快照预览抽屉（从右侧弹出） -->
    <Teleport to="body">
      <Transition name="jobs-resume-drawer">
        <div v-if="showResumeSnapshotDrawer" class="jobs-resume-drawer-mask" @click.self="closeResumeSnapshotDrawer">
          <div class="jobs-resume-drawer">
            <!-- 顶部标题栏 -->
            <div class="jobs-resume-drawer__header">
              <div class="jobs-resume-drawer__header-left">
                <div class="jobs-resume-drawer__close" @click="closeResumeSnapshotDrawer">
                  <svg viewBox="0 0 24 24" fill="none" class="jobs-resume-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="jobs-resume-drawer__title">简历快照</span>
              </div>
            </div>
            <!-- 简历内容 -->
            <div class="jobs-resume-drawer__body">
              <div v-if="resumeSnapshotLoading" class="jobs-resume-drawer__loading">
                <div class="jobs-page__loading-spinner"></div>
                <span>加载中...</span>
              </div>
              <JobResumeTemplate v-else-if="resumeSnapshotData" :resume-data="resumeSnapshotData" mode="preview" />
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>

  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { JOB_TYPE_OPTIONS, formatEmploymentType, formatEducation } from '@/stores/index'
import SideNav from '@/components/SideNav.vue'
import AiChat from '@/components/AiChat.vue'
import JobPageHeader from '@/components/JobPageHeader.vue'
import JobStatsOverview from '@/components/JobStatsOverview.vue'
import JobDislikeDialog from '@/components/JobDislikeDialog.vue'
import JobFeedbackDialog from '@/components/JobFeedbackDialog.vue'
import MemberDialog from '@/components/MemberDialog.vue'
import JobApplyMethodDialog from '@/components/JobApplyMethodDialog.vue'
import IndustrySelector from '@/components/tools/IndustrySelector.vue'
import JobCategorySelector from '@/components/tools/JobCategorySelector.vue'
import RegionSelector from '@/components/tools/RegionSelector.vue'


import { fetchJobList, fetchJobListCount, fetchJobListMatch, fetchFavoriteList, toggleJobFavorite, removeJobFavorite, fetchFavoriteCount, fetchApplyList, fetchApplyCount, removeJobFromList, fetchCustomizeResume, fetchHotIndustries, fetchHotCategories, fetchHotCities, fetchJobCount } from '@/api/jobs'
import type { JobListItem, JobListParams, FavoriteListParams, ApplyListParams, ApplyCountData, HotIndustryItem, HotCategoryItem, HotCityItem } from '@/api/jobs'
import { getTimeEvent, setTimeEvent, timestampToLocalDateTime } from '@/utils/time'
import { getDailyJobCount } from '@/utils/dailyJobCount'
import { fetchIndustryTree, fetchJobCategoryTree } from '@/api/common'
import type { IndustryItem, JobCategoryItem } from '@/api/common'
import { ElMessage } from 'element-plus'
import JobResumeTemplate from '@/components/JobResumeTemplate.vue'
import type { ResumeTemplateData } from '@/components/JobResumeTemplate.vue'



// 2. 注意：这里的字符串不需要再手动转义双引号了
const paymentFormHtml = ref(`
  <form name="punchout_form" method="post" action="https://openapi-sandbox.dl.alipaydev.com/gateway.do?charset=UTF-8&method=alipay.trade.page.pay&sign=o8MQ7cEAh4yrf6ri5iT9gXbtR%2BTncX36p9JNZf8nmXxEp1WKO6dF1HDC6DPF8nxJbus6OG9E5UPSoiHgqrEiu3aeOs4LMcYzXXZP0UQzG%2F6pXyZrvlL70G8uwpnV6MgQojzhKheG0vYIJgSPaGsHKjwcp%2BT8yOZg3eEDIgFYEBf2a3c7kANc7%2FuOOGCSD9Ip9zqwX9LQ3b433NPH3AbGQkFSLsdGOTY62I7yI8hEF7EM7nNm%2BYryieqju21yN76JrV4k%2BgIGHn83I5oT3y7zurzdTqHLD4UawpPWdJ5B7p6wnJ4cN4uzO8JgRpNqogYqqKBPcHIlB9o4uax3bcRqhg%3D%3D&notify_url=http%3A%2F%2F39.108.134.218%3A10106%2Fapi%2F%2Fpublic%2FalipayNotify%2Fpay&version=1.0&app_id=2018062160374941&sign_type=RSA2&timestamp=2026-05-20+15%3A29%3A21&alipay_sdk=alipay-sdk-java-4.40.791.ALL&format=json">
    <input type="hidden" name="biz_content" value='{"out_trade_no":"OP2057000709638877186","product_code":"FAST_INSTANT_TRADE_PAY","qr_pay_mode":"4","qrcode_width":200,"subject":"周会员","total_amount":"0.10"}'>
    <input type="submit" value="立即支付" style="display:none">
  </form>
  <script>document.forms[0].submit();<\/script>
`)

// ==================== 路由相关 ====================

const router = useRouter()
const route = useRoute()
const store = useStore()


// 声明友盟统计 _czc 对象
const _czc: any[] = (window as any)._czc || [];
(window as any)._czc = _czc;
// 绑定 siteid，请用您的 siteid 替换下方 "XXXXXXXX" 部分
_czc.push(["_setAccount", "1281490571"]);

/** 招聘分类标签背景色：校招=#3AC6E5，社招=#B95DDD，实习=#50D3B5 */
function recruitCategoryColor(category: number | undefined | null): string {
  if (category === 1) return '#3AC6E5'  // 校招
  if (category === 0) return '#B95DDD'  // 社招
  if (category === 2) return '#50D3B5'  // 实习
  return '#EDF9FA'
}

/** 登录状态 — 从 store 读取 */
const isAuthenticated = computed(() => store.state.isAuthenticated)

/** 用户昵称 — 从全局 store 读取 */
const nickName = computed(() => store.state.userInfo?.nick || '')

// ==================== 页面状态 ====================

/** 当前激活的 Tab，从 URL query 参数读取，默认"推荐" */
const activeTab = ref((route.query.tab as string) || 'recommend')

/** 是否为推荐列表 Tab */
const isRecommendTab = computed(() => activeTab.value === 'recommend')

// ==================== 岗位概览统计数据 ====================

/** 筛选面板 DOM 引用 */
const filtersPanelRef = ref<HTMLElement | null>(null)

/** 筛选面板高度（同步给 JobStatsOverview 卡片） */
const filtersPanelHeight = ref<string>('auto')

/** 监听筛选面板高度变化的 ResizeObserver */
let filtersPanelObserver: ResizeObserver | null = null

/** 今日新增岗位数量 */
const statsDailyJobCount = getDailyJobCount()

/** 全网岗位总数 */
const statsJobCount = ref(0)

/** 格式化岗位总数（万为单位） */
const statsFormattedJobCount = computed(() => {
  if (statsJobCount.value >= 10000) {
    return Math.floor(statsJobCount.value / 10000) + 'w'
  }
  return statsJobCount.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
})

/** 当前日期（MM.DD 格式） */
const statsCurrentDate = computed(() => {
  const now = new Date()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${month}.${day}`
})

/** 加载岗位总数 */
async function loadStatsJobCount() {
  try {
    const res = await fetchJobCount()
    if (res.code === '0' && res.data !== undefined) {
      statsJobCount.value = Number(res.data)
    }
  } catch (e) {
    console.error('加载岗位总数失败', e)
  }
}

/** 搜索框输入内容 */
const keyword = ref('')

/** 热门搜索标签列表 */
const hotSearchTags = ref(['系统集成', 'AI产品经理', '广告投放', 'AI开发', '大模型'])

/** 点击热门搜索标签 — 设置关键词并触发搜索 */
function handleHotSearch(tag: string) {
  keyword.value = tag
  reloadFirstPage()
}

/** 当前选中的职位卡片索引 */
const selectedIndex = ref(0)

/** 不感兴趣弹窗的显示状态 */
const showDislikeDialog = ref(false)

/** 当前操作的职位 ID（用于提交不感兴趣反馈） */
const dislikeJobId = ref<string | null>(null)

/** 问题反馈弹窗的显示状态 */
const showFeedbackDialog = ref(false)

/** 当前操作的职位 ID（用于提交问题反馈） */
const feedbackJobId = ref<string | null>(null)

/** 当前问助手的岗位 ID（传给 AiChat 组件） */
const currentAskJobId = ref<string>('')



/** 点击"问助手"按钮，传入岗位 ID 给 AiChat */
function askAssistant(job: JobItem) {
  currentAskJobId.value = job.id
}

/** 格式化发布时间显示（expireAt 字段） */
function formatExpireAt(expireAt?: string | null): string {
  if (!expireAt) return ''
  try {
    const date = new Date(expireAt)
    if (isNaN(date.getTime())) return ''
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${month}-${day}更新`
  } catch {
    return ''
  }
}

/** 切换卡片弹出菜单（三点按钮） */
function toggleCardMenu(index: number) {
  jobList.value.forEach((j, i) => {
    j.showMenu = i === index ? !j.showMenu : false
  })
}

/** 卡片弹出菜单中点击收藏/取消收藏 */
function handleCardFavorite(job: JobItem) {
  job.showMenu = false
  toggleFavorite(job)
}

/** 卡片弹出菜单中点击不再显示 */
function handleCardDislike(job: JobItem) {
  job.showMenu = false
  openDislikeDialog(job)
}

/** "更多"按钮触发器样式 — 灰色背景无hover变色 */
const moreBtnTriggerStyle: Record<string, string> = {
  'box-sizing': 'border-box',
  padding: '0.07rem 0.08rem',
  'font-size': '0.12rem',
  color: '#1A1A1A',
  background: '#F3F4F6',
  border: 'none',
  'border-radius': '0.04rem',
  'max-width': 'none',
  'justify-content': 'center',
  cursor: 'pointer',
}

/** "更多"按钮hover样式 — 不改变颜色 */
const moreBtnHoverStyle: Record<string, string> = {
  background: '#F3F4F6',
  color: '#1A1A1A',
}

/** 选择器显示文字的自定义样式，覆盖默认 max-width: 1.6rem */
const selectorDisplayStyle: Record<string, string> = {
  'max-width': 'none',
}

// ==================== 热门分类数据 ====================

/** 热门行业列表 */
const hotIndustries = ref<HotIndustryItem[]>([])

/** 热门岗位列表 */
const hotCategories = ref<HotCategoryItem[]>([])

/** 热门城市列表 */
const hotCities = ref<HotCityItem[]>([])

/** 加载热门推荐数据 */
async function loadHotFilters() {
  try {
    const [indRes, catRes, cityRes] = await Promise.all([
      fetchHotIndustries(),
      fetchHotCategories(),
      fetchHotCities(),
    ])
    if (indRes.code === '0' && indRes.data) hotIndustries.value = indRes.data
    if (catRes.code === '0' && catRes.data) hotCategories.value = catRes.data
    if (cityRes.code === '0' && cityRes.data) hotCities.value = cityRes.data
  } catch (e) {
    console.error('加载热门分类失败', e)
  }
}

/** 点击热门行业chip — 切换选中/取消 */
function toggleHotIndustry(id: number) {
  const current = [...selectedIndustryIds.value]
  const idx = current.indexOf(id)
  if (idx >= 0) {
    current.splice(idx, 1)
  } else {
    current.push(id)
  }
  store.dispatch('saveJobIntention', { ...store.state.jobIntention, industryIds: current })
}

/** 点击热门岗位chip — 切换选中/取消 */
function toggleHotCategory(id: number) {
  const current = [...selectedCategoryIds.value]
  const idx = current.indexOf(id)
  if (idx >= 0) {
    current.splice(idx, 1)
  } else {
    current.push(id)
  }
  store.dispatch('saveJobIntention', { ...store.state.jobIntention, categoryIds: current })
}

/** 点击热门城市chip — 切换选中/取消 */
function toggleHotCity(code: string) {
  const current = [...selectedRegionCodes.value]
  const idx = current.indexOf(code)
  if (idx >= 0) {
    current.splice(idx, 1)
  } else {
    current.push(code)
  }
  store.dispatch('saveJobIntention', { ...store.state.jobIntention, regionCodes: current })
}

/** 清空行业筛选 */
function clearIndustryFilter() {
  if (selectedIndustryIds.value.length === 0) return
  store.dispatch('saveJobIntention', { ...store.state.jobIntention, industryIds: [] })
}

/** 清空岗位筛选 */
function clearCategoryFilter() {
  if (selectedCategoryIds.value.length === 0) return
  store.dispatch('saveJobIntention', { ...store.state.jobIntention, categoryIds: [] })
}

/** 清空地区筛选 */
function clearRegionFilter() {
  if (selectedRegionCodes.value.length === 0) return
  store.dispatch('saveJobIntention', { ...store.state.jobIntention, regionCodes: [] })
}

// ==================== 额外chip：选择器选中但不在热门列表里的项 ====================

/** 额外行业chip（意向中选中的ID - 热门列表中的ID = 选择器里额外选的） */
const extraIndustryChips = computed<{ id: number; name: string }[]>(() => {
  const hotIdSet = new Set(hotIndustries.value.map(i => i.id))
  // 从完整行业树中查找名称
  const industries: IndustryItem[] = store.state.industries || []
  return selectedIndustryIds.value
    .filter(id => !hotIdSet.has(id))
    .map(id => {
      // 在完整树里找名称（ID可能是string或number类型，统一用String比较）
      const strId = String(id)
      for (const p of industries) {
        if (String(p.id) === strId) return { id, name: p.name }
        for (const c of p.children) {
          if (String(c.id) === strId) return { id, name: c.name }
        }
      }
      return null
    })
    .filter((item): item is { id: number; name: string } => !!(item && item.name))
})

/** 额外岗位chip（意向中选中的ID - 热门列表中的ID = 选择器里额外选的） */
const extraCategoryChips = computed<{ id: number; name: string }[]>(() => {
  const hotIdSet = new Set(hotCategories.value.map(i => i.id))
  const categories: JobCategoryItem[] = store.state.jobCategories || []
  return selectedCategoryIds.value
    .filter(id => !hotIdSet.has(id))
    .map(id => {
      const strId = String(id)
      for (const l1 of categories) {
        if (String(l1.id) === strId) return { id, name: l1.name }
        for (const l2 of l1.children) {
          if (String(l2.id) === strId) return { id, name: l2.name }
          if (l2.children) {
            for (const l3 of l2.children) {
              if (String(l3.id) === strId) return { id, name: l3.name }
            }
          }
        }
      }
      return null
    })
    .filter((item): item is { id: number; name: string } => !!(item && item.name))
})

/** 额外城市chip（意向中选中的code - 热门列表中的code = 选择器里额外选的） */
const extraCityChips = computed<{ code: string; name: string }[]>(() => {
  const hotCodeSet = new Set(hotCities.value.map(i => i.code))
  // 从完整地区树中查找名称
  const regions = store.state.regions || []
  return selectedRegionCodes.value
    .filter(code => !hotCodeSet.has(code))
    .map(code => {
      for (const province of regions) {
        for (const city of province.children) {
          if (city.code === code) return { code, name: city.name }
          if (city.children) {
            for (const district of city.children) {
              if (district.code === code) return { code, name: district.name }
            }
          }
        }
      }
      return null
    })
    .filter(Boolean) as { code: string; name: string }[]
})

// ==================== 学历要求筛选 ====================

/** 学历要求选项 */
const educationOptions = [
  { label: '不限', value: 0 },
  { label: '大专', value: 1 },
  { label: '本科', value: 2 },
  { label: '硕士', value: 3 },
  { label: '博士', value: 4 },
]

/** 学历下拉菜单显示状态 */
const showEducationDropdown = ref(false)

/** 已选学历（单选，0表示不限/未选） */
const selectedEducation = ref<number>(0)

/** 学历筛选显示文字 */
const educationFilterLabel = computed(() => {
  if (!selectedEducation.value) return '学历要求'
  return educationOptions.find(o => o.value === selectedEducation.value)?.label || '学历要求'
})

/** 选择学历（单选） */
function selectEducation(option: { label: string; value: number }) {
  selectedEducation.value = option.value === selectedEducation.value ? 0 : option.value
  showEducationDropdown.value = false
  reloadFirstPage()
}

// ==================== 发布时间筛选 ====================

/** 发布时间面板显示状态 */
const showPublishTimePanel = ref(false)

/** 发布时间范围 */
const publishTimeRange = ref<[Date, Date] | null>(null)

/** 发布时间显示文字 */
const publishTimeLabel = computed(() => {
  if (!publishTimeRange.value) return '发布时间'
  const [start, end] = publishTimeRange.value
  const fmt = (d: Date) => `${d.getMonth() + 1}/${d.getDate()}`
  return `${fmt(start)}-${fmt(end)}`
})

/** 发布时间变更回调 */
function onPublishTimeChange(val: [Date, Date] | null) {
  publishTimeRange.value = val
  showPublishTimePanel.value = false
  reloadFirstPage()
}

// ==================== 收藏统计 ====================

/** 收藏总数（用于 Tab 标签显示） */
const favoriteTotal = ref(0)

/** 有效收藏数 */
const favoriteValidCount = ref(0)

/** 失效收藏数 */
const favoriteInvalidCount = ref(0)

/** 加载收藏统计 */
async function loadFavoriteCount() {
  try {
    const res = await fetchFavoriteCount()
    if (res.code === '0' && res.data) {
      favoriteTotal.value = res.data.totalCount
      favoriteValidCount.value = res.data.validCount
      favoriteInvalidCount.value = res.data.invalidCount
    }
  } catch (e) {
    console.error('加载收藏统计失败', e)
  }
}

// ==================== 投递统计 ====================

/** 投递总数（用于 Tab 标签显示） */
const applyTotal = ref(0)

/** 投递统计详情 */
const applyCountData = ref<ApplyCountData>({
  totalCount: 0,
  appliedCount: 0,
  interviewingCount: 0,
  offerCount: 0,
  rejectedCount: 0,
  closedCount: 0,
})

/** 当前投递状态筛选（null=全部） */
const applyStatusFilter = ref<number | null>(null)

/** 投递状态 Tab 列表 */
const applyStatusTabs = computed(() => [
  { status: 0, label: '已投递', count: applyCountData.value.appliedCount },
  { status: 1, label: '面试中', count: applyCountData.value.interviewingCount },
  { status: 2, label: '有Offer', count: applyCountData.value.offerCount },
  { status: 3, label: '未通过', count: applyCountData.value.rejectedCount },
  { status: 4, label: '已结束', count: applyCountData.value.closedCount },
])

/** 切换投递状态筛选 */
function switchApplyStatus(status: number) {
  applyStatusFilter.value = applyStatusFilter.value === status ? null : status
  pageNum.value = 1
  hasNoMoreData.value = false
  jobList.value = []
  total.value = 0
  loadApplyList()
}

/** 加载投递统计 */
async function loadApplyCount() {
  try {
    const res = await fetchApplyCount()
    if (res.code === '0' && res.data) {
      applyCountData.value = res.data
      applyTotal.value = res.data.totalCount
    }
  } catch (e) {
    console.error('加载投递统计失败', e)
  }
}

// ==================== 常量数据 ====================

/** 筛选条件项类型 */
interface FilterItem {
  label: string
  key: string
  selected: string
}

/** 筛选条件列表 */
const filters = ref<FilterItem[]>([
  { label: '城市', key: 'city', selected: '' },
  { label: '岗位', key: 'position', selected: '' },
  { label: '行业', key: 'industry', selected: '' },
  { label: '招聘分类', key: 'jobType', selected: '' },
  { label: '公司类型', key: 'companyType', selected: '' },
])

/** 招聘分类选项映射：从全局 store 常量统一引入 */
const jobTypeOptions = JOB_TYPE_OPTIONS

/** 招聘分类下拉菜单是否显示 */
const showJobTypeDropdown = ref(false)

/** 公司类型选项（label=显示文字，value=传给接口的字符串数组） */
const companyTypeOptions: { label: string; value: string[] }[] = [
  { label: '全部', value: [] },
  { label: '央国企', value: ['央企', '国企'] },
  { label: '独角兽', value: ['独角兽'] },
  { label: '事业单位', value: ['事业单位'] },
  { label: '上市企业', value: ['上市企业'] },
  { label: '外资企业', value: ['外资企业'] },
  { label: '合资企业', value: ['合资企业'] },
  { label: '民营企业', value: ['民营企业'] },
]

/** 公司类型下拉菜单是否显示 */
const showCompanyTypeDropdown = ref(false)

/** localStorage 缓存 key（带用户 ID 隔离不同用户） */
const COMPANY_TYPE_CACHE_KEY = 'offerpai_jobs_company_type_filter_'

/** 获取当前用户的公司类型缓存 key */
function getCompanyTypeCacheKey(): string {
  const userId = store.state.userInfo?.id || 'anonymous'
  return COMPANY_TYPE_CACHE_KEY + userId
}

/** 从 localStorage 读取缓存的公司类型筛选 */
function loadCachedCompanyTypes(): string[] {
  try {
    const cached = localStorage.getItem(getCompanyTypeCacheKey())
    if (!cached || cached === 'null') return []
    return JSON.parse(cached) as string[]
  } catch {
    return []
  }
}

/** 保存公司类型筛选到 localStorage */
function saveCachedCompanyTypes(types: string[]) {
  const key = getCompanyTypeCacheKey()
  if (types.length === 0) {
    localStorage.setItem(key, 'null')
  } else {
    localStorage.setItem(key, JSON.stringify(types))
  }
}

/** 当前选中的公司类型（传给接口的字符串数组），onMounted 中从缓存恢复 */
const selectedCompanyTypes = ref<string[]>([])

/** 当前选中的招聘分类 — 直接读 store.jobIntention.recruitCategory */
const selectedEmploymentType = computed<number | null>(
  () => store.state.jobIntention.recruitCategory ?? null,
)

/** 选中的行业 id 数组 — 直接读 store.jobIntention.industryIds */
const selectedIndustryIds = computed<number[]>(
  () => store.state.jobIntention.industryIds || [],
)

/** 选中的岗位 id 数组 — 直接读 store.jobIntention.categoryIds */
const selectedCategoryIds = computed<number[]>(
  () => store.state.jobIntention.categoryIds || [],
)

/** 选中的地区编码数组 — 直接读 store.jobIntention.regionCodes */
const selectedRegionCodes = computed<string[]>(
  () => store.state.jobIntention.regionCodes || [],
)

/** AI 推荐的行业 ID 列表 */
const aiIndustryIds = computed<string[]>(
  () => store.state.jobIntention.aiIndustryIds || [],
)

/** AI 推荐的岗位 ID 列表 */
const aiCategoryIds = computed<string[]>(
  () => store.state.jobIntention.aiCategoryIds || [],
)

/** ====== AI 推荐提示条专用：完整分类树（含空分类） ====== */
const fullIndustryTree = ref<IndustryItem[]>([])
const fullJobCategoryTree = ref<JobCategoryItem[]>([])

/** 加载完整分类树数据（includeEmpty=true），仅用于 AI 推荐提示条 ID 转名称 */
async function loadFullCategoryTrees() {
  const [indRes, catRes] = await Promise.all([
    fetchIndustryTree({ includeEmpty: true }),
    fetchJobCategoryTree({ includeEmpty: true }),
  ])
  if (indRes && indRes.code === '0' && indRes.data) {
    fullIndustryTree.value = indRes.data
  }
  if (catRes && catRes.code === '0' && catRes.data) {
    fullJobCategoryTree.value = catRes.data
  }
}

/** 从完整行业树中根据 ID 查找名称 */
function resolveFullIndustryName(id: string): string {
  for (const parent of fullIndustryTree.value) {
    if (String(parent.id) === id) return parent.name
    for (const child of parent.children) {
      if (String(child.id) === id) return child.name
    }
  }
  return ''
}

/** 从完整岗位树中根据 ID 查找名称 */
function resolveFullCategoryName(id: string): string {
  for (const lv1 of fullJobCategoryTree.value) {
    if (String(lv1.id) === id) return lv1.name
    for (const lv2 of lv1.children) {
      if (String(lv2.id) === id) return lv2.name
      if (lv2.children) {
        for (const lv3 of lv2.children) {
          if (String(lv3.id) === id) return lv3.name
        }
      }
    }
  }
  return ''
}

/** AI 推荐的行业列表（ID + 名称，用于提示条展示和点击） */
const aiIndustryItems = computed<{ id: string; name: string }[]>(() => {
  if (!aiIndustryIds.value.length || !fullIndustryTree.value.length) return []
  const idSet = new Set(aiIndustryIds.value.map(String))
  const items: { id: string; name: string }[] = []
  for (const id of aiIndustryIds.value) {
    // 如果该 ID 是一级父节点且子节点也在列表中，跳过父级避免重复
    const parent = fullIndustryTree.value.find(p => String(p.id) === id)
    if (parent && parent.children?.some(c => idSet.has(String(c.id)))) {
      continue
    }
    const name = resolveFullIndustryName(id)
    if (name) items.push({ id, name })
  }
  return items
})

/** AI 推荐的岗位列表（ID + 名称，用于提示条展示和点击） */
const aiCategoryItems = computed<{ id: string; name: string }[]>(() => {
  if (!aiCategoryIds.value.length || !fullJobCategoryTree.value.length) return []
  const idSet = new Set(aiCategoryIds.value.map(String))
  const items: { id: string; name: string }[] = []
  for (const id of aiCategoryIds.value) {
    // 如果该 ID 是一级父节点且下级子节点也在列表中，跳过
    const lv1 = fullJobCategoryTree.value.find(p => String(p.id) === id)
    if (lv1 && lv1.children?.some(c => idSet.has(String(c.id)) || c.children?.some(leaf => idSet.has(String(leaf.id))))) {
      continue
    }
    // 如果该 ID 是二级节点且三级子节点也在列表中，跳过
    let isParentWithChild = false
    for (const cat of fullJobCategoryTree.value) {
      const lv2 = cat.children?.find(c => String(c.id) === id)
      if (lv2 && lv2.children?.some(leaf => idSet.has(String(leaf.id)))) {
        isParentWithChild = true
        break
      }
    }
    if (isParentWithChild) continue
    const name = resolveFullCategoryName(id)
    if (name) items.push({ id, name })
  }
  return items
})

/** AI 推荐的行业名称（兼容旧逻辑，拼接字符串用于条件判断） */
const aiIndustryNames = computed<string>(() => aiIndustryItems.value.map(i => i.name).join('、'))

/** AI 推荐的岗位名称（兼容旧逻辑，拼接字符串用于条件判断） */
const aiCategoryNames = computed<string>(() => aiCategoryItems.value.map(i => i.name).join('、'))

/** 是否显示 AI 推荐提示条 */
const showAiRecommendTip = computed(() => {
  return isRecommendTab.value && (aiIndustryNames.value || aiCategoryNames.value)
})

/** 行业选择变更回调 */
function onIndustryChange(ids: number[]) {
  store.dispatch('saveJobIntention', {
    ...store.state.jobIntention,
    industryIds: ids,
  })
}

/** 岗位选择变更回调 */
function onCategoryChange(ids: number[]) {
  store.dispatch('saveJobIntention', {
    ...store.state.jobIntention,
    categoryIds: ids,
  })
}

/** 点击 AI 推荐岗位词 — 将该岗位 ID 添加到筛选器（去重，最多3个） */
function handleAddCategory(id: string) {
  const numId = Number(id)
  const current = selectedCategoryIds.value
  if (current.includes(numId)) return // 已存在，不重复添加
  if (current.length >= 3) {
    ElMessage.warning('最多选择3个分类，请先去掉一个再添加')
    return
  }
  store.dispatch('saveJobIntention', {
    ...store.state.jobIntention,
    categoryIds: [...current, numId],
  })
}

/** 点击 AI 推荐行业词 — 将该行业 ID 添加到筛选器（去重，最多3个） */
function handleAddIndustry(id: string) {
  const numId = Number(id)
  const current = selectedIndustryIds.value
  if (current.includes(numId)) return // 已存在，不重复添加
  if (current.length >= 3) {
    ElMessage.warning('最多选择3个分类，请先去掉一个再添加')
    return
  }
  store.dispatch('saveJobIntention', {
    ...store.state.jobIntention,
    industryIds: [...current, numId],
  })
}

/** 地区选择变更回调 */
function onRegionChange(codes: string[]) {
  store.dispatch('saveJobIntention', {
    ...store.state.jobIntention,
    regionCodes: codes,
  })
}

/** 点击筛选条件按钮 — 仅招聘分类展开下拉 */
function handleFilterClick(filter: FilterItem) {
  if (filter.key === 'jobType') {
    showJobTypeDropdown.value = !showJobTypeDropdown.value
    showCompanyTypeDropdown.value = false
    showEducationDropdown.value = false
    showPublishTimePanel.value = false
  } else if (filter.key === 'companyType') {
    showCompanyTypeDropdown.value = !showCompanyTypeDropdown.value
    showJobTypeDropdown.value = false
    showEducationDropdown.value = false
    showPublishTimePanel.value = false
  }
}

/** 选中招聘分类选项 */
function selectJobType(filter: FilterItem, option: { label: string; value: number }) {
  filter.selected = option.label
  showJobTypeDropdown.value = false
  store.dispatch('saveJobIntention', {
    ...store.state.jobIntention,
    recruitCategory: option.value,
  })
}

/** 选中公司类型选项 */
function selectCompanyType(filter: FilterItem, option: { label: string; value: string[] }) {
  filter.selected = option.value.length ? option.label : ''
  showCompanyTypeDropdown.value = false
  selectedCompanyTypes.value = option.value
  saveCachedCompanyTypes(option.value)
  reloadFirstPage()
}

/** 监听 store 中 recruitCategory 变化，同步招聘分类筛选按钮的显示文字 */
watch(selectedEmploymentType, (val) => {
  const jobTypeFilter = filters.value.find(f => f.key === 'jobType')
  if (jobTypeFilter && val !== null) {
    const matched = jobTypeOptions.find(o => o.value === val)
    if (matched) jobTypeFilter.selected = matched.label
  }
}, { immediate: true })

/** 点击页面其他区域时关闭下拉菜单和卡片弹出菜单 */
function closeDropdownOnClickOutside(e: MouseEvent) {
  const target = e.target as HTMLElement
  // 排除 el-date-picker 的弹出面板（挂在body上）
  if (target.closest('.el-picker-panel') || target.closest('.el-date-picker') || target.closest('.el-popper')) return
  if (!target.closest('.jobs-page__dropdown-item')) {
    showJobTypeDropdown.value = false
    showCompanyTypeDropdown.value = false
    showEducationDropdown.value = false
  }
  // 关闭所有卡片弹出菜单
  if (!target.closest('.jobs-page__card-more-btn') && !target.closest('.jobs-page__card-popup')) {
    jobList.value.forEach(j => { j.showMenu = false })
  }
}

/** 跳转到原链接 — 选择投递方式弹窗 */
/**
 * 旧的提醒弹窗频率逻辑（已注销，保留不删）：
 * 1. 未登录用户：直接跳转外部链接，不弹窗
 * 2. 已登录用户首次点击（无 ai_agent_remind_first 缓存）：弹窗提醒，记录第一次提醒时间
 * 3. 有第一次记录但无第二次记录：
 *    - 距第一次记录 ≤ 1小时：直接跳转，不弹窗
 *    - 距第一次记录 > 1小时：弹窗提醒，记录第二次提醒时间
 * 4. 有第二次记录：
 *    - 距第二次记录 ≤ 7天：直接跳转，不弹窗
 *    - 距第二次记录 > 7天：弹窗提醒，更新第二次记录时间为当前时间
 */
// function handleReportOld(url: string) {
//   pendingApplyUrl.value = url
//   if (!isAuthenticated.value) { window.open(url, '_blank'); return }
//   const userId = store.state.userInfo?.id
//   if (!userId) { window.open(url, '_blank'); return }
//   const now = Date.now()
//   const firstTime = getTimeEvent('ai_agent_remind_first', userId)
//   const secondTime = getTimeEvent('ai_agent_remind_second', userId)
//   if (!firstTime) {
//     setTimeEvent('ai_agent_remind_first', userId, timestampToLocalDateTime(now))
//     showAgentRemindDialog.value = true; return
//   }
//   if (!secondTime) {
//     const firstTimestamp = new Date(firstTime).getTime()
//     const diffHours = (now - firstTimestamp) / (1000 * 60 * 60)
//     if (diffHours <= 1) { window.open(url, '_blank') }
//     else { setTimeEvent('ai_agent_remind_second', userId, timestampToLocalDateTime(now)); showAgentRemindDialog.value = true }
//     return
//   }
//   const secondTimestamp = new Date(secondTime).getTime()
//   const diffDays = (now - secondTimestamp) / (1000 * 60 * 60 * 24)
//   if (diffDays <= 7) { window.open(url, '_blank') }
//   else { setTimeEvent('ai_agent_remind_second', userId, timestampToLocalDateTime(now)); showAgentRemindDialog.value = true }
// }

/** 点击"去投递"按钮 — 每次都弹出选择投递方式弹窗 */
function handleReport(job: JobListItem) {
  // 暂存当前岗位信息
  pendingApplyUrl.value = job.sourceUrl
  pendingApplyJobId.value = job.id
  // 展示弹窗并调用组件 open 方法初始化
  showAgentRemindDialog.value = true
  nextTick(() => {
    applyMethodDialogRef.value?.open()
  })
}

// ==================== 选择投递方式弹窗状态 ====================

/** 弹窗组件 ref */
const applyMethodDialogRef = ref<InstanceType<typeof JobApplyMethodDialog> | null>(null)

/** 弹窗是否显示 */
const showAgentRemindDialog = ref(false)

/** 暂存待跳转的外部链接 */
const pendingApplyUrl = ref('')

/** 暂存当前触发弹窗的岗位 ID */
const pendingApplyJobId = ref('')

/** 会员购买弹窗显示状态 */
const showMemberDialog = ref(false)



onMounted(async () => {
  document.addEventListener('click', closeDropdownOnClickOutside)

  // 加载岗位总数
  loadStatsJobCount()

  // 监听筛选面板高度变化，同步给 JobStatsOverview
  nextTick(() => {
    if (filtersPanelRef.value) {
      filtersPanelHeight.value = filtersPanelRef.value.offsetHeight + 'px'
      filtersPanelObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
          filtersPanelHeight.value = entry.target.clientHeight + 'px'
        }
      })
      filtersPanelObserver.observe(filtersPanelRef.value)
    }
  })

  // 从缓存恢复公司类型筛选按钮的显示文字
  // 需要等 userInfo 加载后再读取（刷新时 userInfo 可能还没有）
  const restoreCompanyTypeFilter = () => {
    const cached = loadCachedCompanyTypes()
    if (cached.length) {
      selectedCompanyTypes.value = cached
      const matched = companyTypeOptions.find(o => JSON.stringify(o.value) === JSON.stringify(cached))
      const companyTypeFilter = filters.value.find(f => f.key === 'companyType')
      if (companyTypeFilter && matched) {
        companyTypeFilter.selected = matched.label
      }
    }
  }
  if (store.state.userInfo?.id) {
    restoreCompanyTypeFilter()
  } else {
    // userInfo 还没加载，监听变化后恢复
    const unwatch = watch(() => store.state.userInfo, (info) => {
      if (info?.id) {
        restoreCompanyTypeFilter()
        unwatch()
      }
    })
  }

  // 窗口 resize 时更新尖角位置
  window.addEventListener('resize', updateAiTipArrowPosition)

  // 监听列表容器宽度变化，动态设置网格列数
  nextTick(() => {
    if (jobListRef.value) {
      updateGridCols()
      gridResizeObserver = new ResizeObserver(updateGridCols)
      gridResizeObserver.observe(jobListRef.value)
    }
  })  // 加载完整分类树（含空分类），用于 AI 推荐提示条 ID 转名称
  loadFullCategoryTrees()

  // 加载热门推荐分类数据
  loadHotFilters()

  // 先判断是否有缓存（从详情页返回），在任何异步操作之前取出
  const cache = store.state.jobListCache
  const hasCache = !!(cache && cache.list.length > 0 && cache.tab === activeTab.value)

  if (hasCache) {
    // 立即恢复缓存数据，隐藏列表避免闪烁
    restoring.value = true
    jobList.value = cache!.list
    pageNum.value = cache!.pageNum
    total.value = cache!.total
    savedScrollTop = cache!.scrollTop
  }
  // 无论是否命中缓存，都清除，避免下次非详情页返回时误用
  if (cache) {
    store.commit('SET_JOB_LIST_CACHE', null)
  }

  // 进入 Jobs 页时加载公共工具数据（行业分类等）
  store.dispatch('loadCommonData')

  // 仅登录状态下才加载需要鉴权的数据
  if (isAuthenticated.value) {
    // 加载用户个人信息到全局 store
    store.dispatch('loadUserInfo')



    // 加载收藏统计（用于 Tab 标签显示）
    loadFavoriteCount()

    // 加载投递统计（用于 Tab 标签显示）
    loadApplyCount()

    // 加载求职意向数据，computed 会自动反映到筛选条件
    await store.dispatch('loadJobIntention')
  }

  if (hasCache) {
    // 从详情页返回，恢复滚动位置后再显示列表
    nextTick(() => {
      if (jobListRef.value) {
        jobListRef.value.scrollTop = savedScrollTop
      }
      restoring.value = false
    })
  } else {
    // 没有缓存，正常加载
    loadCurrentTab()
  }

  // 初始化完成，允许 watcher 正常工作
  // 使用双重 nextTick 确保 loadJobIntention 引起的所有响应式更新都已 flush
  nextTick(() => {
    nextTick(() => {
      initializing = false
      // 数据加载完成后计算尖角位置
      updateAiTipArrowPosition()
    })
  })
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeDropdownOnClickOutside)
  window.removeEventListener('resize', updateAiTipArrowPosition)
  // 清理筛选面板高度监听
  if (filtersPanelObserver) {
    filtersPanelObserver.disconnect()
    filtersPanelObserver = null
  }
  // 清理网格列数监听
  if (gridResizeObserver) {
    gridResizeObserver.disconnect()
    gridResizeObserver = null
  }
})

// ==================== 职位列表项（扩展接口字段，增加前端交互状态） ====================

/** 职位列表项类型（在接口返回基础上扩展前端交互字段） */
interface JobItem extends JobListItem {
  /** 是否已投递 */
  applied: boolean
  /** 是否显示弹出菜单 */
  showMenu: boolean
}

// ==================== 分页与加载状态 ====================

/** 当前页码 */
const pageNum = ref(1)

/** 每页条数 */
const pageSize = ref(15)

/** 总记录数 */
const total = ref(0)

/** 是否正在加载（首次加载） */
const loading = ref(false)

/** 是否正在加载下一页 */
const loadingMore = ref(false)

/** 接口返回空列表时标记为无更多数据 */
const hasNoMoreData = ref(false)

/** 是否已加载全部数据 */
const noMore = computed(() => hasNoMoreData.value || (jobList.value.length >= total.value && total.value > 0))

/** 职位列表数据 */
const jobList = ref<JobItem[]>([])

/** 列表容器 ref，用于监听滚动和恢复滚动位置 */
const jobListRef = ref<HTMLElement | null>(null)

/** ResizeObserver 实例，用于监听列表容器宽度变化动态设置列数 */
let gridResizeObserver: ResizeObserver | null = null

/** 根据列表容器宽度计算网格列数（最多3列，最少2列） */
function updateGridCols() {
  const el = jobListRef.value
  if (!el) return
  const width = el.clientWidth
  // 获取当前 scale 比例（小屏模式下 body 被 transform scale 缩放）
  const bodyTransform = document.body.style.transform
  let scale = 1
  const scaleMatch = bodyTransform.match(/scale\(([\d.]+)\)/)
  if (scaleMatch) {
    scale = parseFloat(scaleMatch[1]) || 1
  }
  // 容器实际可视宽度 = CSS宽度 * scale
  const visualWidth = width * scale
  // 每个卡片视觉上最少需要约 280px，3列需要 ≥ 840px 可视宽度
  const cols = visualWidth >= 840 ? 3 : 2
  el.style.setProperty('--job-grid-cols', String(cols))
}

/** 岗位筛选组件 ref（保留给模板绑定） */
const jobCategorySelectorRef = ref<InstanceType<typeof JobCategorySelector> | null>(null)

/** 行业筛选组件 ref（保留给模板绑定） */
const industrySelectorRef = ref<InstanceType<typeof IndustrySelector> | null>(null)

/** 城市筛选组件 ref（保留给模板绑定） */
const regionSelectorRef = ref<InstanceType<typeof RegionSelector> | null>(null)

/** 筛选条件按钮容器 ref，用于 DOM 查询获取 trigger 宽度 */
const filterGroupRef = ref<HTMLElement | null>(null)

/** AI 提示条尖角的 left 偏移量（像素），动态对齐岗位和行业选择器中间 */
const aiTipArrowLeft = ref(120)

/** 计算尖角位置：从 filter-group 容器直接查找 trigger DOM 获取宽度 */
function updateAiTipArrowPosition() {
  nextTick(() => {
    const group = filterGroupRef.value
    if (!group) return
    const regionTrigger = group.querySelector('.region-selector__trigger') as HTMLElement | null
    const categoryTrigger = group.querySelector('.job-category-selector__trigger') as HTMLElement | null
    if (!regionTrigger || !categoryTrigger) return
    // filter-group gap 为 0.08rem = 8px
    const gap = 8
    // 尖角 left = 城市trigger宽度 + 1gap + 岗位trigger宽度 + 半gap
    const left = regionTrigger.offsetWidth + gap + categoryTrigger.offsetWidth + gap / 2
    aiTipArrowLeft.value = left
  })
}

/** 监听选择器数据变化和提示条显示状态，DOM 更新后重新计算尖角位置 */
watch(
  [showAiRecommendTip, selectedCategoryIds, selectedRegionCodes,
   () => store.state.jobCategories, () => store.state.regions],
  () => {
    updateAiTipArrowPosition()
  },
  { flush: 'post', deep: true },
)

/** 记录离开页面前的滚动位置 */
let savedScrollTop = 0

/** 初始化标志 — onMounted 期间为 true，防止 watcher 误触发 reloadFirstPage */
let initializing = true

/** 恢复缓存中 — 为 true 时列表容器 visibility:hidden，避免滚动位置闪烁 */
const restoring = ref(false)
// ==================== 加载岗位列表 ====================

/** 组装请求参数 */
function buildParams(): JobListParams {
  const params: JobListParams = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  // 地区筛选
  if (selectedRegionCodes.value.length) {
    params.regionCodes = selectedRegionCodes.value
  }
  // 岗位类型筛选
  if (selectedCategoryIds.value.length) {
    params.categoryIds = selectedCategoryIds.value
  }
  // 行业筛选
  if (selectedIndustryIds.value.length) {
    params.industryIds = selectedIndustryIds.value
  }
  // 招聘分类筛选
  if (selectedEmploymentType.value !== null) {
    params.recruitCategory = selectedEmploymentType.value
  }
  // 搜索关键词
  if (keyword.value.trim()) {
    params.keyword = keyword.value.trim()
  }
  // 公司类型筛选
  if (selectedCompanyTypes.value.length) {
    params.companyTypes = selectedCompanyTypes.value
  }
  // 学历要求筛选
  if (selectedEducation.value) {
    params.educations = [selectedEducation.value]
  }
  // 发布时间筛选（转为ISO 8601字符串）
  if (publishTimeRange.value) {
    const [start, end] = publishTimeRange.value
    params.publishStartTime = new Date(start).toISOString()
    params.publishEndTime = new Date(end).toISOString()
  }
  return params
}

/** 加载岗位列表数据（首次加载，替换列表） */
async function loadJobList() {
  loading.value = true
  try {
    const res = await fetchJobList(buildParams())
    if (res.code === '0' && res.data) {
      // 将接口数据映射为前端 JobItem，补充交互状态字段
      jobList.value = res.data.list.map((item) => ({
        ...item,
        applied: false,
        showMenu: false,
      }))
      total.value = Number(res.data.total)
    }
  } catch (e) {
    console.error('加载岗位列表失败', e)
  } finally {
    loading.value = false
    // 登录状态下，首次加载后检查是否需要自动填满容器
    nextTick(() => { autoFillIfNeeded() })
  }
  // 加载完列表后查询筛选数量
  loadFilterJobCount()
}

/** 加载下一页数据（追加到列表末尾） */
async function loadNextPage() {
  if (loadingMore.value || noMore.value) return
  loadingMore.value = true
  pageNum.value++
  try {
    const res = await fetchJobList(buildParams())
    if (res.code === '0' && res.data) {
      const newItems = res.data.list.map((item) => ({
        ...item,
        applied: false,
        showMenu: false,
      }))
      // 返回空列表时标记无更多数据，停止滚动加载
      if (newItems.length === 0) {
        hasNoMoreData.value = true
        pageNum.value--
      } else {
        jobList.value.push(...newItems)
        total.value = Number(res.data.total)
      }
    }
  } catch (e) {
    // 加载失败时回退页码
    pageNum.value--
    console.error('加载下一页失败', e)
  } finally {
    loadingMore.value = false
    // 加载下一页后继续检查是否需要填满容器
    nextTick(() => { autoFillIfNeeded() })
  }
}

/** 自动填满容器：登录状态下，当推荐列表内容不足以产生滚动条且还有更多数据时，自动加载下一页 */
function autoFillIfNeeded() {
  // 未登录时不自动补全，只展示一页
  if (!isAuthenticated.value) return
  // 仅推荐Tab生效，收藏和已投递不处理
  if (!isRecommendTab.value) return
  const el = jobListRef.value
  if (!el) return
  // 如果容器没有滚动条（内容高度不超过可视高度）且还有更多数据未加载
  if (el.scrollHeight <= el.clientHeight && !noMore.value && !loadingMore.value && !loading.value) {
    loadNextPage()
  }
}

/** 列表滚动事件 — 滚动到底部时自动加载下一页 */
function onListScroll() {
  const el = jobListRef.value
  if (!el) return
  // 未登录时只展示一页，不加载更多
  if (!isAuthenticated.value) return
  // 距离底部小于 100px 时触发加载
  const threshold = 100
  if (el.scrollHeight - el.scrollTop - el.clientHeight < threshold) {
    if (isRecommendTab.value) {
      loadNextPage()
    } else if (activeTab.value === 'collected') {
      loadFavoriteNextPage()
    } else if (activeTab.value === 'applied') {
      loadApplyNextPage()
    }
  }
}

/** 筛选条件变化时重置到第一页并重新加载 */
function reloadFirstPage() {
  pageNum.value = 1
  hasNoMoreData.value = false
  jobList.value = []
  total.value = 0
  // 筛选条件变化时清除缓存
  store.commit('SET_JOB_LIST_CACHE', null)
  loadCurrentTab()
}

/** 是否有任何筛选条件或搜索关键词处于激活状态 */
const hasActiveFilters = computed(() => {
  return selectedCategoryIds.value.length > 0
    || selectedIndustryIds.value.length > 0
    || selectedRegionCodes.value.length > 0
    || selectedEmploymentType.value !== null
    || selectedCompanyTypes.value.length > 0
    || selectedEducation.value > 0
    || publishTimeRange.value !== null
    || keyword.value.trim() !== ''
})

// ==================== 筛选数量与深度匹配 ====================

/** 筛选岗位数量（/job/list/count 返回） */
const filterJobCount = ref<number | null>(null)

/** 是否正在加载筛选数量 */
const filterCountLoading = ref(false)

/** 是否显示筛选数量与深度匹配提示条（数量 < 2000 时显示） */
const showFilterCountBar = computed(() => {
  return filterJobCount.value !== null && filterJobCount.value < 5000 && isRecommendTab.value
})

/** 是否正在进行深度匹配查询 */
const deepMatchLoading = ref(false)

/** 加载筛选岗位数量 */
async function loadFilterJobCount() {
  filterCountLoading.value = true
  try {
    const params = buildParams()
    const res = await fetchJobListCount(params)
    if (res.code === '0' && res.data !== undefined) {
      filterJobCount.value = res.data
    }
  } catch (e) {
    console.error('加载筛选数量失败', e)
    filterJobCount.value = null
  } finally {
    filterCountLoading.value = false
  }
}

/** 点击深度匹配按钮 — 调用 /job/list/match 接口替换列表 */
async function handleDeepMatch() {
  deepMatchLoading.value = true
  pageNum.value = 1
  hasNoMoreData.value = false
  try {
    const res = await fetchJobListMatch(buildParams())
    if (res.code === '0' && res.data) {
      jobList.value = res.data.list.map((item) => ({
        ...item,
        applied: false,
        showMenu: false,
      }))
      total.value = Number(res.data.total)
    }
  } catch (e) {
    console.error('深度匹配失败', e)
  } finally {
    deepMatchLoading.value = false
  }
}

/** 清空所有筛选条件和搜索关键词，重新查询 */
function clearAllFilters() {
  // 清空搜索关键词
  keyword.value = ''
  // 清空公司类型（本地状态 + 缓存）
  selectedCompanyTypes.value = []
  saveCachedCompanyTypes([])
  // 清空学历和发布时间
  selectedEducation.value = 0
  publishTimeRange.value = null
  // 清空筛选按钮的显示文字
  filters.value.forEach(f => { f.selected = '' })
  // 清空 store 中的分类筛选条件
  store.dispatch('saveJobIntention', {
    ...store.state.jobIntention,
    categoryIds: [],
    industryIds: [],
    regionCodes: [],
    recruitCategory: null,
  })
}

/** 根据当前 Tab 加载对应列表 */
function loadCurrentTab() {
  if (isRecommendTab.value) {
    loadJobList()
  } else if (activeTab.value === 'collected') {
    loadFavoriteList()
  } else if (activeTab.value === 'applied') {
    loadApplyList()
  }
}

/** 加载收藏列表 */
async function loadFavoriteList() {
  loading.value = true
  try {
    const params: FavoriteListParams = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      valid: true,
    }
    const res = await fetchFavoriteList(params)
    if (res.code === '0' && res.data) {
      jobList.value = res.data.list.map((item) => ({
        ...item,
        applied: false,
        showMenu: false,
      }))
      total.value = Number(res.data.total)
    }
  } catch (e) {
    console.error('加载收藏列表失败', e)
  } finally {
    loading.value = false
  }
}

/** 加载收藏列表下一页 */
async function loadFavoriteNextPage() {
  if (loadingMore.value || noMore.value) return
  loadingMore.value = true
  pageNum.value++
  try {
    const params: FavoriteListParams = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      valid: true,
    }
    const res = await fetchFavoriteList(params)
    if (res.code === '0' && res.data) {
      const newItems = res.data.list.map((item) => ({
        ...item,
        applied: false,
        showMenu: false,
      }))
      // 返回空列表时标记无更多数据，停止滚动加载
      if (newItems.length === 0) {
        hasNoMoreData.value = true
        pageNum.value--
      } else {
        jobList.value.push(...newItems)
        total.value = Number(res.data.total)
      }
    }
  } catch (e) {
    pageNum.value--
    console.error('加载收藏列表下一页失败', e)
  } finally {
    loadingMore.value = false
  }
}

// ==================== 投递列表加载 ====================

/** 加载投递列表 */
async function loadApplyList() {
  loading.value = true
  try {
    const params: ApplyListParams = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }
    if (applyStatusFilter.value !== null) {
      params.status = applyStatusFilter.value
    }
    const res = await fetchApplyList(params)
    if (res.code === '0' && res.data) {
      jobList.value = res.data.list.map((item) => ({
        ...item,
        applied: true,
        showMenu: false,
      }))
      total.value = Number(res.data.total)
    }
  } catch (e) {
    console.error('加载投递列表失败', e)
  } finally {
    loading.value = false
  }
}

/** 加载投递列表下一页 */
async function loadApplyNextPage() {
  if (loadingMore.value || noMore.value) return
  loadingMore.value = true
  pageNum.value++
  try {
    const params: ApplyListParams = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }
    if (applyStatusFilter.value !== null) {
      params.status = applyStatusFilter.value
    }
    const res = await fetchApplyList(params)
    if (res.code === '0' && res.data) {
      const newItems = res.data.list.map((item) => ({
        ...item,
        applied: true,
        showMenu: false,
      }))
      // 返回空列表时标记无更多数据，停止滚动加载
      if (newItems.length === 0) {
        hasNoMoreData.value = true
        pageNum.value--
      } else {
        jobList.value.push(...newItems)
        total.value = Number(res.data.total)
      }
    }
  } catch (e) {
    pageNum.value--
    console.error('加载投递列表下一页失败', e)
  } finally {
    loadingMore.value = false
  }
}

// 监听筛选条件变化，自动重新加载
watch(
  [selectedRegionCodes, selectedCategoryIds, selectedIndustryIds, selectedEmploymentType],
  () => {
    // 初始化阶段（loadJobIntention 导致的变化）跳过，避免清掉缓存
    if (initializing) return
    reloadFirstPage()
    // 岗位选择器宽度可能变化，重新计算尖角位置
    updateAiTipArrowPosition()
  },
  { deep: true },
)



// 监听 Tab 切换，重置列表状态并加载对应数据
watch(activeTab, (newTab, oldTab) => {
  if (initializing) return

  // 收藏和投递 Tab 需要登录
  if ((newTab === 'collected' || newTab === 'applied') && !isAuthenticated.value) {
    // 回退到之前的 Tab，弹登录框
    nextTick(() => { activeTab.value = oldTab })
    store.dispatch('openLogin')
    return
  }

  // 同步 tab 到 URL query，刷新浏览器时能恢复正确的 Tab
  const query = { ...route.query }
  if (newTab === 'recommend') {
    delete query.tab
  } else {
    query.tab = newTab
  }
  router.replace({ query })

  jobList.value = []
  keyword.value = ''
  pageNum.value = 1
  total.value = 0
  hasNoMoreData.value = false
  loadCurrentTab()
  // 切换到收藏 Tab 时刷新统计
  if (newTab === 'collected') {
    loadFavoriteCount()
  }
  // 切换到投递 Tab 时刷新统计并重置筛选
  if (newTab === 'applied') {
    applyStatusFilter.value = null
    loadApplyCount()
  }
})

// ==================== 事件处理 ====================

/** 切换职位卡片的弹出菜单（同时关闭其他已打开的菜单） */
function toggleMenu(index: number) {
  jobList.value.forEach((j, i) => {
    j.showMenu = i === index ? !j.showMenu : false
  })
}

/** 处理弹出菜单操作项点击 */
function handlePopupAction(action: string, job: JobItem) {
  job.showMenu = false
  if (action === '从列表中移除') {
    handleRemoveFromList(job)
  } else if (action === '复制链接') {
    handleCopyLink(job)
  } else if (action === '问题反馈') {
    openFeedbackDialog(job)
  }
}

/** 复制职位原链接到剪贴板 */
async function handleCopyLink(job: JobItem) {
  try {
    await navigator.clipboard.writeText(job.sourceUrl)
    ElMessage.success('复制链接成功')
  } catch {
    ElMessage.error('复制链接失败')
  }
}

/** 从推荐列表中移除职位（前端移除 + 预留接口调用） */
async function handleRemoveFromList(job: JobItem) {
  try {
    // TODO: 接口对接后此处会真正调用后端，当前为模拟成功
    const res = await removeJobFromList(job.id)
    if (res.code === '0') {
      const index = jobList.value.findIndex(j => j.id === job.id)
      if (index !== -1) {
        jobList.value.splice(index, 1)
        total.value = Math.max(0, total.value - 1)
      }
      ElMessage.success('已从列表中移除')
    }
  } catch (e) {
    console.error('移除职位失败', e)
  }
}

/** 根据匹配分数返回对应的 CSS 类名 */
function matchClass(score: number) {
  if (score >= 80) return 'jobs-page__job-match--high'
  if (score >= 40) return 'jobs-page__job-match--medium'
  return 'jobs-page__job-match--low'
}

/** 根据匹配分数返回环形颜色 */
function matchRingColor(score: number) {
  if (score >= 80) return '#9FD051'
  if (score >= 40) return '#F59E0B'
  return '#FE6D52'
}

/** 根据匹配分数返回卡片右上角渐变背景：高=绿，中=橙，低=红 */
function cardBgGradient(score: number): string {
  let color = 'rgba(159, 208, 81, 0.16)' // 高匹配度绿色
  if (score < 80 && score >= 40) {
    color = 'rgba(245, 158, 11, 0.16)' // 中匹配度橙色
  } else if (score < 40) {
    color = 'rgba(254, 109, 82, 0.16)' // 低匹配度红色
  }
  return `radial-gradient(31.23% 47.59% at 100% 0%, ${color} 0%, rgba(255, 255, 255, 0.16) 100%), #FFFFFF`
}

/** 根据匹配分数返回匹配等级文案 */
function matchLevelText(score: number) {
  if (score >= 80) return '高匹配度'
  if (score >= 40) return '中匹配度'
  return '低匹配度'
}

/** 跳转到岗位详情页 — 未登录弹登录框，登录后再跳转 */
function goToDetail(job: JobItem) {
  // 保存当前列表状态到 store，返回时恢复
  store.commit('SET_JOB_LIST_CACHE', {
    tab: activeTab.value,
    list: jobList.value,
    pageNum: pageNum.value,
    total: total.value,
    scrollTop: jobListRef.value?.scrollTop ?? 0,
  })
  router.push(`/jobs/${job.id}`)
}

/** 不感兴趣弹窗和问题反馈弹窗的组件引用 */
const dislikeDialogRef = ref<InstanceType<typeof JobDislikeDialog> | null>(null)
const feedbackDialogRef = ref<InstanceType<typeof JobFeedbackDialog> | null>(null)

/** JobPageHeader 组件引用，用于刷新收藏/投递计数 */
const jobPageHeaderRef = ref<InstanceType<typeof JobPageHeader> | null>(null)

/** 收藏/取消收藏岗位 */
async function toggleFavorite(job: JobItem) {
  try {
    const res = job.isFavorite
      ? await removeJobFavorite(job.id)
      : await toggleJobFavorite(job.id)
    if (res.code === '0') {
      const wasFavorite = job.isFavorite
      job.isFavorite = !job.isFavorite
      ElMessage.success(wasFavorite ? '已取消收藏' : '收藏成功')
      // 刷新收藏统计
      loadFavoriteCount()
      // 同步刷新 JobPageHeader 组件内的收藏计数
      jobPageHeaderRef.value?.loadFavoriteCount()
    }
  } catch (e) {
    console.error('收藏操作失败', e)
  }
}

/** 收藏列表中取消收藏并移除该项 */
async function removeFavoriteFromList(job: JobItem, index: number) {
  try {
    const res = await removeJobFavorite(job.id)
    if (res.code === '0') {
      jobList.value.splice(index, 1)
      total.value = Math.max(0, total.value - 1)
      ElMessage.success('已取消收藏')
      loadFavoriteCount()
      // 同步刷新 JobPageHeader 组件内的收藏计数
      jobPageHeaderRef.value?.loadFavoriteCount()
    }
  } catch (e) {
    console.error('取消收藏失败', e)
  }
}

/** 打开不感兴趣弹窗 — 记录当前职位 ID 并重置表单 */
function openDislikeDialog(job: JobItem) {
  dislikeJobId.value = job.id
  dislikeDialogRef.value?.resetForm()
  showDislikeDialog.value = true
}

/** 不感兴趣提交成功后，从列表中移除该职位 */
function removeDislikedJob() {
  if (!dislikeJobId.value) return
  const index = jobList.value.findIndex(j => j.id === dislikeJobId.value)
  if (index !== -1) {
    jobList.value.splice(index, 1)
    total.value = Math.max(0, total.value - 1)
  }
}

/** 打开问题反馈弹窗 — 记录当前职位 ID 并重置表单 */
function openFeedbackDialog(job: JobItem) {
  feedbackJobId.value = job.id
  feedbackDialogRef.value?.resetForm()
  showFeedbackDialog.value = true
}

// ==================== 简历快照抽屉 ====================

/** 简历快照抽屉是否显示 */
const showResumeSnapshotDrawer = ref(false)

/** 简历快照加载状态 */
const resumeSnapshotLoading = ref(false)

/** 简历快照数据 */
const resumeSnapshotData = ref<ResumeTemplateData | null>(null)

/** 学历文字转数字 */
function degreeToNumber(degree?: string): number {
  const map: Record<string, number> = { '大专': 1, '本科': 2, '硕士': 3, '博士': 4 }
  return map[degree || ''] || 2
}

/** 将匹配度接口返回的简历数据映射为 ResumeTemplateData */
function mapResumeToTemplate(data: any): ResumeTemplateData {
  const r = data.resume || {}
  return {
    name: r.name || '未填写姓名',
    email: r.email || '',
    mobileNumber: r.mobileNumber || '',
    wechatNumber: r.wechatNumber || '',
    summary: r.summary || '',
    educations: (data.education || []).map((e: any) => ({
      school: e.school || '',
      major: e.major || '',
      degree: degreeToNumber(e.degree),
      startDate: e.startDate || '',
      endDate: e.endDate || '',
      description: (e.description || []).map((d: any) => ({ id: d.id, text: d.text || '' })),
    })),
    workExperiences: (data.work || []).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 || '' })),
    })),
    internships: (data.internship || []).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 || '' })),
    })),
    projects: (data.project || []).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 || '' })),
    })),
    competitions: (data.competition || []).map((c: any) => ({
      competitionName: c.competitionName || '',
      award: c.award || '',
      awardDate: c.awardDate || '',
      description: (c.description || []).map((d: any) => ({ id: d.id, text: d.text || '' })),
    })),
    skills: r.skills || [],
    certificates: r.certificates || [],
  }
}

/** 点击查看简历快照按钮 */
async function handleViewResumeSnapshot(job: JobItem) {
  showResumeSnapshotDrawer.value = true
  resumeSnapshotLoading.value = true
  resumeSnapshotData.value = null
  try {
    const res = await fetchCustomizeResume(String(job.id))
    if (res.code === 0 && res.data) {
      resumeSnapshotData.value = mapResumeToTemplate(res.data)
    } else {
      ElMessage.error('获取简历快照失败')
      showResumeSnapshotDrawer.value = false
    }
  } catch (e) {
    console.error('获取简历快照失败', e)
    ElMessage.error('获取简历快照失败')
    showResumeSnapshotDrawer.value = false
  } finally {
    resumeSnapshotLoading.value = false
  }
}

/** 关闭简历快照抽屉 */
function closeResumeSnapshotDrawer() {
  showResumeSnapshotDrawer.value = false
  resumeSnapshotData.value = null
}
</script>
