<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import { NDataTable, NButton, NTag, NAlert, NCard, NGrid, NGridItem } from 'naive-ui'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'

const toast = useToast()
const runs = ref<any[]>([])
const loading = ref(true)

// Action loading states
const running = ref(false)
const refreshingCitations = ref(false)
const extractingPico = ref(false)
const backfillingDesign = ref(false)
const generatingSummary = ref(false)
const backfillingOA = ref(false)
const retagging = ref(false)

function fmtPipelineTime(ts: string | null | undefined): string {
  if (!ts) return '—'
  const d = new Date(ts)
  if (isNaN(d.getTime())) return ts
  return d.toLocaleString('zh-CN', {
    timeZone: 'Asia/Shanghai',
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false,
  }).replace(/\//g, '-')
}

onMounted(loadData)
async function loadData() {
  loading.value = true
  try { const { data } = await api.get('/admin/pipeline/runs'); runs.value = data.items || [] }
  catch (e) { toast.apiError(e, '加载管道记录失败') }
  finally { loading.value = false }
}

async function triggerPipeline() {
  running.value = true
  try { await api.post('/admin/pipeline/run'); toast.success('管道已触发'); await loadData() }
  catch (e) { toast.apiError(e, '触发失败') }
  finally { running.value = false }
}
async function refreshCitations() {
  refreshingCitations.value = true
  try { const { data } = await api.post('/admin/pipeline/refresh-citations'); toast.success('引用更新完成: ' + data.updated + ' 篇'); await loadData() }
  catch (e) { toast.apiError(e, '刷新失败') }
  finally { refreshingCitations.value = false }
}
async function extractPico() {
  extractingPico.value = true
  try { const { data } = await api.post('/admin/pipeline/extract-pico'); toast.success('PICO 提取完成: ' + data.processed + ' 篇'); await loadData() }
  catch (e) { toast.apiError(e, '提取失败') }
  finally { extractingPico.value = false }
}
async function backfillDesign() {
  backfillingDesign.value = true
  try { const { data } = await api.post('/admin/pipeline/backfill-study-designs'); toast.success('回填完成: ' + data.updated + ' 篇'); await loadData() }
  catch (e) { toast.apiError(e, '回填失败') }
  finally { backfillingDesign.value = false }
}
async function generateSummary() {
  generatingSummary.value = true
  try { const { data } = await api.post('/admin/ai/summarize'); toast.success('摘要生成完成: ' + data.processed + ' 篇'); await loadData() }
  catch (e) { toast.apiError(e, '生成失败') }
  finally { generatingSummary.value = false }
}
async function backfillOA() {
  backfillingOA.value = true
  try { const { data } = await api.post('/admin/pipeline/backfill-oa-text?limit=5000'); toast.success('OA全文回填完成: ' + data.fetched + ' 篇'); await loadData() }
  catch (e) { toast.apiError(e, '回填失败') }
  finally { backfillingOA.value = false }
}
async function retagTags() {
  retagging.value = true
  try { const { data } = await api.post('/admin/pipeline/retag-tags'); toast.success('MeSH 回填完成: ' + data.tagged_articles + ' 篇 (' + data.tags_added + ' 个标签)'); await loadData() }
  catch (e) { toast.apiError(e, '回填失败') }
  finally { retagging.value = false }
}

const cols = [
  { title: '类型', key: 'type', width: 120 },
  { title: '状态', key: 'status', width: 70, render: (r: any) => h(NTag, { size:'tiny', type: r.status==='success'?'success':'error' }, r.status) },
  { title: '新增', key: 'new', width: 50 },
  { title: '打标', key: 'filtered', width: 50 },
  { title: 'Feed', key: 'feeds', width: 50 },
  { title: '错误', key: 'error', width: 120, ellipsis: true, render: (r: any) => r.error || '—' },
  { title: '开始', key: 'started', width: 140, render: (r: any) => fmtPipelineTime(r.started) },
  { title: '完成', key: 'completed', width: 140, render: (r: any) => fmtPipelineTime(r.completed) },
]
const scrollX = 740
</script>

<template>
  <div class="pipeline-view">
    <div class="header-row" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <h2 style="margin:0">📡 数据管道</h2>
      <NButton type="primary" :loading="running" @click="triggerPipeline" class="sky-btn">🔄 手动触发管道</NButton>
    </div>

    <NAlert type="info" style="margin-bottom:16px" title="PubMed E-utilities API · 自动 MeSH 打标 · 自动生成 Feed">
      <div style="font-size:13px;line-height:1.8">
        • 每天 03:07 UTC 自动精搜（MAJR）· 周日 03:37 UTC 自动宽搜<br>
        • 引用刷新 05:13 UTC 每日自动 · 11月中–12月中 MeSH 年更期 in-process 文献仅宽搜覆盖
      </div>
    </NAlert>

    <!-- Action cards -->
    <n-grid :cols="4" :x-gap="12" responsive="screen" style="margin-bottom:20px">
      <n-grid-item>
        <NCard size="small" style="text-align:center">
          <div style="font-size:12px;color:var(--text-secondary);margin-bottom:8px">🔄 刷新被引次数</div>
          <NButton size="tiny" :loading="refreshingCitations" @click="refreshCitations" class="sky-btn">执行</NButton>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard size="small" style="text-align:center">
          <div style="font-size:12px;color:var(--text-secondary);margin-bottom:8px">📝 PICO 提取</div>
          <NButton size="tiny" :loading="extractingPico" @click="extractPico" class="sky-btn">执行</NButton>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard size="small" style="text-align:center">
          <div style="font-size:12px;color:var(--text-secondary);margin-bottom:8px">🏗️ 回填研究设计</div>
          <NButton size="tiny" :loading="backfillingDesign" @click="backfillDesign" class="sky-btn">执行</NButton>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard size="small" style="text-align:center">
          <div style="font-size:12px;color:var(--text-secondary);margin-bottom:8px">🤖 AI 摘要生成</div>
          <NButton size="tiny" :loading="generatingSummary" @click="generateSummary" class="sky-btn">执行</NButton>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard size="small" style="text-align:center">
          <div style="font-size:12px;color:var(--text-secondary);margin-bottom:8px">📄 OA 全文回填</div>
          <NButton size="tiny" :loading="backfillingOA" @click="backfillOA" class="sky-btn">执行</NButton>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard size="small" style="text-align:center">
          <div style="font-size:12px;color:var(--text-secondary);margin-bottom:8px">🏷️ MeSH 标签回填</div>
          <NButton size="tiny" :loading="retagging" @click="retagTags" class="sky-btn">执行</NButton>
        </NCard>
      </n-grid-item>
    </n-grid>

    <!-- Run history table -->
    <NCard title="运行历史" size="small">
      <NDataTable :columns="cols" :data="runs" :loading="loading" size="small" :bordered="false" :paginate="{ pageSize: 20 }" :scroll-x="scrollX" />
    </NCard>
  </div>
</template>

<style scoped>
@media (max-width: 768px) {
  .pipeline-view {
    padding: 12px;
  }

  .header-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .header-row h2 {
    font-size: 20px;
  }

  .n-grid {
    grid-template-columns: 1fr 1fr;
  }

  .n-card:has(.n-data-table) {
    overflow-x: auto;
  }
}
</style>
