const { request } = require('../../utils/request')

Page({
  data: {
    loading: false,
    stats: null,
    kpis: [],
    bars: [],
    sourceDist: [],
    topKeywords: []
  },

  formatPercent(value, digits = 2) {
    const num = Number(value || 0)
    return `${(num * 100).toFixed(digits)}%`
  },

  onShow() {
    this.fetchStats()
  },

  onPullDownRefresh() {
    this.fetchStats(true)
  },

  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(fromPullDown = false) {
    this.setData({ loading: true })
    try {
      const stats = await request({ url: '/admin/stats' })
      const normalizedStats = {
        ...stats,
        threshold_text: stats && stats.threshold ? this.formatPercent(stats.threshold.spam_threshold, 1) : '--'
      }
      this.setData({
        stats: normalizedStats,
        kpis: this.normalizeKpis(normalizedStats),
        bars: this.normalizeBars(normalizedStats.trend_7d || []),
        sourceDist: normalizedStats.source_distribution || [],
        topKeywords: normalizedStats.top_keywords || []
      })
    } finally {
      this.setData({ loading: false })
      if (fromPullDown) wx.stopPullDownRefresh()
    }
  }
})
