<template>
  <!-- 求职辅导Tab内容 -->
  <div class="home-mentor">
    <!-- 第一部分：找到真正懂行业的求职导师 -->
    <section class="home-mentor__section">
      <div class="home-mentor__header">
        <h2 class="home-mentor__title">找到真正懂行业的求职导师</h2>
        <p class="home-mentor__subtitle">连接名企在职导师，获取来自真实职场的一对一求职指导与经验分享</p>
      </div>

      <!-- 行业分类Tab -->
      <div class="home-mentor__tabs">
        <span
          v-for="(tab, index) in industryTabs"
          :key="index"
          class="home-mentor__tab"
          :class="{ 'home-mentor__tab--active': activeTab === index }"
          @click="handleTabChange(index)"
        >{{ tab }}</span>
      </div>

      <!-- 导师列表滚动容器 -->
      <div ref="listWrapRef" class="home-mentor__list-wrap scrollbar-thin" @scroll="onListScroll">
        <!-- 导师列表 -->
        <div class="home-mentor__list">
          <div
            v-for="mentor in mentorList"
            :key="mentor.id"
            class="home-mentor__card"
            @click="goToDetail(mentor)"
          >
          <!-- 左侧：头像 + 基本信息 -->
          <div class="home-mentor__card-left">
            <!-- 头像 -->
            <div class="home-mentor__avatar-wrap">
              <img
                v-if="mentor.picture"
                :src="toOssUrl(mentor.picture)"
                class="home-mentor__avatar"
                :alt="mentor.platformName"
              />
              <div v-else class="home-mentor__avatar-placeholder">
                {{ mentor.platformName?.charAt(0) || '师' }}
              </div>
            </div>
            <!-- 导师基本信息 -->
            <div class="home-mentor__card-info">
              <div class="home-mentor__card-name-row">
                <span class="home-mentor__card-name">{{ mentor.platformName }}</span>
                <span v-if="mentor.agencyName" class="home-mentor__card-meta">
                  <img v-if="mentor.agencyLogo" :src="toOssUrl(mentor.agencyLogo)" class="home-mentor__card-agency-logo" alt="" />
                  {{ mentor.agencyName }}<template v-if="mentor.position">｜{{ mentor.position }}</template>
                </span>
              </div>
              <!-- 标签列表 -->
              <div class="home-mentor__card-labels" v-if="mentor.labels && mentor.labels.length">
                <span
                  v-for="(label, li) in mentor.labels.slice(0, 6)"
                  :key="li"
                  class="home-mentor__card-label"
                >{{ label }}</span>
              </div>
            </div>
          </div>

          <!-- 右侧：话题 + 查看详情 -->
          <div class="home-mentor__card-right">
            <!-- 话题列表 -->
            <div class="home-mentor__card-topics">
              <div
                v-for="(title, ti) in mentor.titles.slice(0, 3)"
                :key="ti"
                class="home-mentor__card-topic"
              ><span class="color-accent">#</span> {{ title }}</div>
            </div>
            <!-- 查看详情按钮 -->
            <button class="home-mentor__detail-btn">
              <span>查看详情</span>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path fill-rule="evenodd" clip-rule="evenodd" d="M7.51612 4.07575C7.38279 3.94242 7.31879 3.78686 7.32412 3.60908C7.32945 3.43131 7.39901 3.27575 7.53278 3.14241C7.66612 3.02019 7.82167 2.95619 7.99946 2.95041C8.17723 2.94464 8.33278 3.00864 8.46612 3.14241L12.8661 7.54241C12.9328 7.60908 12.9801 7.6813 13.0081 7.75908C13.0361 7.83686 13.0497 7.92019 13.0488 8.00908C13.0479 8.09797 13.0339 8.18131 13.0068 8.25908C12.9797 8.33686 12.9326 8.40908 12.8654 8.47575L8.46545 12.8757C8.34323 12.998 8.19034 13.0591 8.00679 13.0591C7.82323 13.0591 7.66501 12.998 7.53212 12.8757C7.39879 12.7424 7.33212 12.584 7.33212 12.4004C7.33212 12.2169 7.39879 12.0586 7.53212 11.9257L10.7828 8.67575H3.33279C3.1439 8.67575 2.98546 8.61175 2.85745 8.48375C2.72945 8.35575 2.66567 8.19753 2.66612 8.00908C2.66656 7.82064 2.73056 7.6622 2.85812 7.53375C2.98568 7.40531 3.1439 7.34153 3.33279 7.34242L10.7828 7.34242L7.51612 4.07575Z" fill="currentColor"/>
              </svg>
            </button>
          </div>
        </div>

        <!-- 加载中提示 -->
        <div v-if="loading" class="home-mentor__loading">
          <div class="home-mentor__spinner"></div>
          <span>加载中...</span>
        </div>

        <!-- 加载更多中 -->
        <div v-if="loadingMore" class="home-mentor__loading">
          <div class="home-mentor__spinner"></div>
          <span>加载中...</span>
        </div>

        <!-- 没有更多数据 -->
        <div v-if="noMore && mentorList.length > 0" class="home-mentor__no-more">没有更多导师了</div>

        <!-- 空列表 -->
        <div v-if="!loading && mentorList.length === 0" class="home-mentor__empty">
          暂无相关导师
        </div>
      </div>
      </div>

    </section>

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

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { fetchMentorList } from '@/api/mentor'
import type { MentorItem, MentorListParams } from '@/api/mentor'
import { toOssUrl } from '@/utils/image'

/** 路由实例 */
const router = useRouter()
/** Vuex Store */
const store = useStore()

// ==================== 行业 Tab 数据 ====================

/** 行业 Tab 标签列表 */
const industryTabs = ['推荐', '互联网', '金融', '快消', '咨询', '央国企', '硬科技', '生涯规划', '名校导师', '心理咨询', '其他']

/** 当前选中的 Tab 索引 */
const activeTab = ref(0)

/** 生成 min~max 之间的整数数组 */
function createIntegerRange(min: number, max: number): number[] {
  min = Math.floor(min)
  max = Math.floor(max)
  if (min > max) return []
  const result: number[] = []
  for (let i = min; i <= max; i++) result.push(i)
  return result
}

/** 根据当前 Tab 计算 industryIds 参数 */
const industryIds = computed<number[]>(() => {
  if (activeTab.value === 0) return []
  if (activeTab.value === 1) return createIntegerRange(1000, 1016)
  if (activeTab.value === 2) return createIntegerRange(1131, 1139)
  if (activeTab.value === 3) return createIntegerRange(1038, 1047)
  if (activeTab.value === 4) return createIntegerRange(1087, 1093)
  if (activeTab.value === 5) return []
  if (activeTab.value === 6) return [
    1012, 1014, 1017, 1018, 1019, 1020, 1021, 1022, 1023,
    1074, 1078, 1079, 1084, 1085,
    1095, 1097, 1098,
    1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130,
  ]
  if (activeTab.value === 7) return []
  if (activeTab.value === 8) return []
  if (activeTab.value === 9) return []
  if (activeTab.value === 10) {
    const all = createIntegerRange(1000, 1143)
    const used = new Set([
      ...createIntegerRange(1000, 1016),
      ...createIntegerRange(1131, 1139),
      ...createIntegerRange(1038, 1047),
      ...createIntegerRange(1087, 1093),
      1012, 1014, 1017, 1018, 1019, 1020, 1021, 1022, 1023,
      1074, 1078, 1079, 1084, 1085,
      1095, 1097, 1098,
      1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130,
    ])
    return all.filter(id => !used.has(id))
  }
  return []
})

/** 根据当前 Tab 计算机构类型 type 参数 */
const mentorType = computed<string | null>(() => {
  return activeTab.value === 5 ? '央国企' : null
})

/** 根据当前 Tab 计算身份类型 identityType 参数 */
const identityType = computed<number | null>(() => {
  if (activeTab.value === 5) return 0
  if (activeTab.value === 7) return 1
  if (activeTab.value === 8) return 4
  if (activeTab.value === 9) return 2
  return null
})

// ==================== 列表数据 ====================

/** 导师列表数据 */
const mentorList = ref<MentorItem[]>([])
/** 加载状态（首次加载） */
const loading = ref(false)
/** 加载更多状态 */
const loadingMore = ref(false)
/** 当前页码 */
const pageNum = ref(1)
/** 每页条数 */
const pageSize = ref(20)
/** 是否没有更多数据 */
const noMore = ref(false)
/** 列表滚动容器 ref */
const listWrapRef = ref<HTMLElement | null>(null)

/** 构建接口请求参数 */
function buildParams(): MentorListParams {
  const params: MentorListParams = {
    page: pageNum.value,
    pageSize: pageSize.value,
    sort: 0,
  }
  if (industryIds.value.length) params.industryIds = industryIds.value
  if (mentorType.value !== null) params.type = mentorType.value
  if (identityType.value !== null) params.identityType = identityType.value
  return params
}

/** 加载导师列表（首次加载） */
async function loadMentors() {
  loading.value = true
  pageNum.value = 1
  noMore.value = false
  mentorList.value = []
  try {
    const res: any = await fetchMentorList(buildParams())
    const pageData = res?.data ?? res
    const records = pageData?.records ?? []
    mentorList.value = records
    if (records.length < pageSize.value) {
      noMore.value = true
    }
  } 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: any = await fetchMentorList(buildParams())
    const pageData = res?.data ?? res
    const records = pageData?.records ?? []
    if (records.length === 0) {
      noMore.value = true
      pageNum.value--
    } else {
      mentorList.value.push(...records)
      if (records.length < pageSize.value) {
        noMore.value = true
      }
    }
  } catch (e) {
    pageNum.value--
    console.error('[首页导师列表] 加载下一页失败', e)
  } finally {
    loadingMore.value = false
    nextTick(() => { autoFillIfNeeded() })
  }
}

/** 自动填满容器：内容不足以滚动时自动加载下一页 */
function autoFillIfNeeded() {
  const el = listWrapRef.value
  if (!el) return
  if (el.scrollHeight <= el.clientHeight && !noMore.value && !loadingMore.value && !loading.value) {
    loadNextPage()
  }
}

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

/** 切换行业 Tab */
function handleTabChange(index: number) {
  if (activeTab.value === index) return
  activeTab.value = index
  loadMentors()
}

/** 点击查看详情 — 需要登录验证 */
function goToDetail(mentor: MentorItem) {
  if (!store.state.isAuthenticated) {
    store.dispatch('openLogin', `/mentor/${mentor.id}`)
    return
  }
  router.push({ path: `/mentor/${mentor.id}`, query: { price: String(mentor.price), from: 'home' } })
}

/** 跳转导师页面 — 需要登录验证 */
function goToMentorPage() {
  if (!store.state.isAuthenticated) {
    store.dispatch('openLogin', '/mentor')
    return
  }
  router.push('/mentor')
}

onMounted(() => {
  loadMentors()
})
</script>
