<template>
  <div class="container">
    <section class="hero fade-up">
      <div class="hero-badge">OPS DASHBOARD</div>
      <h1 class="hero-title">垃圾信息运营看板</h1>
      <p class="hero-sub">覆盖发布、拦截、申诉、样本与模型状态，支持日常运营与风险监控。</p>
    </section>

    <section class="card fade-up fade-up-delay-1" v-if="kpis.length">
      <div class="card-title">核心指标</div>
      <div class="grid-3">
        <div class="kpi" v-for="item in kpis" :key="item.label">
          <div class="kpi-value">{{ item.value }}</div>
          <div class="kpi-label">{{ item.label }}</div>
        </div>
      </div>
    </section>

    <div class="grid-2">
      <section class="card fade-up fade-up-delay-2" v-if="stats && stats.threshold">
        <div class="card-title">检测阈值配置</div>
        <div class="row"><span class="label">当前阈值</span><span class="value">{{ stats.threshold_text }}</span></div>
        <div class="row"><span class="label">更新时间</span><span class="value">{{ stats.threshold.updated_at || '--' }}</span></div>
      </section>

      <section class="card fade-up fade-up-delay-2" v-if="stats && stats.model_info">
        <div class="card-title">模型信息</div>
        <div class="row"><span class="label">模型版本</span><span class="value">{{ stats.model_info.version || '未训练' }}</span></div>
        <div class="row"><span class="label">训练时间</span><span class="value">{{ stats.model_info.trained_at || '--' }}</span></div>
        <div class="row"><span class="label">样本数量</span><span class="value">{{ stats.model_info.sample_count || 0 }}</span></div>
      </section>
    </div>

    <section class="card fade-up fade-up-delay-3" v-if="bars.length">
      <div class="card-title">近 7 天发布趋势</div>
      <div class="list-item" v-for="item in bars" :key="item.date">
        <div class="row">
          <span class="label">{{ item.label }}</span>
          <span class="value">{{ item.value }} 条</span>
        </div>
        <div class="progress-track">
          <div class="progress-fill-safe" :style="{ width: item.percent_text }"></div>
        </div>
      </div>
    </section>

    <div class="grid-2">
      <section class="card fade-up fade-up-delay-3" v-if="sourceDist.length">
        <div class="card-title">训练样本来源</div>
        <div class="list-item" v-for="item in sourceDist" :key="item.name">
          <div class="row"><span class="item-title">{{ item.name }}</span><span class="value">{{ item.value }}</span></div>
        </div>
      </section>

      <section class="card fade-up fade-up-delay-3" v-if="topKeywords.length">
        <div class="card-title">高频风险词</div>
        <div class="chip-group">
          <span class="tag" v-for="kw in topKeywords" :key="kw.token">{{ kw.token }} × {{ kw.count }}</span>
        </div>
      </section>
    </div>

    <section class="card fade-up fade-up-delay-3">
      <button class="btn btn-accent" :disabled="reportLoading" @click="generateReport">
        {{ reportLoading ? '生成中...' : '生成运营报告' }}
      </button>
    </section>

    <transition name="fade">
      <div v-if="report" class="modal-mask" @click.self="closeReport">
        <div class="modal-card" style="width: min(720px, 96vw); max-height: 88vh; overflow-y: auto;">
          <div class="modal-title" style="text-align: center;">垃圾信息运营报告</div>
          <div class="muted" style="text-align: center;">{{ report.period }}</div>

          <div class="report-section">
            <div class="report-section-title">汇总统计</div>
            <div class="grid-3">
              <div class="report-kpi">
                <div class="report-kpi-value">{{ report.summary.total_posts }}</div>
                <div class="report-kpi-label">总发布量</div>
              </div>
              <div class="report-kpi">
                <div class="report-kpi-value">{{ report.summary.total_blocked }}</div>
                <div class="report-kpi-label">拦截量</div>
              </div>
              <div class="report-kpi">
                <div class="report-kpi-value">{{ report.summary.total_published }}</div>
                <div class="report-kpi-label">正常发布</div>
              </div>
            </div>
            <div class="row" style="margin-top: 10px;">
              <span class="label">拦截率</span>
              <span class="value">{{ formatPercent(report.summary.blocked_ratio, 2) }}</span>
            </div>
            <div class="row">
              <span class="label">平均误判率</span>
              <span class="value">{{ report.summary.avg_misjudge_rate_text || '0%' }}</span>
            </div>
          </div>

          <div class="report-section">
            <div class="report-section-title">垃圾信息数量变化（近 14 天）</div>
            <div v-for="item in report.spam_trend" :key="'s' + item.date" style="margin-top: 6px;">
              <div class="row">
                <span class="label">{{ item.label }}</span>
                <span class="value">拦截 {{ item.blocked }} / 发布 {{ item.published }}</span>
              </div>
              <div class="progress-track">
                <div class="progress-fill" :style="{ width: item.blocked_percent }"></div>
              </div>
            </div>
          </div>

          <div class="report-section">
            <div class="report-section-title">高频风险词 Top10</div>
            <div class="chip-group">
              <span
                class="tag tag-danger"
                v-for="(kw, i) in (report.top_keywords || []).slice(0, 10)"
                :key="kw.token"
              >{{ kw.token }} × {{ kw.count }}</span>
            </div>
          </div>

          <div class="report-section">
            <div class="report-section-title">误判率趋势（近 14 天）</div>
            <div v-for="item in report.misjudge_trend" :key="'m' + item.date" style="margin-top: 6px;">
              <div class="row">
                <span class="label">{{ item.label }}</span>
                <span class="value">{{ item.misjudge_rate_text }}</span>
              </div>
              <div class="progress-track">
                <div class="progress-fill-safe" :style="{ width: item.rate_percent }"></div>
              </div>
            </div>
          </div>

          <div class="btn-row">
            <button class="btn btn-primary" @click="copyReportText">复制报告文本</button>
            <button class="btn btn-ghost" @click="closeReport">关闭</button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { request } from '@/utils/request'
import { toast } from '@/utils/feedback'

export default {
  name: 'AdminDashboard',
  data() {
    return {
      loading: false,
      stats: null,
      kpis: [],
      bars: [],
      sourceDist: [],
      topKeywords: [],
      report: null,
      reportLoading: false
    }
  },
  mounted() {
    this.fetchStats()
  },
  methods: {
    formatPercent(value, digits = 2) {
      return `${(Number(value || 0) * 100).toFixed(digits)}%`
    },
    normalizeKpis(stats) {
      return [
        { label: '系统用户', value: stats.user_count || 0 },
        { label: '发布总量', value: stats.post_count || 0 },
        { label: '拦截总量', value: stats.blocked_count || 0 },
        { label: '待处理申诉', value: stats.pending_appeal_count || 0 },
        { label: '训练样本', value: stats.sample_count || 0 },
        { label: '近 7 天拦截率', value: this.formatPercent(stats.blocked_ratio_7d, 2) }
      ]
    },
    normalizeBars(trend) {
      const rows = Array.isArray(trend) ? trend : []
      const maxVal = Math.max(1, ...rows.map((r) => Number(r.post_count || 0)))
      return rows.map((row) => {
        const value = Number(row.post_count || 0)
        const ratio = value / maxVal
        return {
          ...row,
          value,
          percent_text: `${Math.max(6, Math.round(ratio * 100))}%`
        }
      })
    },
    async fetchStats() {
      this.loading = true
      try {
        const stats = await request({ url: '/admin/stats' })
        const normalized = {
          ...stats,
          threshold_text: stats && stats.threshold ? this.formatPercent(stats.threshold.spam_threshold, 1) : '--'
        }
        this.stats = normalized
        this.kpis = this.normalizeKpis(normalized)
        this.bars = this.normalizeBars(normalized.trend_7d || [])
        this.sourceDist = normalized.source_distribution || []
        this.topKeywords = normalized.top_keywords || []
      } finally {
        this.loading = false
      }
    },
    async generateReport() {
      this.reportLoading = true
      try {
        const report = await request({ url: '/admin/stats/report' })
        const maxBlocked = Math.max(...(report.spam_trend || []).map((r) => r.blocked || 0), 1)
        const spamTrend = (report.spam_trend || []).map((item) => ({
          ...item,
          blocked_percent: `${Math.max(4, Math.round(((item.blocked || 0) / maxBlocked) * 100))}%`
        }))
        const misjudgeTrend = (report.misjudge_trend || []).map((item) => ({
          ...item,
          rate_percent: `${Math.round((item.misjudge_rate || 0) * 100)}%`
        }))
        this.report = { ...report, spam_trend: spamTrend, misjudge_trend: misjudgeTrend }
        toast('报告已生成', 'success')
      } finally {
        this.reportLoading = false
      }
    },
    closeReport() {
      this.report = null
    },
    async copyReportText() {
      const report = this.report
      if (!report) return
      const summary = report.summary || {}
      const lines = [
        `【垃圾信息运营报告】`,
        `报告周期：${report.period}`,
        `生成时间：${(report.report_date || '').replace('T', ' ').slice(0, 19)}`,
        '',
        `【汇总统计】`,
        `总发布量：${summary.total_posts || 0} 条`,
        `拦截量：${summary.total_blocked || 0} 条`,
        `正常发布：${summary.total_published || 0} 条`,
        `拦截率：${this.formatPercent(summary.blocked_ratio, 2)}`,
        `复核总数：${summary.total_reviews || 0} 次`,
        `误判放行：${summary.total_approved || 0} 次`,
        `平均误判率：${summary.avg_misjudge_rate_text || '0%'}`,
        '',
        `【高频风险词 Top10】`,
        (report.top_keywords || []).slice(0, 10).map((k) => `${k.token}(${k.count}次)`).join('、'),
        '',
        `【近 7 日趋势】`,
        (report.spam_trend || []).slice(-7).map((t) => `${t.label}: 拦截${t.blocked}条，发布${t.published}条`).join('\n')
      ]
      try {
        await navigator.clipboard.writeText(lines.join('\n'))
        toast('报告已复制到剪贴板', 'success')
      } catch (err) {
        toast('复制失败，请手动选择', 'error')
      }
    }
  }
}
</script>
