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

      <!-- 页面标题 -->
      <div class="bg-f mb16 prl24 ptb16 dflex aliite-c">
        <div class="dflex-start aliite-c">
          <h2 class="announcement-page__title">校招公告</h2>
          <span class="announcement-page__subtitle ml12">每日更新最新企业校招信息，助力你的求职之路</span>
        </div>
      </div>

      <!-- 筛选条件面板 -->
      <div class="announcement-page__filters-bar">
        <!-- 筛选面板 + 统计卡片横向排列 -->
        <div class="announcement-page__filters-row">
          <div ref="filtersPanelRef" class="announcement-page__filters-panel">
            <!-- 行业热门分类行 -->
            <div class="announcement-page__filter-row" v-if="hotIndustries.length > 0">
              <div class="announcement-page__filter-row-inner">
                <span class="announcement-page__filter-row-label">行业</span>
                <div class="announcement-page__filter-chips-wrap">
                  <div class="announcement-page__filter-chips">
                    <!-- 全部按钮 -->
                    <span
                      class="announcement-page__filter-chip"
                      :class="{ 'announcement-page__filter-chip--active-solid': selectedIndustryNames.length === 0 }"
                      @click="clearIndustryFilter"
                    >全部</span>
                    <!-- 热门行业chip -->
                    <span
                      v-for="item in hotIndustries"
                      :key="'hot-ind-' + item.id"
                      class="announcement-page__filter-chip"
                      :class="{ 'announcement-page__filter-chip--active': selectedIndustryNames.includes(item.name) }"
                      @click="toggleIndustry(item.name)"
                    >{{ 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="announcement-page__filter-row" v-if="hotCategories.length > 0">
              <div class="announcement-page__filter-row-inner">
                <span class="announcement-page__filter-row-label">岗位</span>
                <div class="announcement-page__filter-chips-wrap">
                  <div class="announcement-page__filter-chips">
                    <!-- 全部按钮 -->
                    <span
                      class="announcement-page__filter-chip"
                      :class="{ 'announcement-page__filter-chip--active-solid': selectedCategoryNames.length === 0 }"
                      @click="clearCategoryFilter"
                    >全部</span>
                    <!-- 热门岗位chip -->
                    <span
                      v-for="item in hotCategories"
                      :key="'hot-cat-' + item.id"
                      class="announcement-page__filter-chip"
                      :class="{ 'announcement-page__filter-chip--active': selectedCategoryNames.includes(item.name) }"
                      @click="toggleCategory(item.name)"
                    >{{ 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="announcement-page__filter-row" v-if="hotCities.length > 0">
              <div class="announcement-page__filter-row-inner">
                <span class="announcement-page__filter-row-label">地点</span>
                <div class="announcement-page__filter-chips-wrap">
                  <div class="announcement-page__filter-chips">
                    <!-- 全国按钮 -->
                    <span
                      class="announcement-page__filter-chip"
                      :class="{ 'announcement-page__filter-chip--active-solid': selectedCityNames.length === 0 }"
                      @click="clearCityFilter"
                    >全国</span>
                    <!-- 热门城市chip -->
                    <span
                      v-for="item in hotCities"
                      :key="'hot-city-' + item.code"
                      class="announcement-page__filter-chip"
                      :class="{ 'announcement-page__filter-chip--active': selectedCityNames.includes(item.name) }"
                      @click="toggleCity(item.name)"
                    >{{ 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="announcement-page__filter-row announcement-page__filter-row--bottom">
              <div class="announcement-page__filter-row-inner">
                <span class="announcement-page__filter-row-label">筛选</span>
                <div class="announcement-page__filter-dropdowns">
                  <!-- 毕业年份下拉 -->
                  <div class="announcement-page__dropdown-item" @click.stop="toggleDropdown('recruitYear')">
                    <span>{{ recruitYearLabel }}</span>
                    <svg class="announcement-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="showRecruitYearDropdown" class="announcement-page__filter-dropdown" @click.stop>
                      <div
                        class="announcement-page__filter-dropdown-item"
                        v-for="option in recruitYearOptions"
                        :key="option.value"
                        :class="{ 'announcement-page__filter-dropdown-item--active': selectedRecruitYear === option.value }"
                        @click.stop="selectRecruitYear(option.value)"
                      >{{ option.label }}</div>
                    </div>
                  </div>
                  <!-- 学历要求下拉 -->
                  <div class="announcement-page__dropdown-item" @click.stop="toggleDropdown('education')">
                    <span>{{ educationFilterLabel }}</span>
                    <svg class="announcement-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="announcement-page__filter-dropdown" @click.stop>
                      <div
                        class="announcement-page__filter-dropdown-item"
                        v-for="option in educationOptions"
                        :key="option"
                        :class="{ 'announcement-page__filter-dropdown-item--active': selectedEducationName === option }"
                        @click.stop="selectEducation(option)"
                      >{{ option }}</div>
                    </div>
                  </div>
                  <!-- 公司类型下拉 -->
                  <div class="announcement-page__dropdown-item" @click.stop="toggleDropdown('companyType')">
                    <span>{{ companyTypeLabel }}</span>
                    <svg class="announcement-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="announcement-page__filter-dropdown" @click.stop>
                      <div
                        class="announcement-page__filter-dropdown-item"
                        v-for="option in companyTypeOptions"
                        :key="option"
                        :class="{ 'announcement-page__filter-dropdown-item--active': selectedCompanyType === option }"
                        @click.stop="selectCompanyType(option)"
                      >{{ option }}</div>
                    </div>
                  </div>
                  <!-- 招聘批次下拉 -->
                  <div class="announcement-page__dropdown-item" @click.stop="toggleDropdown('batch')">
                    <span>{{ batchLabel }}</span>
                    <svg class="announcement-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="showBatchDropdown" class="announcement-page__filter-dropdown" @click.stop>
                      <div
                        class="announcement-page__filter-dropdown-item"
                        v-for="option in batchOptions"
                        :key="option"
                        :class="{ 'announcement-page__filter-dropdown-item--active': selectedBatchName === option }"
                        @click.stop="selectBatch(option)"
                      >{{ option }}</div>
                    </div>
                  </div>
                  <!-- 发布时间选择 -->
                  <div class="announcement-page__dropdown-item border-n announcement-page__dropdown-item--time">
                    <span>发布时间：</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="announcement-page__clear-filters" @click="clearAllFilters">清空筛选条件</span>
            </div>
          </div>
          <!-- 校招动态统计卡片 -->
          <JobStatsOverview
            title="校招动态"
            :subtitle="'数据截至 ' + statsCurrentDate"
            :todayCount="statsTodayCount"
            todayLabel="今日新增"
            :totalCount="statsTotalCompany"
            totalLabel="招聘中企业"
            :rateValue="statsDeadline7days"
            rateLabel="近7日截止"
            :cardHeight="filtersPanelHeight"
          />
        </div>
        <!-- 搜索框（独立在筛选面板下方） -->
        <div class="mt12 dflex aliite-c flex-warp">
          <div class="announcement-page__search-box fgrow1">
            <svg class="announcement-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="announcement-page__search-input"
              placeholder="搜索公司、公告标题或招聘岗位"
              @keyup.enter="reloadFirstPage"
            />
          </div>
          <div class="dflex aliite-c flex-warp ml24">
            <!-- 热门搜索标签 -->
            <span class="announcement-page__hot-search-label">热门搜索：</span>
            <span
              v-for="(tag, idx) in hotSearchTags"
              :key="idx"
              class="announcement-page__hot-search-tag"
              :class="{ 'announcement-page__hot-search-tag--active': keyword === tag }"
              @click="handleHotSearch(tag)"
            >{{ tag }}</span>
          </div>
        </div>
      </div>

      <!-- 公告列表（表格形式） -->
      <div ref="listRef" class="announcement-page__list scrollbar-thin" @scroll="onListScroll">
        <!-- 表头 -->
        <div class="announcement-page__table-header">
          <span class="announcement-page__th announcement-page__th--time flex0">发布时间</span>
          <span class="announcement-page__th announcement-page__th--company">公司/类型/行业</span>
          <span class="announcement-page__th announcement-page__th--title">公告标题</span>
          <span class="announcement-page__th announcement-page__th--position">招聘岗位/城市</span>
          <span class="announcement-page__th announcement-page__th--target">招聘对象</span>
          <span class="announcement-page__th announcement-page__th--major">专业要求</span>
          <span class="announcement-page__th announcement-page__th--batch">招聘批次</span>
          <span class="announcement-page__th announcement-page__th--deadline">截止日期</span>
        </div>
        <!-- 列表行 -->
        <div
          v-for="item in announcementList"
          :key="item.id"
          class="announcement-page__table-row"
          @click="goToDetail(item.id)"
          style="cursor: pointer;"
        >
          <!-- 发布时间 -->
          <span class="announcement-page__td announcement-page__td--time flex0 color-middle tac">{{ formatPublishTime(item) }}</span>
          <!-- 公司/类型/行业 -->
          <div class="announcement-page__td announcement-page__td--company">
            <div class="announcement-page__company-info">
              <img v-if="item.logoUrl" class="announcement-page__company-logo" :src="item.logoUrl" alt="" />
              <div v-else class="announcement-page__company-logo announcement-page__company-logo--default">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="12" fill="#EDF9FA"/><path d="M5.99998 16.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"/></svg>
              </div>
              <div class="announcement-page__company-text">
                <span class="announcement-page__company-name">{{ item.companyName }}</span>
                <div class="announcement-page__company-tags">
                  <span v-if="item.industryNames && item.industryNames.length" class="announcement-page__company-tag announcement-page__company-tag--industry">{{ item.industryNames.join('/') }}</span>
                </div>
              </div>
            </div>
          </div>
          <!-- 公告标题 -->
          <span class="announcement-page__td announcement-page__td--title" :title="item.title">{{ item.title }}</span>
          <!-- 招聘岗位/城市 -->
          <div class="announcement-page__td announcement-page__td--position">
            <span v-if="item.categoryNames && item.categoryNames.length" class="announcement-page__cell-line">{{ item.categoryNames.join('，') }}</span>
            <span v-if="item.cityNames && item.cityNames.length" class="announcement-page__cell-sub">{{ item.cityNames.join('、') }}</span>
          </div>
          <!-- 招聘对象 -->
          <div class="announcement-page__td announcement-page__td--target ">
            <span v-if="item.recruitYears && item.recruitYears.length" class="announcement-page__recruit-year">{{ item.recruitYears.map(y => y + '届').join(', ') }}</span>
            <span v-if="item.educationNames && item.educationNames.length" class="announcement-page__cell-sub ">{{ item.educationNames.join('、') }}</span>
          </div>
          <!-- 专业要求 -->
          <span class="announcement-page__td announcement-page__td--major" :title="item.majorRequire">{{ item.majorRequire || '专业不限' }}</span>
          <!-- 招聘批次 -->
          <span class="announcement-page__td announcement-page__td--batch">{{ item.batchNames && item.batchNames.length ? item.batchNames.join('、') : '' }}</span>
          <!-- 截止日期 -->
          <span class="announcement-page__td announcement-page__td--deadline">{{ formatApplyEndTime(item) }}</span>
        </div>

        <!-- 加载中 -->
        <div v-if="loading" class="announcement-page__loading-box">
          <div class="announcement-page__loading-spinner"></div>
          <span>加载中...</span>
        </div>
        <!-- 暂无数据 -->
        <div v-if="!loading && announcementList.length === 0" class="announcement-page__empty">
          <img class="announcement-page__empty-img" src="@/assets/images/list-empty.png" alt="暂无数据" />
          <p class="announcement-page__empty-title">暂无符合条件的校招公告</p>
          <p class="announcement-page__empty-subtitle">试试 <span class="announcement-page__empty-link" @click="clearAllFilters">减少筛选条件</span> 看看吧~</p>
        </div>
        <!-- 加载更多 -->
        <div v-if="loadingMore" class="announcement-page__loading-box">
          <div class="announcement-page__loading-spinner"></div>
          <span>加载中...</span>
        </div>
        <div v-else-if="noMore && announcementList.length > 0" class="announcement-page__loading-more">没有更多公告了</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import SideNav from '@/components/SideNav.vue'
import JobStatsOverview from '@/components/JobStatsOverview.vue'
import IndustrySelector from '@/components/tools/IndustrySelector.vue'
import JobCategorySelector from '@/components/tools/JobCategorySelector.vue'
import RegionSelector from '@/components/tools/RegionSelector.vue'
import { fetchAnnouncementList, fetchAnnouncementLastUpdateTime, fetchAnnouncementStatistics, fetchAnnouncementRecruitYearTags, fetchAnnouncementEducationOptions, fetchAnnouncementBatchOptions } from '@/api/announcement'
import type { AnnouncementListParams, AnnouncementItem } from '@/api/announcement'
import { fetchHotIndustries, fetchHotCategories, fetchHotCities } from '@/api/jobs'
import type { HotIndustryItem, HotCategoryItem, HotCityItem } from '@/api/jobs'
import type { IndustryItem, JobCategoryItem } from '@/api/common'

// ==================== 全局 Store ====================

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

/** 跳转公告详情页 */
function goToDetail(id: number) {
  router.push(`/announcement/${id}`)
}

// ==================== 筛选面板高度同步 ====================

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

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

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

// ==================== 统计卡片数据 ====================

/** 最新更新时间（MM.DD 格式，从后端获取） */
const statsCurrentDate = ref('--')

/** 今日新增公告数 */
const statsTodayCount = ref<string | number>('--')

/** 招聘中企业数（累计公告数） */
const statsTotalCompany = ref<string | number>('--')

/** 近7日截止数（本月新增） */
const statsDeadline7days = ref<string | number>('--')

/** 加载统计卡片数据 */
async function loadStatsData() {
  try {
    // 并发请求最新更新时间和统计数据
    const [timeRes, statsRes] = await Promise.all([
      fetchAnnouncementLastUpdateTime(),
      fetchAnnouncementStatistics(),
    ])
    // 解析最新更新时间（毫秒时间戳转 MM.DD）
    if (timeRes.code === '0' && timeRes.data) {
      const date = new Date(Number(timeRes.data))
      statsCurrentDate.value = `${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`
    }
    // 解析统计数据
    if (statsRes.code === '0' && statsRes.data) {
      statsTodayCount.value = statsRes.data.dayCount ?? 0
      statsTotalCompany.value = statsRes.data.totalCount ?? 0
      statsDeadline7days.value = statsRes.data.monthCount ?? 0
    }
  } catch (e) {
    console.error('加载统计数据失败', e)
  }
}

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

/** 热门行业列表 */
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)
  }
}

// ==================== 筛选状态 ====================

/** 选中的行业名称列表（传给接口） */
const selectedIndustryNames = ref<string[]>([])

/** 选中的行业 ID 列表（给 IndustrySelector 组件用） */
const selectedIndustryIds = ref<number[]>([])

/** 选中的岗位名称列表（传给接口） */
const selectedCategoryNames = ref<string[]>([])

/** 选中的岗位 ID 列表（给 JobCategorySelector 组件用） */
const selectedCategoryIds = ref<number[]>([])

/** 选中的城市名称列表（传给接口） */
const selectedCityNames = ref<string[]>([])

/** 选中的地区编码列表（给 RegionSelector 组件用） */
const selectedRegionCodes = ref<string[]>([])

/** 选中的学历要求名称（单选，空字符串表示未选） */
const selectedEducationName = ref<string>('')

/** 选中的招聘届数（单选，0表示未选/不限） */
const selectedRecruitYear = ref<number>(0)

/** 选中的公司类型（单选，空字符串表示未选） */
const selectedCompanyType = ref<string>('')

/** 选中的批次名称（单选，空字符串表示未选） */
const selectedBatchName = ref<string>('')

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

/** 搜索关键词 */
const keyword = ref('')

// ==================== 下拉菜单显示状态 ====================

const showRecruitYearDropdown = ref(false)
const showEducationDropdown = ref(false)
const showCompanyTypeDropdown = ref(false)
const showBatchDropdown = ref(false)

// ==================== 筛选选项常量 ====================

/** 毕业年份选项（从后端接口获取） */
const recruitYearOptions = ref<{ label: string; value: number }[]>([{ label: '全部', value: 0 }])

/** 加载毕业年份标签 */
async function loadRecruitYearTags() {
  try {
    const res = await fetchAnnouncementRecruitYearTags()
    if (res.code === '0' && res.data) {
      recruitYearOptions.value = [
        { label: '全部', value: 0 },
        ...res.data.map((year: number) => ({ label: `${year}届`, value: year })),
      ]
    }
  } catch (e) {
    console.error('加载毕业年份标签失败', e)
  }
}

/** 学历要求选项（从后端接口获取） */
const educationOptions = ref<string[]>(['不限'])

/** 加载学历筛选选项 */
async function loadEducationOptions() {
  try {
    const res = await fetchAnnouncementEducationOptions()
    if (res.code === '0' && res.data) {
      educationOptions.value = ['不限', ...res.data]
    }
  } catch (e) {
    console.error('加载学历选项失败', e)
  }
}

/** 公司类型选项 */
const companyTypeOptions = ['全部', '央企', '国企', '上市企业', '外资企业', '民营企业', '事业单位']

/** 招聘批次选项（从后端接口获取） */
const batchOptions = ref<string[]>(['全部'])

/** 加载招聘批次选项 */
async function loadBatchOptions() {
  try {
    const res = await fetchAnnouncementBatchOptions()
    if (res.code === '0' && res.data) {
      batchOptions.value = ['全部', ...res.data]
    }
  } catch (e) {
    console.error('加载招聘批次选项失败', e)
  }
}

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

// ==================== 筛选显示标签 ====================

/** 毕业年份筛选显示文字 */
const recruitYearLabel = computed(() => {
  if (!selectedRecruitYear.value) return '毕业年份'
  return selectedRecruitYear.value + '届'
})

/** 学历要求筛选显示文字 */
const educationFilterLabel = computed(() => {
  if (!selectedEducationName.value) return '学历要求'
  return selectedEducationName.value
})

/** 公司类型筛选显示文字 */
const companyTypeLabel = computed(() => {
  if (!selectedCompanyType.value) return '公司类型'
  return selectedCompanyType.value
})

/** 招聘批次筛选显示文字 */
const batchLabel = computed(() => {
  if (!selectedBatchName.value) return '招聘批次'
  return selectedBatchName.value
})

// ==================== 筛选操作方法 ====================

/** 切换下拉菜单 */
function toggleDropdown(type: string) {
  showRecruitYearDropdown.value = type === 'recruitYear' ? !showRecruitYearDropdown.value : false
  showEducationDropdown.value = type === 'education' ? !showEducationDropdown.value : false
  showCompanyTypeDropdown.value = type === 'companyType' ? !showCompanyTypeDropdown.value : false
  showBatchDropdown.value = type === 'batch' ? !showBatchDropdown.value : false
}

/** 切换行业选中（按名称） */
function toggleIndustry(name: string) {
  const idx = selectedIndustryNames.value.indexOf(name)
  if (idx >= 0) {
    selectedIndustryNames.value.splice(idx, 1)
  } else {
    selectedIndustryNames.value.push(name)
  }
  // 同步 ID 给选择器组件
  syncIndustryIds()
  reloadFirstPage()
}

/** 清空行业筛选 */
function clearIndustryFilter() {
  if (selectedIndustryNames.value.length === 0) return
  selectedIndustryNames.value = []
  selectedIndustryIds.value = []
  reloadFirstPage()
}

/** IndustrySelector 回调 — 根据选中的 ID 反查名称 */
function onIndustryChange(ids: number[]) {
  selectedIndustryIds.value = ids
  // 从完整行业树中反查名称
  const industries: IndustryItem[] = store.state.industries || []
  const names: string[] = []
  for (const id of ids) {
    const strId = String(id)
    for (const p of industries) {
      if (String(p.id) === strId) { names.push(p.name); break }
      const child = p.children.find(c => String(c.id) === strId)
      if (child) { names.push(child.name); break }
    }
  }
  selectedIndustryNames.value = names
  reloadFirstPage()
}

/** 从名称同步行业 ID（给选择器组件） */
function syncIndustryIds() {
  const industries: IndustryItem[] = store.state.industries || []
  const ids: number[] = []
  for (const name of selectedIndustryNames.value) {
    for (const p of industries) {
      if (p.name === name) { ids.push(Number(p.id)); break }
      const child = p.children.find(c => c.name === name)
      if (child) { ids.push(Number(child.id)); break }
    }
  }
  selectedIndustryIds.value = ids
}

/** 切换岗位选中（按名称） */
function toggleCategory(name: string) {
  const idx = selectedCategoryNames.value.indexOf(name)
  if (idx >= 0) {
    selectedCategoryNames.value.splice(idx, 1)
  } else {
    selectedCategoryNames.value.push(name)
  }
  syncCategoryIds()
  reloadFirstPage()
}

/** 清空岗位筛选 */
function clearCategoryFilter() {
  if (selectedCategoryNames.value.length === 0) return
  selectedCategoryNames.value = []
  selectedCategoryIds.value = []
  reloadFirstPage()
}

/** JobCategorySelector 回调 — 根据选中的 ID 反查名称 */
function onCategoryChange(ids: number[]) {
  selectedCategoryIds.value = ids
  const categories: JobCategoryItem[] = store.state.jobCategories || []
  const names: string[] = []
  for (const id of ids) {
    const strId = String(id)
    for (const l1 of categories) {
      if (String(l1.id) === strId) { names.push(l1.name); break }
      for (const l2 of l1.children) {
        if (String(l2.id) === strId) { names.push(l2.name); break }
        if (l2.children) {
          const l3 = l2.children.find(c => String(c.id) === strId)
          if (l3) { names.push(l3.name); break }
        }
      }
    }
  }
  selectedCategoryNames.value = names
  reloadFirstPage()
}

/** 从名称同步岗位 ID（给选择器组件） */
function syncCategoryIds() {
  const categories: JobCategoryItem[] = store.state.jobCategories || []
  const ids: number[] = []
  for (const name of selectedCategoryNames.value) {
    for (const l1 of categories) {
      if (l1.name === name) { ids.push(Number(l1.id)); break }
      for (const l2 of l1.children) {
        if (l2.name === name) { ids.push(Number(l2.id)); break }
        if (l2.children) {
          const l3 = l2.children.find(c => c.name === name)
          if (l3) { ids.push(Number(l3.id)); break }
        }
      }
    }
  }
  selectedCategoryIds.value = ids
}

/** 切换城市选中（按名称） */
function toggleCity(name: string) {
  const idx = selectedCityNames.value.indexOf(name)
  if (idx >= 0) {
    selectedCityNames.value.splice(idx, 1)
  } else {
    selectedCityNames.value.push(name)
  }
  syncRegionCodes()
  reloadFirstPage()
}

/** 清空城市筛选 */
function clearCityFilter() {
  if (selectedCityNames.value.length === 0) return
  selectedCityNames.value = []
  selectedRegionCodes.value = []
  reloadFirstPage()
}

/** RegionSelector 回调 — 根据选中的编码反查名称 */
function onRegionChange(codes: string[]) {
  selectedRegionCodes.value = codes
  const regions = store.state.regions || []
  const names: string[] = []
  for (const code of codes) {
    for (const province of regions) {
      for (const city of province.children) {
        if (city.code === code) { names.push(city.name); break }
      }
    }
  }
  selectedCityNames.value = names
  reloadFirstPage()
}

/** 从名称同步地区编码（给选择器组件） */
function syncRegionCodes() {
  const regions = store.state.regions || []
  const codes: string[] = []
  for (const name of selectedCityNames.value) {
    for (const province of regions) {
      for (const city of province.children) {
        if (city.name === name) { codes.push(city.code); break }
      }
    }
  }
  selectedRegionCodes.value = codes
}

/** 切换毕业年份选中 */
/** 选择毕业年份（单选） */
function selectRecruitYear(value: number) {
  selectedRecruitYear.value = value === selectedRecruitYear.value ? 0 : value
  showRecruitYearDropdown.value = false
  reloadFirstPage()
}

/** 选择学历（单选） */
function selectEducation(value: string) {
  if (value === '不限') {
    selectedEducationName.value = ''
  } else {
    selectedEducationName.value = value === selectedEducationName.value ? '' : value
  }
  showEducationDropdown.value = false
  reloadFirstPage()
}

/** 选择公司类型（单选） */
function selectCompanyType(value: string) {
  if (value === '全部') {
    selectedCompanyType.value = ''
  } else {
    selectedCompanyType.value = value === selectedCompanyType.value ? '' : value
  }
  showCompanyTypeDropdown.value = false
  reloadFirstPage()
}

/** 选择批次（单选） */
function selectBatch(value: string) {
  if (value === '全部') {
    selectedBatchName.value = ''
  } else {
    selectedBatchName.value = value === selectedBatchName.value ? '' : value
  }
  showBatchDropdown.value = false
  reloadFirstPage()
}

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

/** 清空所有筛选条件 */
function clearAllFilters() {
  selectedIndustryNames.value = []
  selectedIndustryIds.value = []
  selectedCategoryNames.value = []
  selectedCategoryIds.value = []
  selectedCityNames.value = []
  selectedRegionCodes.value = []
  selectedEducationName.value = ''
  selectedRecruitYear.value = 0
  selectedCompanyType.value = ''
  selectedBatchName.value = ''
  publishTimeRange.value = null
  keyword.value = ''
  reloadFirstPage()
}

/** 是否有任何筛选条件处于激活状态 */
const hasActiveFilters = computed(() => {
  return selectedIndustryNames.value.length > 0
    || selectedCategoryNames.value.length > 0
    || selectedCityNames.value.length > 0
    || selectedEducationName.value !== ''
    || selectedRecruitYear.value !== 0
    || selectedCompanyType.value !== ''
    || selectedBatchName.value !== ''
    || publishTimeRange.value !== null
    || keyword.value.trim() !== ''
})

/** 点击热门搜索标签 */
function handleHotSearch(tag: string) {
  keyword.value = tag
  reloadFirstPage()
}

// ==================== "更多"按钮样式 ====================

/** "更多"按钮触发器样式 */
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',
}

/** 选择器显示文字自定义样式 */
const selectorDisplayStyle: Record<string, string> = {
  'max-width': 'none',
}

// ==================== 列表数据与分页 ====================

/** 当前页码 */
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 || (announcementList.value.length >= total.value && total.value > 0))

/** 公告列表数据 */
const announcementList = ref<AnnouncementItem[]>([])

/** 列表容器 ref */
const listRef = ref<HTMLElement | null>(null)

// ==================== 列表请求逻辑 ====================

/** 组装请求参数 */
function buildParams(): AnnouncementListParams {
  const params: AnnouncementListParams = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  if (keyword.value.trim()) params.keyword = keyword.value.trim()
  if (selectedIndustryNames.value.length) params.industryNames = selectedIndustryNames.value
  if (selectedCategoryNames.value.length) params.categoryNames = selectedCategoryNames.value
  if (selectedCityNames.value.length) params.cityNames = selectedCityNames.value
  if (selectedEducationName.value) params.educationNames = [selectedEducationName.value]
  if (selectedRecruitYear.value) params.recruitYears = [selectedRecruitYear.value]
  if (selectedCompanyType.value) params.companyTypes = [selectedCompanyType.value]
  if (selectedBatchName.value) params.batchNames = [selectedBatchName.value]
  // 发布时间转 Instant
  if (publishTimeRange.value) {
    const [start, end] = publishTimeRange.value
    params.publishTimeStart = { seconds: Math.floor(start.getTime() / 1000), nanos: 0 }
    params.publishTimeEnd = { seconds: Math.floor(end.getTime() / 1000), nanos: 0 }
  }
  return params
}

/** 加载公告列表（首次加载） */
async function loadList() {
  loading.value = true
  try {
    const res = await fetchAnnouncementList(buildParams())
    if (res.code === '0' && res.data) {
      announcementList.value = res.data.list || []
      total.value = res.data.total
    }
  } catch (e) {
    console.error('加载校招公告列表失败', e)
  } finally {
    loading.value = false
    // 首次加载后检查是否需要自动填满容器
    nextTick(() => { autoFillIfNeeded() })
  }
}

/** 加载下一页 */
async function loadNextPage() {
  if (loadingMore.value || noMore.value) return
  loadingMore.value = true
  pageNum.value++
  try {
    const res = await fetchAnnouncementList(buildParams())
    if (res.code === '0' && res.data) {
      const newItems = res.data.list || []
      if (newItems.length === 0) {
        hasNoMoreData.value = true
        pageNum.value--
      } else {
        announcementList.value.push(...newItems)
        total.value = res.data.total
      }
    }
  } catch (e) {
    pageNum.value--
    console.error('加载下一页失败', e)
  } finally {
    loadingMore.value = false
    // 加载下一页后继续检查是否需要填满容器
    nextTick(() => { autoFillIfNeeded() })
  }
}

/** 自动填满容器：当列表内容不足以产生滚动条且还有更多数据时，自动加载下一页 */
function autoFillIfNeeded() {
  const el = listRef.value
  if (!el) return
  // 如果容器没有滚动条（内容高度不超过可视高度）且还有更多数据未加载
  if (el.scrollHeight <= el.clientHeight && !noMore.value && !loadingMore.value && !loading.value) {
    loadNextPage()
  }
}

/** 列表滚动事件 — 触底自动加载 */
function onListScroll() {
  const el = listRef.value
  if (!el) return
  if (el.scrollHeight - el.scrollTop - el.clientHeight < 100) {
    loadNextPage()
  }
}

/** 筛选变化时重置到第一页 */
function reloadFirstPage() {
  pageNum.value = 1
  hasNoMoreData.value = false
  announcementList.value = []
  total.value = 0
  loadList()
}

// ==================== 时间格式化 ====================

/** 格式化发布时间（取月-日，如 "07-25"） */
function formatPublishTime(item: AnnouncementItem): string {
  if (!item.publishTime) return '--'
  try {
    const date = new Date(item.publishTime)
    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 formatApplyEndTime(item: AnnouncementItem): string {
  if (item.applyEndDesc) return item.applyEndDesc
  if (!item.applyEndTime || !item.applyEndTime.seconds) return '招满即止'
  try {
    const date = new Date(item.applyEndTime.seconds * 1000)
    if (isNaN(date.getTime())) return '招满即止'
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
  } catch {
    return '--'
  }
}

// ==================== 点击页面其他区域关闭下拉 ====================

function closeDropdownOnClickOutside(e: MouseEvent) {
  const target = e.target as HTMLElement
  if (target.closest('.el-picker-panel') || target.closest('.el-date-picker') || target.closest('.el-popper')) return
  if (!target.closest('.announcement-page__dropdown-item')) {
    showRecruitYearDropdown.value = false
    showEducationDropdown.value = false
    showCompanyTypeDropdown.value = false
    showBatchDropdown.value = false
  }
}

// ==================== 生命周期 ====================

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

  // 加载公共分类数据（行业、岗位、地区树）
  store.dispatch('loadCommonData')

  // 加载热门分类
  loadHotFilters()

  // 加载统计卡片数据（从后端接口获取）
  loadStatsData()

  // 加载毕业年份标签
  loadRecruitYearTags()

  // 加载学历筛选选项
  loadEducationOptions()

  // 加载招聘批次选项
  loadBatchOptions()

  // 监听筛选面板高度变化
  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)
    }
  })

  // 加载列表数据
  loadList()
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeDropdownOnClickOutside)
  if (filtersPanelObserver) {
    filtersPanelObserver.disconnect()
    filtersPanelObserver = null
  }
})
</script>
