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

Page({
  data: {
    keyword: '',
    label: '',
    loading: false,
    samples: [],
    form: {
      text: '',
      label: 'spam'
    },
    importText: '[{"text":"点击领取限时现金券","label":"spam"},{"text":"今天下午发布会彩排","label":"ham"}]'
  },

  onShow() {
    this.fetchSamples()
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({ [field]: e.detail.value || '' })
  },

  onFormInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({ [`form.${field}`]: e.detail.value || '' })
  },

  onLabelChange(e) {
    this.setData({ label: e.detail.value || '' })
  },

  onFormLabelChange(e) {
    this.setData({ 'form.label': e.detail.value || 'spam' })
  },

  async fetchSamples() {
    this.setData({ loading: true })
    try {
      const url = `/spam/samples?keyword=${encodeURIComponent(this.data.keyword)}&label=${encodeURIComponent(this.data.label)}&page=1&page_size=80`
      const data = await request({ url })
      this.setData({ samples: data.items || [] })
    } finally {
      this.setData({ loading: false })
    }
  },

  async createSample() {
    const payload = {
      text: (this.data.form.text || '').trim(),
      label: this.data.form.label || 'spam'
    }
    if (payload.text.length < 2) {
      wx.showToast({ title: '样本文本至少 2 个字符', icon: 'none' })
      return
    }
    await request({ url: '/spam/samples', method: 'POST', data: payload })
    wx.showToast({ title: '新增成功', icon: 'success' })
    this.setData({ 'form.text': '' })
    this.fetchSamples()
  },

  async deleteSample(e) {
    const id = Number(e.currentTarget.dataset.id)
    wx.showModal({
      title: '删除样本',
      content: `确认删除样本 ID ${id} 吗？`,
      success: async (res) => {
        if (!res.confirm) return
        await request({ url: `/spam/samples/${id}`, method: 'DELETE' })
        wx.showToast({ title: '删除成功', icon: 'success' })
        this.fetchSamples()
      }
    })
  },

  async toggleActive(e) {
    const id = Number(e.currentTarget.dataset.id)
    const active = !!e.detail.value
    await request({
      url: `/spam/samples/${id}`,
      method: 'PUT',
      data: { is_active: active }
    })
    wx.showToast({ title: '状态已更新', icon: 'success' })
  },

  async retrain() {
    await request({ url: '/spam/train', method: 'POST', data: {} })
    wx.showToast({ title: '模型重训完成', icon: 'success' })
  },

  async importSamples() {
    let items = []
    try {
      items = JSON.parse(this.data.importText)
    } catch (err) {
      wx.showToast({ title: 'JSON 格式错误', icon: 'none' })
      return
    }

    await request({ url: '/spam/samples/import', method: 'POST', data: { items } })
    wx.showToast({ title: '导入完成', icon: 'success' })
    this.fetchSamples()
  }
})
