<template>
  <div class="container">
    <section class="hero fade-up">
      <div class="hero-badge">SAMPLE LAB</div>
      <h1 class="hero-title">训练样本管理</h1>
      <p class="hero-sub">支持增删样本、批量导入、启停样本与一键重训，持续提升识别准确率。</p>
    </section>

    <section class="card fade-up fade-up-delay-1">
      <div class="card-title">筛选样本</div>
      <div class="grid-2">
        <div class="field">
          <label class="field-label">关键词</label>
          <input class="input" v-model="keyword" placeholder="输入关键词" />
        </div>
        <div class="field">
          <label class="field-label">标签</label>
          <div>
            <label class="radio-row"><input type="radio" v-model="label" value="" />全部</label>
            <label class="radio-row"><input type="radio" v-model="label" value="spam" />垃圾</label>
            <label class="radio-row"><input type="radio" v-model="label" value="ham" />正常</label>
          </div>
        </div>
      </div>
      <button class="btn btn-primary" :disabled="loading" @click="fetchSamples">
        {{ loading ? '查询中...' : '查询' }}
      </button>
    </section>

    <section class="card fade-up fade-up-delay-1">
      <div class="card-title">新增样本</div>
      <textarea class="textarea" v-model="form.text" placeholder="输入样本文本" rows="3"></textarea>
      <div class="field">
        <label class="radio-row"><input type="radio" v-model="form.label" value="spam" />垃圾</label>
        <label class="radio-row"><input type="radio" v-model="form.label" value="ham" />正常</label>
      </div>
      <button class="btn btn-accent" @click="createSample">提交样本</button>
    </section>

    <section class="card fade-up fade-up-delay-2">
      <div class="card-title">批量导入</div>
      <div class="card-desc">支持 JSON 数组导入。导入后可直接重训模型。</div>
      <textarea class="textarea" v-model="importText" rows="4"></textarea>
      <div class="btn-row">
        <button class="btn btn-primary" @click="importSamples">执行导入</button>
        <button class="btn btn-ghost" @click="retrain">一键重训模型</button>
      </div>
    </section>

    <section class="card fade-up fade-up-delay-3" v-if="samples.length">
      <div class="card-title">样本列表</div>
      <div class="list-item" v-for="item in samples" :key="item.id">
        <div class="item-title">{{ item.text }}</div>
        <div class="item-sub">标签：{{ item.label === 'spam' ? '垃圾' : '正常' }} · 来源：{{ item.source }} · ID：{{ item.id }}</div>

        <div class="row">
          <span class="label">参与训练</span>
          <label class="switch">
            <input type="checkbox" :checked="item.is_active" @change="toggleActive(item, $event)" />
            <span class="switch-slider"></span>
          </label>
        </div>

        <button class="btn btn-ghost btn-sm" @click="deleteSample(item.id)">删除样本</button>
      </div>
    </section>

    <section class="card fade-up fade-up-delay-3" v-else-if="!loading">
      <div class="empty">暂无样本，先去新增或导入。</div>
    </section>
  </div>
</template>

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

export default {
  name: 'AdminSamples',
  data() {
    return {
      keyword: '',
      label: '',
      loading: false,
      samples: [],
      form: {
        text: '',
        label: 'spam'
      },
      importText: '[{"text":"点击领取限时现金券","label":"spam"},{"text":"今天下午发布会彩排","label":"ham"}]'
    }
  },
  mounted() {
    this.fetchSamples()
  },
  methods: {
    async fetchSamples() {
      this.loading = true
      try {
        const data = await request({
          url: '/spam/samples',
          params: {
            keyword: this.keyword,
            label: this.label,
            page: 1,
            page_size: 80
          }
        })
        this.samples = data.items || []
      } finally {
        this.loading = false
      }
    },
    async createSample() {
      const text = (this.form.text || '').trim()
      if (text.length < 2) {
        toast('样本文本至少 2 个字符', 'error')
        return
      }
      await request({
        url: '/spam/samples',
        method: 'POST',
        data: { text, label: this.form.label || 'spam' }
      })
      toast('新增成功', 'success')
      this.form.text = ''
      this.fetchSamples()
    },
    async deleteSample(id) {
      const { confirm: ok } = await confirm({
        title: '删除样本',
        content: `确认删除样本 ID ${id} 吗？`,
        confirmText: '删除',
        cancelText: '取消'
      })
      if (!ok) return
      await request({ url: `/spam/samples/${id}`, method: 'DELETE' })
      toast('删除成功', 'success')
      this.fetchSamples()
    },
    async toggleActive(item, e) {
      const active = !!e.target.checked
      try {
        await request({
          url: `/spam/samples/${item.id}`,
          method: 'PUT',
          data: { is_active: active }
        })
        item.is_active = active
        toast('状态已更新', 'success')
      } catch (err) {
        e.target.checked = !active
      }
    },
    async retrain() {
      await request({ url: '/spam/train', method: 'POST', data: {} })
      toast('模型重训完成', 'success')
    },
    async importSamples() {
      let items = []
      try {
        items = JSON.parse(this.importText)
      } catch (err) {
        toast('JSON 格式错误', 'error')
        return
      }
      await request({ url: '/spam/samples/import', method: 'POST', data: { items } })
      toast('导入完成', 'success')
      this.fetchSamples()
    }
  }
}
</script>
