<template>
  <!-- 校招公告Tab内容 -->
  <div class="home-announcement">
    <!-- 第一部分：校招公告，一站查全 -->
    <section class="home-announcement__section">
      <div class="home-announcement__header">
        <div class="">
          <h2 class="home-announcement__title">校招公告，一站查全</h2>
          <p class="home-announcement__subtitle">汇集企业官网、公众号和招聘专题页，优先看今天新动态</p>
        </div>
        <!-- 首页版校招动态统计卡片 -->
        <div class="home-announcement__stats-card">
          <!-- 标题区域 -->
          <div class="home-announcement__stats-title-wrap">
            <span class="home-announcement__stats-title">岗位概览</span>
            <span class="home-announcement__stats-date">数据截至 {{ statsCurrentDate }}</span>
          </div>
          <!-- 数据区域 -->
          <div class="home-announcement__stats-data">
            <!-- 今日新增 -->
            <div class="home-announcement__stats-item">
              <span class="home-announcement__stats-num">{{ statsTodayCount }}</span>
              <span class="home-announcement__stats-label">今日新增</span>
            </div>
            <!-- 分割线 -->
            <div class="home-announcement__stats-divider"></div>
            <!-- 本月新增 -->
            <div class="home-announcement__stats-item">
              <span class="home-announcement__stats-num">{{ statsMonthCount }}</span>
              <span class="home-announcement__stats-label">本月新增</span>
            </div>
            <!-- 分割线 -->
            <div class="home-announcement__stats-divider"></div>
            <!-- 累计收录 -->
            <div class="home-announcement__stats-item">
              <span class="home-announcement__stats-num">{{ statsTotalCount }}</span>
              <span class="home-announcement__stats-label">累计收录</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选面板（与岗位雷达一致） -->
      <div class="home-announcement__filters">
        <!-- 行业筛选行 -->
        <div class="home-announcement__filter-row">
          <span class="home-announcement__filter-label">行业</span>
          <div class="home-announcement__filter-chips">
            <span
              class="home-announcement__chip"
              :class="{ 'home-announcement__chip--active': selectedIndustryName === null }"
              @click="selectIndustry(null)"
            >全部</span>
            <span
              v-for="item in hotIndustries"
              :key="'ind-' + item.id"
              class="home-announcement__chip"
              :class="{ 'home-announcement__chip--active': selectedIndustryName === item.name }"
              @click="selectIndustry(item.name)"
            >{{ item.name }}</span>
          </div>
        </div>
        <!-- 城市筛选行 -->
        <div class="home-announcement__filter-row">
          <span class="home-announcement__filter-label">城市</span>
          <div class="home-announcement__filter-chips">
            <span
              class="home-announcement__chip"
              :class="{ 'home-announcement__chip--active': selectedCityName === null }"
              @click="selectCity(null)"
            >全部</span>
            <span
              v-for="item in hotCities"
              :key="'city-' + item.code"
              class="home-announcement__chip"
              :class="{ 'home-announcement__chip--active': selectedCityName === item.name }"
              @click="selectCity(item.name)"
            >{{ item.name }}</span>
          </div>
        </div>
        <!-- 岗位筛选行 -->
        <div class="home-announcement__filter-row">
          <span class="home-announcement__filter-label">岗位</span>
          <div class="home-announcement__filter-chips">
            <span
              class="home-announcement__chip"
              :class="{ 'home-announcement__chip--active': selectedCategoryName === null }"
              @click="selectCategory(null)"
            >全部</span>
            <span
              v-for="item in hotCategories"
              :key="'cat-' + item.id"
              class="home-announcement__chip"
              :class="{ 'home-announcement__chip--active': selectedCategoryName === item.name }"
              @click="selectCategory(item.name)"
            >{{ item.name }}</span>
          </div>
        </div>
      </div>

      <!-- 公告列表网格 -->
      <div class="home-announcement__grid">
        <div
          v-for="(item, index) in announcementList"
          :key="index"
          class="home-announcement__card"
          @click="goToDetail(item)"
        >
          <!-- 卡片主体 -->
          <div class="home-announcement__card-body">
            <!-- 左侧公司logo -->
            <div class="home-announcement__card-logo-wrap">
              <img v-if="item.logoUrl" class="home-announcement__card-logo" :src="item.logoUrl" alt="" />
              <div v-else class="home-announcement__card-logo home-announcement__card-logo--default">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="4" fill="#EDF9FA"/><g clip-path="url(#clogo3)"><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="clogo3"><rect width="16" height="16" fill="white" transform="translate(4 4)"/></clipPath></defs></svg>
              </div>
            </div>
            <!-- 右侧内容 -->
            <div class="home-announcement__card-content">
              <!-- 标题行 + 公司类型标签 -->
              <div class="home-announcement__card-title-row">
                <span class="home-announcement__card-title">{{ item.title }}</span>
                <span v-if="getCompanyType(item)" class="home-announcement__card-type-tag">{{ getCompanyType(item) }}</span>
              </div>
              <!-- 标签行：批次 + 学历 -->
              <div class="home-announcement__card-tags">
                <span v-if="item.batchNames && item.batchNames.length" class="home-announcement__card-tag home-announcement__card-tag--batch">{{ item.batchNames[0] }}</span>
                <span v-if="item.educationNames && item.educationNames.length" class="home-announcement__card-tag home-announcement__card-tag--edu">{{ item.educationNames[0] }}</span>
              </div>
              <!-- 岗位信息行 -->
              <div class="home-announcement__card-info-line">
                <svg class="home-announcement__card-icon" viewBox="0 0 16 16" fill="none">
                  <path d="M2.66669 12H13.3334V5.33333H2.66669V12ZM2.66669 4H13.3334V3.33333H2.66669V4ZM2.66669 12.6667C2.30002 12.6667 1.98602 12.5362 1.72469 12.2753C1.46402 12.0138 1.33335 11.6998 1.33335 11.3333V3.33333C1.33335 2.96667 1.46402 2.65289 1.72469 2.392C1.98602 2.13067 2.30002 2 2.66669 2H13.3334C13.7 2 14.014 2.13067 14.2754 2.392C14.5361 2.65289 14.6667 2.96667 14.6667 3.33333V11.3333C14.6667 11.6998 14.5361 12.0138 14.2754 12.2753C14.014 12.5362 13.7 12.6667 13.3334 12.6667H2.66669ZM4.66669 14H11.3334V13.3333H4.66669V14Z" fill="#64748B"/>
                </svg>
                <span>{{ formatCategories(item) }}</span>
              </div>
              <!-- 城市信息行 -->
              <div class="home-announcement__card-info-line">
                <svg class="home-announcement__card-icon" viewBox="0 0 16 16" fill="none">
                  <path d="M8 8.66667C8.36667 8.66667 8.68067 8.53622 8.942 8.27533C9.20289 8.01400 9.33333 7.7 9.33333 7.33333C9.33333 6.96667 9.20289 6.65289 8.942 6.392C8.68067 6.13067 8.36667 6 8 6C7.63333 6 7.31956 6.13067 7.05867 6.392C6.79733 6.65289 6.66667 6.96667 6.66667 7.33333C6.66667 7.7 6.79733 8.01400 7.05867 8.27533C7.31956 8.53622 7.63333 8.66667 8 8.66667ZM8 13.3C9.35556 12.0667 10.3751 10.9527 11.0587 9.958C11.7418 8.96378 12.0833 8.08889 12.0833 7.33333C12.0833 6.17778 11.7084 5.22222 10.9587 4.46667C10.2084 3.71111 9.2 3.33333 8 3.33333C6.8 3.33333 5.79156 3.71111 4.94133 4.46667C4.09156 5.22222 3.91667 6.17778 3.91667 7.33333C3.91667 8.08889 4.25844 8.96378 4.942 9.958C5.62511 10.9527 6.64444 12.0667 8 13.3Z" fill="#64748B"/>
                </svg>
                <span>{{ formatCities(item) }}</span>
              </div>
            </div>
          </div>
          <!-- 卡片底部渐变条 -->
          <div class="home-announcement__card-footer">
            <span class="home-announcement__card-update">{{ formatUpdateStatus(item) }}</span>
            <span class="home-announcement__card-deadline">{{ formatDeadline(item) }}</span>
          </div>
        </div>
      </div>

      <!-- 加载中 -->
      <div v-if="loading" class="home-announcement__loading">
        <div class="home-announcement__spinner"></div>
        <span>加载中...</span>
      </div>

      <!-- 查看更多按钮 -->
      <div v-if="!loading && announcementList.length > 0" class="home-announcement__more">
        <button class="home-announcement__more-btn" @click="router.push('/announcement')">查看更多</button>
      </div>
    </section>

    <!-- 第二部分：CTA区域 -->
    <section class="home-cta">
      <div class="home-cta__inner">
        <h2>让Offer派带你找到<br/>人生第一份好工作</h2>
        <button class="home-cta__btn" @click="router.push('/announcement')">免费体验</button>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { fetchAnnouncementList, fetchAnnouncementLastUpdateTime, fetchAnnouncementStatistics } from '@/api/announcement'
import type { AnnouncementItem } from '@/api/announcement'
import { fetchHotIndustries, fetchHotCategories, fetchHotCities } from '@/api/jobs'
import type { HotIndustryItem, HotCategoryItem, HotCityItem } from '@/api/jobs'

/** 路由实例 */
const router = useRouter()

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

/** 最新更新时间（MM.DD 格式） */
const statsCurrentDate = ref('--')
/** 今日新增 */
const statsTodayCount = ref<string | number>('--')
/** 本月新增 */
const statsMonthCount = ref<string | number>('--')
/** 累计收录 */
const statsTotalCount = ref<string | number>('--')

/** 加载统计卡片数据 */
async function loadStatsData() {
  try {
    const [timeRes, statsRes] = await Promise.all([
      fetchAnnouncementLastUpdateTime(),
      fetchAnnouncementStatistics(),
    ])
    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
      statsMonthCount.value = statsRes.data.monthCount ?? 0
      statsTotalCount.value = statsRes.data.totalCount ?? 0
    }
  } catch (e) {
    console.error('加载统计数据失败', e)
  }
}

// ==================== 筛选数据 ====================

/** 热门行业列表 */
const hotIndustries = ref<HotIndustryItem[]>([])
/** 热门城市列表 */
const hotCities = ref<HotCityItem[]>([])
/** 热门岗位列表 */
const hotCategories = ref<HotCategoryItem[]>([])

/** 当前选中的行业名称（null=全部） */
const selectedIndustryName = ref<string | null>(null)
/** 当前选中的城市名称（null=全部） */
const selectedCityName = ref<string | null>(null)
/** 当前选中的岗位名称（null=全部） */
const selectedCategoryName = ref<string | null>(null)

// ==================== 公告列表 ====================

/** 公告列表数据 */
const announcementList = ref<AnnouncementItem[]>([])
/** 加载状态 */
const loading = ref(false)

/** 选择行业 */
function selectIndustry(name: string | null) {
  selectedIndustryName.value = name
}

/** 选择城市 */
function selectCity(name: string | null) {
  selectedCityName.value = name
}

/** 选择岗位分类 */
function selectCategory(name: string | null) {
  selectedCategoryName.value = name
}

/** 加载公告列表（公告接口传名称） */
async function loadAnnouncementList() {
  loading.value = true
  try {
    const params: any = {
      pageNum: 1,
      pageSize: 30,
    }
    if (selectedIndustryName.value !== null) {
      params.industryNames = [selectedIndustryName.value]
    }
    if (selectedCityName.value !== null) {
      params.cityNames = [selectedCityName.value]
    }
    if (selectedCategoryName.value !== null) {
      params.categoryNames = [selectedCategoryName.value]
    }
    const res = await fetchAnnouncementList(params)
    if (res.code === '0' && res.data) {
      announcementList.value = res.data.list || []
    }
  } catch (e) {
    console.error('加载校招公告列表失败', e)
  } finally {
    loading.value = false
  }
}

/** 格式化岗位分类显示 */
function formatCategories(item: AnnouncementItem): string {
  if (!item.categoryNames || item.categoryNames.length === 0) return '暂无岗位信息'
  const maxShow = 3
  const shown = item.categoryNames.slice(0, maxShow).join(' / ')
  const totalCount = item.categoryNames.length
  if (totalCount <= maxShow) return shown
  return `${shown}等${totalCount}类`
}

/** 格式化城市显示 */
function formatCities(item: AnnouncementItem): string {
  if (!item.cityNames || item.cityNames.length === 0) return '全国'
  const maxShow = 3
  const shown = item.cityNames.slice(0, maxShow).join(' / ')
  const totalCount = item.cityNames.length
  if (totalCount <= maxShow) return shown
  return `${shown}等${totalCount}城`
}

/** 获取公司类型（从批次名中推断，暂用批次标签展示） */
function getCompanyType(_item: AnnouncementItem): string {
  // 公告列表数据无公司类型字段，暂不显示
  return ''
}

/** 格式化更新状态 */
function formatUpdateStatus(item: AnnouncementItem): string {
  if (!item.publishTime) return ''
  const now = new Date()
  const pub = new Date(item.publishTime)
  const diffDays = Math.floor((now.getTime() - pub.getTime()) / (1000 * 60 * 60 * 24))
  if (diffDays === 0) return '今日更新'
  if (diffDays === 1) return '昨日更新'
  if (diffDays <= 7) return `${diffDays}天前更新`
  const month = String(pub.getMonth() + 1).padStart(2, '0')
  const day = String(pub.getDate()).padStart(2, '0')
  return `${month}-${day}更新`
}

/** 格式化截止时间 */
function formatDeadline(item: AnnouncementItem): string {
  if (item.applyEndDesc) return item.applyEndDesc
  if (!item.applyEndTime || !item.applyEndTime.seconds) return '招满即止'
  const date = new Date(item.applyEndTime.seconds * 1000)
  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}截止`
}

/** 跳转公告详情 */
function goToDetail(item: AnnouncementItem) {
  router.push({ path: `/announcement/${item.id}`, query: { from: 'home' } })
}

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

// 监听筛选条件变化，刷新列表
watch([selectedIndustryName, selectedCityName, selectedCategoryName], () => {
  loadAnnouncementList()
})

onMounted(() => {
  loadHotFilters()
  loadAnnouncementList()
  loadStatsData()
})
</script>
