<template>
  <!-- 岗位雷达Tab内容 -->
  <div class="home-job-radar">
    <!-- 第一部分：全网优质岗位，实时精准匹配 -->
    <section class="home-job-radar__section">
      <div class="home-job-radar__header">
        <h2 class="home-job-radar__title">全网优质岗位，实时精准匹配</h2>
        <p class="home-job-radar__subtitle">实时汇聚全网企业名额信息, 综合求职意向与履历适配, 让每一次投递都是精准匹配, 更高效</p>
      </div>

      <!-- 筛选面板 -->
      <div class="home-job-radar__filters">
        <!-- 行业筛选行 -->
        <div class="home-job-radar__filter-row">
          <span class="home-job-radar__filter-label">行业</span>
          <div class="home-job-radar__filter-chips">
            <span
              class="home-job-radar__chip"
              :class="{ 'home-job-radar__chip--active': selectedIndustryId === null }"
              @click="selectIndustry(null)"
            >全部</span>
            <span
              v-for="item in hotIndustries"
              :key="'ind-' + item.id"
              class="home-job-radar__chip"
              :class="{ 'home-job-radar__chip--active': selectedIndustryId === item.id }"
              @click="selectIndustry(item.id)"
            >{{ item.name }}</span>
          </div>
        </div>
        <!-- 城市筛选行 -->
        <div class="home-job-radar__filter-row">
          <span class="home-job-radar__filter-label">城市</span>
          <div class="home-job-radar__filter-chips">
            <span
              class="home-job-radar__chip"
              :class="{ 'home-job-radar__chip--active': selectedCityCode === null }"
              @click="selectCity(null)"
            >全部</span>
            <span
              v-for="item in hotCities"
              :key="'city-' + item.code"
              class="home-job-radar__chip"
              :class="{ 'home-job-radar__chip--active': selectedCityCode === item.code }"
              @click="selectCity(item.code)"
            >{{ item.name }}</span>
          </div>
        </div>
        <!-- 岗位筛选行 -->
        <div class="home-job-radar__filter-row">
          <span class="home-job-radar__filter-label">岗位</span>
          <div class="home-job-radar__filter-chips">
            <span
              class="home-job-radar__chip"
              :class="{ 'home-job-radar__chip--active': selectedCategoryId === null }"
              @click="selectCategory(null)"
            >全部</span>
            <span
              v-for="item in hotCategories"
              :key="'cat-' + item.id"
              class="home-job-radar__chip"
              :class="{ 'home-job-radar__chip--active': selectedCategoryId === item.id }"
              @click="selectCategory(item.id)"
            >{{ item.name }}</span>
          </div>
        </div>
      </div>

      <!-- 岗位列表网格 -->
      <div class="home-job-radar__grid">
        <div
          v-for="(job, index) in jobList"
          :key="index"
          class="home-job-radar__card"
          @click="goToDetail(job)"
        >
          <!-- 上半部分：岗位标题 + 标签 -->
          <div class="home-job-radar__card-top">
            <div class="home-job-radar__card-title">{{ job.title }}</div>
            <div class="home-job-radar__card-tags">
              <span v-if="job.regionName" class="home-job-radar__card-tag">{{ job.regionName }}</span>
              <span v-if="formatEmploymentType(job.recruitCategory)" class="home-job-radar__card-tag">{{ formatEmploymentType(job.recruitCategory) }}</span>
              <span v-if="formatEducation(job.education)" class="home-job-radar__card-tag">{{ formatEducation(job.education) }}</span>
            </div>
          </div>
          <!-- 下半部分：公司信息 + 发布时间 -->
          <div class="home-job-radar__card-bottom">
            <div class="home-job-radar__card-company">
              <img v-if="job.companyLogoUrl" class="home-job-radar__card-logo" :src="job.companyLogoUrl" alt="" />
              <div v-else class="home-job-radar__card-logo home-job-radar__card-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(#clogo2)"><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="clogo2"><rect width="16" height="16" fill="white" transform="translate(4 4)"/></clipPath></defs></svg>
              </div>
              <span class="home-job-radar__card-company-name">{{ job.companyShortName || job.companyName }}</span>
              <span v-if="job.companyType" class="home-job-radar__card-company-type">{{ job.companyType }}</span>
            </div>
            <span class="home-job-radar__card-time">{{ formatExpireAt(job.expireAt) }}</span>
          </div>
        </div>
      </div>

      <!-- 加载中 -->
      <div v-if="loading" class="home-job-radar__loading">
        <div class="home-job-radar__spinner"></div>
        <span>加载中...</span>
      </div>

      <!-- 查看更多按钮 -->
      <div v-if="!loading && jobList.length > 0" class="home-job-radar__more">
        <button class="home-job-radar__more-btn" @click="router.push('/jobs')">查看更多</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('/jobs')">免费体验</button>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { fetchJobList, fetchHotIndustries, fetchHotCategories, fetchHotCities } from '@/api/jobs'
import type { JobListItem, HotIndustryItem, HotCategoryItem, HotCityItem } from '@/api/jobs'
import { formatEmploymentType, formatEducation } from '@/stores/index'

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

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

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

/** 当前选中的行业ID（null=全部） */
const selectedIndustryId = ref<number | null>(null)
/** 当前选中的城市编码（null=全部） */
const selectedCityCode = ref<string | null>(null)
/** 当前选中的岗位ID（null=全部） */
const selectedCategoryId = ref<number | null>(null)

// ==================== 岗位列表 ====================

/** 岗位列表数据 */
const jobList = ref<JobListItem[]>([])
/** 加载状态 */
const loading = ref(false)

/** 选择行业 */
function selectIndustry(id: number | null) {
  selectedIndustryId.value = id
}

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

/** 选择岗位分类 */
function selectCategory(id: number | null) {
  selectedCategoryId.value = id
}

/** 加载岗位列表 */
async function loadJobList() {
  loading.value = true
  try {
    const params: any = {
      pageNum: 1,
      pageSize: 30,
    }
    if (selectedIndustryId.value !== null) {
      params.industryIds = [selectedIndustryId.value]
    }
    if (selectedCityCode.value !== null) {
      params.regionCodes = [selectedCityCode.value]
    }
    if (selectedCategoryId.value !== null) {
      params.categoryIds = [selectedCategoryId.value]
    }
    const res = await fetchJobList(params)
    if (res.code === '0' && res.data) {
      jobList.value = res.data.list || []
    }
  } catch (e) {
    console.error('加载岗位列表失败', e)
  } finally {
    loading.value = false
  }
}

/** 格式化发布时间 */
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 goToDetail(job: JobListItem) {
  router.push({ path: `/jobs/${job.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([selectedIndustryId, selectedCityCode, selectedCategoryId], () => {
  loadJobList()
})

onMounted(() => {
  loadHotFilters()
  loadJobList()
})
</script>
