<template>
  <div class="mentor-detail dflex">
    <SideNav />
    <div class="mentor-detail__body dflex">
      <!-- 左侧主内容区 -->
      <div class="mentor-detail__main">
        <!-- 页面标题 -->
        <div class="mentor-detail__page-title">导师详情</div>

        <!-- 返回按钮 -->
        <div class="mentor-detail__back" @click="goBack">
          <svg viewBox="0 0 16 16" fill="none" class="mentor-detail__back-icon">
            <path d="M10 12L6 8l4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <span>返回</span>
        </div>

        <!-- 主内容滚动区域 -->
        <div class="mentor-detail__scroll">

          <!-- 导师信息卡片 -->
          <div class="mentor-detail__card mentor-detail__info-card">
            <div class="mentor-detail__info-left">
              <!-- 头像 -->
              <div class="mentor-detail__avatar-wrap">
                <img
                  v-if="mentorInfo?.picture"
                  :src="toOssUrl(mentorInfo.picture)"
                  class="mentor-detail__avatar"
                  :alt="mentorInfo.platformName"
                />
                <div v-else class="mentor-detail__avatar-placeholder">
                  {{ mentorInfo?.platformName?.charAt(0) || '师' }}
                </div>
              </div>
              <!-- 基本信息 -->
              <div class="mentor-detail__info-text">
                <div class="mentor-detail__name">
                  <span>{{ mentorInfo?.platformName }}</span>
                  <div class="mentor-detail__meta">
                    <span v-if="agencyName">{{ agencyName }}</span>
                    <span v-if="agencyName && position"> | </span>
                    <span v-if="position">{{ position }}</span>
                  </div>
                </div>

                <div class="mentor-detail__location" v-if="locationText">
                  所在城市　<span class="">{{ locationText }}</span>
                </div>
                <div class="mentor-detail__services" v-if="serviceLabels.length">
                  服务类型 <span class="ml10">{{ serviceLabels.join('、') }}</span>
                </div>
              </div>
            </div>
            <!-- 右侧：咨询价 + 立即咨询按钮 -->
            <div class="mentor-detail__consult-wrap">
              <!-- 咨询价格（从列表页传入） -->
              <div class="mentor-detail__price" v-if="mentorPrice">
                <span class="mentor-detail__price-label">咨询价</span>
                <span class="mentor-detail__price-value">¥{{ mentorPrice }}</span>
                <span class="mentor-detail__price-suffix">起</span>
              </div>
              <!-- 立即咨询按钮 -->
              <button
                class="mentor-detail__consult-btn"
                @click="openQrDialog"
              >立即咨询 →</button>
            </div>
          </div>

          <!-- 擅长话题卡片 -->
          <div class="mentor-detail__card" v-if="talks.length">
            <div class="mentor-detail__section-title">擅长话题</div>
            <div
              v-for="(talk, index) in talks"
              :key="talk.id"
              class="mentor-detail__talk-item"
            >
              <div class="mentor-detail__talk-title">{{ index + 1 }}.{{ talk.title }}</div>
              <div class="mentor-detail__talk-content" v-if="talk.content">{{ talk.content }}</div>
            </div>
          </div>

          <!-- 个人介绍卡片 -->
          <div class="mentor-detail__card" v-if="mentorInfo?.introduce">
            <div class="mentor-detail__section-title">个人介绍</div>
            <div class="mentor-detail__introduce">{{ mentorInfo.introduce }}</div>
          </div>

          <!-- 加载中 -->
          <div v-if="loading" class="mentor-detail__loading">
            <div class="mentor-detail__loading-spinner"></div>
            <span>加载中...</span>
          </div>
        </div>
      </div>

      <!-- 右侧：广告区域 -->
      <div class="mentor-detail__aside">
        <MentorAsidePanel mode="detail" :mentorId="mentorId" />
      </div>
    </div>

    <!-- 二维码弹窗组件 -->
    <MentorQrCodeDialog
      v-model:visible="showQrDialog"
      :mentorId="mentorId"
      source="api"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import SideNav from '@/components/SideNav.vue'
import MentorAsidePanel from '@/components/MentorAsidePanel.vue'
import { fetchMentorFullInfo, fetchMentorTalks } from '@/api/mentor'
import type { MentorFullInfo, MentorTalk } from '@/api/mentor'
import { toOssUrl } from '@/utils/image'
import MentorQrCodeDialog from '@/components/MentorQrCodeDialog.vue'

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

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

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

/** 导师 ID，从路由参数获取（字符串，避免大数精度丢失） */
const mentorId = route.params.id as string

/** 咨询价格，从列表页 query 传入 */
const mentorPrice = route.query.price as string || ''

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

/** 是否正在加载 */
const loading = ref(false)

/** 导师完整信息 */
const fullInfo = ref<MentorFullInfo | null>(null)

/** 导师话题列表 */
const talks = ref<MentorTalk[]>([])

/** 导师基本信息快捷访问 */
const mentorInfo = computed(() => fullInfo.value?.mentorInfo || null)

/** 机构/公司名 — 根据身份类型从不同认证信息中获取 */
const agencyName = computed(() => {
  const v = fullInfo.value?.verification
  if (!v) return ''
  if (v.working?.companyName) return v.working.companyName
  if (v.career?.agencyName) return v.career.agencyName
  if (v.staff?.schoolName) return v.staff.schoolName
  if (v.student?.schoolName) return v.student.schoolName
  if (v.psychology?.agencyName) return v.psychology.agencyName
  return ''
})

/** 岗位/职位 */
const position = computed(() => {
  const v = fullInfo.value?.verification
  if (!v) return ''
  if (v.working?.position) return v.working.position
  if (v.career?.position) return v.career.position
  if (v.staff?.position) return v.staff.position
  if (v.psychology?.position) return v.psychology.position
  return ''
})

/** 所在城市文本 */
const locationText = computed(() => {
  const info = mentorInfo.value
  if (!info) return ''
  const parts = [info.province, info.city].filter(Boolean)
  return parts.join(' · ')
})

/** 服务类型标签 — 取 labelRelations 中每项的 labelName */
const serviceLabels = computed(() => {
  const labels = fullInfo.value?.labelRelations
  if (!labels || !labels.length) return []
  return labels.map(l => l.labelName).filter(Boolean)
})

// ==================== 数据加载 ====================

/** 加载导师详情和话题 */
async function loadDetail() {
  if (!mentorId) return
  loading.value = true
  try {
    // 并行请求导师信息和话题
    const [infoRes, talksRes] = await Promise.all([
      fetchMentorFullInfo(mentorId),
      fetchMentorTalks(mentorId),
    ])
    // 信息接口返回的可能是 { data: ... } 或直接数据
    const infoData = (infoRes as any)?.data ?? infoRes
    fullInfo.value = infoData
    // 话题接口返回数组或 { data: [...] }
    const talksData = (talksRes as any)?.data ?? talksRes
    talks.value = Array.isArray(talksData) ? talksData : []
  } catch (e) {
    console.error('[导师详情] 加载失败', e)
  } finally {
    loading.value = false
  }
}

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

/** 返回导师列表页 */
function goBack() {
  // 从首页跳转过来时，直接去列表页而非回首页
  if (route.query.from === 'home') {
    router.push('/mentor')
    return
  }
  if (window.history.length > 1) {
    router.back()
  } else {
    router.push('/mentor')
  }
}

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

onMounted(() => {
  loadDetail()
})

// ==================== 二维码弹窗 ====================

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

/**
 * 打开二维码弹窗
 */
function openQrDialog() {
  showQrDialog.value = true
}
</script>
