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

Page({
  data: {
    inputText: '',
    loading: false,
    summary: null,
    items: []
  },

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

  onInput(e) {
    this.setData({ inputText: e.detail.value || '' })
  },

  parseLines() {
    return (this.data.inputText || '')
      .split('\n')
      .map((line) => line.trim())
      .filter((line) => line.length >= 2)
  },

  async submit() {
    if (this.data.loading) return
    const items = this.parseLines()
    if (!items.length) {
      wx.showToast({ title: '请至少输入一条有效文本', icon: 'none' })
      return
    }

    this.setData({ loading: true })
    try {
      const data = await request({
        url: '/spam/predict/batch',
        method: 'POST',
        data: { items }
      })

      const summary = {
        ...(data.summary || {}),
        spam_ratio_text: this.formatPercent((data.summary || {}).spam_ratio, 2),
        blocked_ratio_text: this.formatPercent((data.summary || {}).blocked_ratio, 2)
      }

      const normalizedItems = (data.items || []).map((item) => ({
        ...item,
        confidence_text: this.formatPercent(item.confidence, 2)
      }))

      this.setData({ summary, items: normalizedItems })
    } finally {
      this.setData({ loading: false })
    }
  },

  fillDemo() {
    this.setData({
      inputText: [
        '点击链接领取购物补贴，名额有限。',
        '明天下午三点上线前演练。',
        '高薪兼职日结，扫码进群。',
        '测试报告我已经同步到项目群。'
      ].join('\n')
    })
  },

  showTokenWeight(e) {
    const token = e.currentTarget.dataset.token
    const weight = e.currentTarget.dataset.weight
    const weightNum = Number(weight || 0)
    const direction = weightNum >= 0 ? '倾向垃圾判定' : '倾向正常判定'
    wx.showModal({
      title: '关键词权重',
      content: `关键词"${token}"\n权重贡献：${weightNum >= 0 ? '+' : ''}${weightNum.toFixed(4)}\n(${direction})`,
      showCancel: false,
      confirmText: '关闭'
    })
  }
})
