<template>
  <div class="forbidden-words-tab">
    <div class="tab-header">
      <div class="filter-section">
        <el-select v-model="filterCategory" placeholder="按类别筛选" clearable style="width: 140px;">
          <el-option v-for="opt in WORD_CATEGORY_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索禁词"
          clearable
          style="width: 200px;"
          @keyup.enter="loadWords"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="action-section">
        <el-button @click="testDialogVisible = true">
          <el-icon><Search /></el-icon>
          测试护栏
        </el-button>
        <el-button @click="showBatchImport = true">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          添加禁词
        </el-button>
      </div>
    </div>

    <el-table :data="words" v-loading="loading" stripe>
      <el-table-column prop="word" label="禁词" min-width="150" />
      <el-table-column prop="category" label="类别" width="120">
        <template #default="{ row }">
          <el-tag :type="getCategoryTagType(row.category)" size="small">
            {{ getCategoryLabel(row.category) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="strategy" label="策略" width="120">
        <template #default="{ row }">
          <el-tag size="small">
            {{ getStrategyLabel(row.strategy) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="hit_count" label="命中次数" width="100" sortable />
      <el-table-column prop="is_enabled" label="状态" width="80">
        <template #default="{ row }">
          <el-switch
            v-model="row.is_enabled"
            @change="handleToggleEnabled(row)"
            size="small"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑禁词' : '添加禁词'"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="禁词" prop="word">
          <el-input v-model="formData.word" placeholder="请输入禁词" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="formData.category" placeholder="请选择类别" style="width: 100%;">
            <el-option v-for="opt in WORD_CATEGORY_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="策略" prop="strategy">
          <el-radio-group v-model="formData.strategy">
            <el-radio-button
              v-for="opt in WORD_STRATEGY_OPTIONS"
              :key="opt.value"
              :value="opt.value"
            >
              {{ opt.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <transition name="slide-fade" mode="out-in">
          <el-form-item v-if="formData.strategy === 'replace'" label="替换文本" prop="replacement">
            <el-input v-model="formData.replacement" placeholder="请输入替换文本" />
          </el-form-item>
          <el-form-item v-else-if="formData.strategy === 'block'" label="兜底话术" prop="fallback_message">
            <el-input v-model="formData.fallback_message" type="textarea" :rows="3" placeholder="请输入兜底话术" />
          </el-form-item>
        </transition>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? '保存' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showBatchImport"
      title="批量导入禁词"
      width="500px"
      destroy-on-close
    >
      <el-form :model="batchForm" label-width="80px">
        <el-form-item label="默认类别">
          <el-select v-model="batchForm.category" style="width: 100%;">
            <el-option v-for="opt in WORD_CATEGORY_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认策略">
          <el-select v-model="batchForm.strategy" style="width: 100%;">
            <el-option v-for="opt in WORD_STRATEGY_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="禁词列表">
          <el-input
            v-model="batchForm.words"
            type="textarea"
            :rows="10"
            placeholder="每行一个禁词，例如：&#10;竞品A&#10;竞品B&#10;敏感词1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchImport = false">取消</el-button>
        <el-button type="primary" :loading="batchSubmitting" @click="handleBatchImport">
          导入
        </el-button>
      </template>
    </el-dialog>

    <TestDialog v-model:visible="testDialogVisible" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Search } from '@element-plus/icons-vue'
import {
  listForbiddenWords,
  createForbiddenWord,
  updateForbiddenWord,
  deleteForbiddenWord
} from '@/api/guardrail'
import { WORD_CATEGORY_OPTIONS, WORD_STRATEGY_OPTIONS } from '@/types/guardrail'
import type { ForbiddenWord, ForbiddenWordCreate, ForbiddenWordUpdate } from '@/types/guardrail'
import TestDialog from './TestDialog.vue'

const loading = ref(false)
const words = ref<ForbiddenWord[]>([])
const filterCategory = ref('')
const searchKeyword = ref('')
const dialogVisible = ref(false)
const showBatchImport = ref(false)
const testDialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const batchSubmitting = ref(false)
const formRef = ref()
const currentEditId = ref('')

const defaultFormData = (): ForbiddenWordCreate => ({
  word: '',
  category: 'custom',
  strategy: 'mask',
  replacement: '',
  fallback_message: '',
  is_enabled: true
})

const formData = ref<ForbiddenWordCreate>(defaultFormData())

const batchForm = ref({
  category: 'custom',
  strategy: 'mask',
  words: ''
})

const formRules = {
  word: [{ required: true, message: '请输入禁词', trigger: 'blur' }],
  category: [{ required: true, message: '请选择类别', trigger: 'change' }],
  strategy: [{ required: true, message: '请选择策略', trigger: 'change' }]
}

const getCategoryLabel = (category: string) => {
  const opt = WORD_CATEGORY_OPTIONS.find(o => o.value === category)
  return opt?.label || category
}

const getCategoryTagType = (category: string): '' | 'success' | 'warning' | 'danger' | 'info' => {
  const colorMap: Record<string, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    competitor: 'danger',
    sensitive: 'warning',
    political: 'danger',
    custom: 'info'
  }
  return colorMap[category] || 'info'
}

const getStrategyLabel = (strategy: string) => {
  const opt = WORD_STRATEGY_OPTIONS.find(o => o.value === strategy)
  return opt?.label || strategy
}

const loadWords = async () => {
  loading.value = true
  try {
    const res = await listForbiddenWords({
      category: filterCategory.value || undefined
    })
    words.value = res.data || []
  } catch (error) {
    ElMessage.error('加载禁词列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  isEdit.value = false
  currentEditId.value = ''
  formData.value = defaultFormData()
  dialogVisible.value = true
}

const handleEdit = (row: ForbiddenWord) => {
  isEdit.value = true
  currentEditId.value = row.id
  formData.value = {
    word: row.word,
    category: row.category,
    strategy: row.strategy,
    replacement: row.replacement || '',
    fallback_message: row.fallback_message || '',
    is_enabled: row.is_enabled
  }
  dialogVisible.value = true
}

const handleDelete = async (row: ForbiddenWord) => {
  try {
    await ElMessageBox.confirm('确定要删除该禁词吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteForbiddenWord(row.id)
    ElMessage.success('删除成功')
    loadWords()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleToggleEnabled = async (row: ForbiddenWord) => {
  try {
    await updateForbiddenWord(row.id, { is_enabled: row.is_enabled })
    ElMessage.success(row.is_enabled ? '已启用' : '已禁用')
  } catch (error) {
    row.is_enabled = !row.is_enabled
    ElMessage.error('操作失败')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitting.value = true
  try {
    if (isEdit.value) {
      const updateData: ForbiddenWordUpdate = {
        word: formData.value.word,
        category: formData.value.category,
        strategy: formData.value.strategy,
        replacement: formData.value.replacement,
        fallback_message: formData.value.fallback_message,
        is_enabled: formData.value.is_enabled
      }
      await updateForbiddenWord(currentEditId.value, updateData)
      ElMessage.success('保存成功')
    } else {
      await createForbiddenWord(formData.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadWords()
  } catch (error) {
    ElMessage.error(isEdit.value ? '保存失败' : '添加失败')
  } finally {
    submitting.value = false
  }
}

const handleBatchImport = async () => {
  const wordList = batchForm.value.words
    .split('\n')
    .map(w => w.trim())
    .filter(w => w.length > 0)

  if (wordList.length === 0) {
    ElMessage.warning('请输入要导入的禁词')
    return
  }

  batchSubmitting.value = true
  let successCount = 0
  let failCount = 0

  try {
    for (const word of wordList) {
      try {
        await createForbiddenWord({
          word,
          category: batchForm.value.category as any,
          strategy: batchForm.value.strategy as any,
          is_enabled: true
        })
        successCount++
      } catch {
        failCount++
      }
    }

    if (successCount > 0) {
      ElMessage.success(`成功导入 ${successCount} 个禁词${failCount > 0 ? `，${failCount} 个失败` : ''}`)
      showBatchImport.value = false
      batchForm.value.words = ''
      loadWords()
    } else {
      ElMessage.error('导入失败')
    }
  } finally {
    batchSubmitting.value = false
  }
}

watch(filterCategory, () => {
  loadWords()
})

onMounted(() => {
  loadWords()
})
</script>

<style scoped>
.forbidden-words-tab {
  min-height: 300px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-section {
  display: flex;
  gap: 12px;
}

.action-section {
  display: flex;
  gap: 12px;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>
