<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NTag, NButton, NAlert, NSkeleton, NTabs, NTabPane, NDropdown, NIcon } from 'naive-ui'
import { LockOpenOutline, DownloadOutline } from '@vicons/ionicons5'
import { useMessage } from 'naive-ui'
import { toBeijingDate } from '../../utils/date'
import { copyToClipboard } from '../../utils/clipboard'
import { api } from '../../api/client'
import { computeStudyTypes } from '../../constants/studyTypes'
import { RouterLink } from 'vue-router'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const lit = ref<any>(null)
const loading = ref(true)

const SITE_URL = 'https://oncolit.gonsun.com'

onMounted(async () => {
  try {
    const { data } = await api.get(`/public/literature/${route.params.pmid}`)
    lit.value = data
    injectSchema(data)
  } catch (e: any) { message.error(e?.response?.data?.detail || '加载文献失败') }
  finally { loading.value = false }
})

function setMeta(attr: string, value: string, attrType: 'name'|'property' = 'name') {
  const sel = attrType === 'property' ? `meta[property="${attr}"]` : `meta[name="${attr}"]`
  let el = document.querySelector(sel) as HTMLMetaElement | null
  if (!el) {
    el = document.createElement('meta')
    el.setAttribute(attrType, attr)
    document.head.appendChild(el)
  }
  el.setAttribute('content', value)
}

function injectJsonLd(id: string, data: Record<string, unknown>) {
  const existing = document.getElementById(id)
  if (existing) existing.remove()
  const script = document.createElement('script')
  script.id = id
  script.type = 'application/ld+json'
  script.textContent = JSON.stringify(data)
  document.head.appendChild(script)
}

function injectSchema(article: any) {
  if (!article) return
  const pmid = route.params.pmid as string
  const pageUrl = SITE_URL + '/literature/' + pmid
  const abstract = article.abstract || ''

  // Document title
  document.title = `${article.title?.slice(0, 60)} - OncoLit 肿瘤科研文献速递`

  // Meta description
  setMeta('description', abstract.slice(0, 200))

  // Open Graph
  setMeta('og:title', article.title?.slice(0, 100) || '', 'property')
  setMeta('og:description', abstract.slice(0, 300), 'property')
  setMeta('og:type', 'article', 'property')
  setMeta('og:url', pageUrl, 'property')
  setMeta('og:site_name', 'OncoLit 肿瘤科研文献速递', 'property')

  // Twitter Card
  setMeta('twitter:card', 'summary_large_image')
  setMeta('twitter:title', article.title?.slice(0, 100) || '')
  setMeta('twitter:description', abstract.slice(0, 300))

  // Canonical URL
  let link = document.querySelector('link[rel="canonical"]') as HTMLLinkElement | null
  if (!link) {
    link = document.createElement('link')
    link.setAttribute('rel', 'canonical')
    document.head.appendChild(link)
  }
  link.setAttribute('href', pageUrl)

  // JSON-LD ScholarlyArticle
  const authors = (article.authors || []).map((a: any) => ({
    '@type': 'Person', name: [a.given, a.family].filter(Boolean).join(' '),
  }))
  injectJsonLd('schema-scholarly', {
    '@context': 'https://schema.org',
    '@type': 'ScholarlyArticle',
    headline: article.title,
    name: article.title,
    description: abstract.slice(0, 500),
    author: authors,
    datePublished: article.article_date || article.pub_date,
    journalName: article.journal,
    doi: article.doi,
    pmid: article.pmid,
    isAccessibleForFree: article.is_oa || false,
    keywords: article.keywords?.join(', ') || '',
    isPartOf: {
      '@type': 'Periodical',
      name: article.journal,
      issn: article.journal_issn,
    },
  })

  // BreadcrumbList
  injectJsonLd('schema-breadcrumb', {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      { '@type': 'ListItem', position: 1, name: '首页', item: SITE_URL + '/' },
      { '@type': 'ListItem', position: 2, name: article.title?.slice(0, 60), item: pageUrl },
    ],
  })
}

function goBack() {
  router.back()
}

async function copyPmid() {
  if (!lit.value?.pmid) return
  const ok = await copyToClipboard(String(lit.value.pmid))
  if (ok) message.success('已复制 PMID')
  else message.info(String(lit.value.pmid))
}

async function copyDoi() {
  if (!lit.value?.doi) return
  const ok = await copyToClipboard(lit.value.doi)
  if (ok) message.success('已复制 DOI')
  else message.info(lit.value.doi)
}

const studyTypes = computed(() => computeStudyTypes(lit.value?.pub_types || []))

function formatDate(d: string | undefined | null) {
  if (!d) return ''
  return d.length > 10 ? toBeijingDate(d) : d.slice(0, 10)
}

const isUpdated = computed(() => {
  if (!lit.value?.created_at || !lit.value?.updated_at) return false
  return new Date(lit.value.updated_at).getTime() > new Date(lit.value.created_at).getTime()
})

// ── 搜索关键词高亮 ──
const searchQuery = computed(() => (route.query.q as string) || '')

function highlightText(text: string): string {
  const q = searchQuery.value
  if (!q || !text) return text || ''
  const escaped = q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const terms = escaped.split(/\s+/).filter(Boolean)
  let result = text
  for (const term of terms) {
    result = result.replace(new RegExp(`(${term})`, 'gi'), '<mark class="search-highlight">$1</mark>')
  }
  return result
}

// ── 导出 ──
const exportOptions = [
  { label: 'BibTeX', key: 'bibtex' },
  { label: 'RIS', key: 'ris' },
  { label: 'EndNote', key: 'endnote' },
  { label: 'CSV', key: 'csv' },
]

function handleExport(fmt: string) {
  if (!lit.value?.pmid) return
  const url = `/api/v1/literature/export/${lit.value.pmid}/${fmt}`
  window.open(url, '_blank')
}
</script>

<template>
  <div class="detail" style="max-width:1100px;margin:0 auto;padding:24px">
    <NSkeleton v-if="loading" text :repeat="12" />
    <template v-else-if="lit">
      <div class="back-bar">
        <span class="back-btn" @click="goBack">← 返回</span>
      </div>

      <!-- 更新提示 -->
      <div v-if="isUpdated" class="update-notice">🔄 该文献内容已于 {{ formatDate(lit.updated_at) }} 更新</div>

      <!-- 标题 -->
      <h2>{{ lit.title }}</h2>

      <!-- 研究类型徽章 -->
      <div v-if="studyTypes.length" class="detail-type-row">
        <NTag v-for="st in studyTypes" :type="st.type" size="tiny" :bordered="false">{{ st.label }}</NTag>
      </div>

      <!-- 元信息 -->
      <p class="meta">
        {{ lit.authors?.map((a:any) => a.family).slice(0,4).join(', ') }}
        <span v-if="(lit.authors||[]).length > 4">et al.</span>
        <span v-if="lit.affiliation" style="color:#1a5276"> · 🏛 {{ lit.affiliation }}</span>
        <br>
        <strong>{{ lit.journal }}</strong>
        <span v-if="lit.pub_date"> | {{ (lit.article_date || lit.pub_date).slice(0,10) }}</span>
        <span v-if="lit.pub_year"> ({{ lit.pub_year }})</span>
        <span v-if="lit.volume">; {{ lit.volume }}{{ lit.issue ? `(${lit.issue})` : '' }}{{ lit.pages ? `:${lit.pages}` : '' }}</span>
      </p>

      <!-- PMID / DOI / PMC / OA / 引用 -->
      <div class="detail-ids">
        <template v-if="lit.pmid">
          <span class="id-label">PMID:</span>
          <span class="id-value">{{ lit.pmid }}</span>
          <span class="copy-btn" @click="copyPmid" title="复制 PMID">📋</span>
        </template>
        <template v-if="lit.doi">
          <span class="id-sep">|</span>
          <span class="id-label">DOI:</span>
          <span class="id-value">{{ lit.doi }}</span>
          <span class="copy-btn" @click="copyDoi" title="复制 DOI">📋</span>
        </template>
        <template v-if="lit.pmc_id">
          <span class="id-sep">|</span>
          <span class="id-label">PMCID:</span>
          <span class="id-value">{{ lit.pmc_id }}</span>
          <NTag v-if="lit.is_oa" type="success" size="tiny" :bordered="false">🔓 免费全文</NTag>
        </template>
        <template v-if="lit.cited_by_count">
          <span class="id-sep">|</span>
          <span class="cited-count">📊 被引 {{ lit.cited_by_count }} 次</span>
        </template>
        <span class="id-sep">|</span>
        <a :href="'https://pubmed.ncbi.nlm.nih.gov/' + lit.pmid + '/'" target="_blank" rel="noopener" style="font-size:12px;color:#1a5276">PubMed ↗</a>
        <a v-if="lit.doi" :href="'https://doi.org/' + lit.doi" target="_blank" rel="noopener" style="font-size:12px;color:#1a5276;margin-left:4px">DOI ↗</a>
      </div>

      <!-- 标签 -->
      <div class="tags" v-if="lit.tags?.length">
        <NTag v-for="tag in lit.tags" :key="tag.id" size="small" :bordered="false" type="info" style="cursor:pointer">
          {{ tag.name_zh || tag.name_en }}
        </NTag>
      </div>

      <!-- 关键词 -->
      <div v-if="lit.keywords?.length" class="detail-section">
        <div class="section-title">关键词</div>
        <div class="kw-row">
          <span v-for="kw in lit.keywords" :key="kw" class="kw-pill">{{ kw }}</span>
        </div>
      </div>

      <!-- 基金 -->
      <div v-if="lit.grants?.length" class="detail-section">
        <div class="section-title">基金资助</div>
        <div v-for="(g, i) in lit.grants" :key="i" class="grant-row">
          <span v-if="g.agency">{{ g.agency }}</span>
          <span v-if="g.grant_id"> ({{ g.grant_id }})</span>
        </div>
      </div>

      <!-- Tab: 摘要 / AI -->
      <NTabs type="line" default-value="abstract" style="margin-top:12px">
        <NTabPane name="abstract" tab="📋 摘要">
          <div class="abstract-text" v-html="highlightText(lit.abstract || '摘要不可用')"></div>
        </NTabPane>
        <NTabPane name="ai" tab="🤖 AI 总结">
          <div v-if="lit.ai_summary" class="ai-text">{{ lit.ai_summary }}</div>
          <div v-else style="text-align:center;padding:24px">
            <div style="color:var(--text-muted);font-size:14px;margin-bottom:12px">🔒 AI 深度解读仅限登录用户</div>
            <router-link to="/auth/login"><NButton class="sky-btn" type="primary" size="small"><template #icon><NIcon size="14"><LockOpenOutline /></NIcon></template>登录后查看</NButton></router-link>
          </div>
        </NTabPane>
      </NTabs>

      <!-- 操作栏 -->
      <div class="detail-actions" style="margin-top:16px">
        <router-link to="/auth/login"><NButton class="sky-btn" type="primary">⭐ 收藏（登录后可用）</NButton></router-link>
        <NDropdown :options="exportOptions" @select="handleExport">
          <NButton class="sky-btn" ><template #icon><NIcon size="14"><DownloadOutline /></NIcon></template>导出引用 ▼</NButton>
        </NDropdown>
      </div>

      <!-- 登录 CTA -->
      <NAlert type="info" style="margin-top:16px" title="🔒 登录后查看 PDF 全文、收藏到个人库、AI 深度解读">
        <template #default>
          <router-link to="/auth/login"><NButton class="sky-btn" size="small" ghost><template #icon><NIcon size="14"><LockOpenOutline /></NIcon></template>登录</NButton></router-link>
        </template>
      </NAlert>
    </template>
  </div>
</template>

<style scoped>
.back-bar { margin-bottom: 8px; }
.back-btn { font-size: 13px; color: #1a5276; cursor: pointer; user-select: none; }
.back-btn:hover { text-decoration: underline; }
.detail h2 { font-size:22px;font-weight:700;line-height:1.4;margin-bottom:8px }
.detail-type-row { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 8px; }
.meta { font-size:13px;color:var(--text-muted);margin:0 0 8px;line-height:1.6 }
.detail-ids { font-size: 13px; color: var(--text-secondary); margin-bottom: 8px; display: flex; align-items: center; flex-wrap: wrap; gap: 4px; }
.id-label { color: var(--text-muted); }
.id-value { color: var(--text-secondary); }
.copy-btn { cursor: pointer; font-size: 12px; }
.copy-btn:hover { opacity: .7; }
.id-sep { color: var(--border-color); margin: 0 2px; }
.cited-count { color: var(--text-muted); }
.tags { display:flex;gap:4px;flex-wrap:wrap;margin:8px 0 }
.detail-section { margin: 14px 0; }
.section-title { font-size: 13px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px; }
.kw-row { display: flex; flex-wrap: wrap; gap: 4px; }
.kw-pill { font-size: 12px; background: var(--kw-pill-bg); color: var(--kw-pill-color); padding: 2px 10px; border-radius: 10px; }
.grant-row { font-size: 12px; color: var(--text-secondary); margin-bottom: 2px; }
.abstract-text { line-height:1.8;white-space:pre-wrap;font-size:14px;color:var(--text-primary) }
.abstract-text :deep(.search-highlight) { background: #ffd700; color: #333; padding: 0 2px; border-radius: 2px; }
html.dark .abstract-text :deep(.search-highlight) { background: #b8860b; color: #fff; }
.ai-text { line-height:1.7;font-size:14px;color:var(--text-primary);background:var(--bg-card);padding:14px;border-radius:6px }
.detail-actions { margin-top: 20px; display: flex; gap: 8px; }
.update-notice { font-size:12px; color:var(--text-secondary); background:var(--bg-card); padding:6px 12px; border-radius:6px; margin-bottom:12px; border-left:3px solid #e8c080; }

@media (max-width: 768px) {
  .detail { padding: 12px !important; }
  .detail h2 { font-size: 18px; }
}

@media (min-width: 1400px) {
  .detail { max-width: 1200px !important; }
}
</style>
