<template>
  <div class="sensitive-word-manager">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.word"
            placeholder="请输入敏感词"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.level" placeholder="敏感级别" clearable @change="handleSearch">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增敏感词
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="word" label="敏感词" min-width="150">
        <template #default="{ row }">
          <span :class="{ 'sensitive-word': true, [`level-${row.level}`]: true }">
            {{ row.word }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="敏感级别" width="100">
        <template #default="{ row }">
          <el-tag :type="getLevelTagType(row.level) as any">
            {{ getLevelLabel(row.level) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="replacement" label="替换词" min-width="150">
        <template #default="{ row }">
          {{ row.replacement || '***' }}
        </template>
      </el-table-column>
      <el-table-column prop="is_enabled" label="状态" width="80">
        <template #default="{ row }">
          <el-switch v-model="row.is_enabled" @change="handleToggleStatus(row)" :loading="row.statusLoading" />
        </template>
      </el-table-column>
      <el-table-column prop="created_time" label="创建时间" width="160">
        <template #default="{ row }">
          {{ formatDate(row.created_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)"> 编辑 </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 移除分页组件 -->

    <!-- 批量操作 -->
    <div v-if="selectedRows.length > 0" class="batch-actions">
      <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" show-icon :closable="false">
        <template #default>
          <el-button type="danger" size="small" @click="handleBatchDelete"> 批量删除 </el-button>
          <el-button type="warning" size="small" @click="handleBatchDisable"> 批量禁用 </el-button>
          <el-button type="success" size="small" @click="handleBatchEnable"> 批量启用 </el-button>
        </template>
      </el-alert>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="formVisible" :title="isEdit ? '编辑敏感词' : '新增敏感词'" width="500px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="敏感词" prop="word">
          <el-input v-model="formData.word" placeholder="请输入敏感词" />
        </el-form-item>
        <el-form-item label="敏感级别" prop="level">
          <el-select v-model="formData.level" placeholder="请选择敏感级别">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>
        </el-form-item>
        <el-form-item label="替换词" prop="replacement">
          <el-input v-model="formData.replacement" placeholder="请输入替换词（可选）" />
        </el-form-item>
        <el-form-item label="启用状态" prop="is_enabled">
          <el-switch v-model="formData.is_enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 移除批量导入和测试检测对话框 -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { sensitiveWordStorage } from '@/utils/llmStorage'

// 搜索表单
const searchForm = reactive({
  word: '',
  level: '',
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const selectedRows = ref<any[]>([])

// 移除分页相关变量

// 表单相关
const formVisible = ref(false)
const formRef = ref<FormInstance>()
const submitting = ref(false)
const isEdit = ref(false)
const formData = reactive({
  word: '',
  level: 'medium',
  replacement: '',
  is_enabled: true,
})

// 移除导入和测试相关变量

// 表单验证规则
const rules: FormRules = {
  word: [
    { required: true, message: '请输入敏感词', trigger: 'blur' },
    { min: 1, max: 50, message: '敏感词长度在 1 到 50 个字符', trigger: 'blur' },
  ],
  level: [{ required: true, message: '请选择敏感级别', trigger: 'change' }],
}

// 获取级别标签类型
const getLevelTagType = (level: string) => {
  const typeMap: Record<string, string> = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
  }
  return typeMap[level] || 'info'
}

// 获取级别标签
const getLevelLabel = (level: string) => {
  const labelMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
  }
  return labelMap[level] || level
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 加载数据
const loadData = () => {
  loading.value = true
  try {
    // 获取所有数据
    let allData = sensitiveWordStorage.getAll()

    // 应用搜索过滤
    if (searchForm.word) {
      allData = allData.filter((item: any) => item.word.toLowerCase().includes(searchForm.word.toLowerCase()))
    }

    if (searchForm.level) {
      allData = allData.filter((item: any) => item.level === searchForm.level)
    }

    // 直接显示所有数据，不分页
    tableData.value = allData
  } catch (error: any) {
    ElMessage.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    word: '',
    level: '',
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  Object.assign(formData, {
    word: '',
    level: 'medium',
    replacement: '',
    is_enabled: true,
  })
  formVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(formData, row)
  formVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  submitting.value = true
  try {
    if (isEdit.value && (formData as any).id) {
      sensitiveWordStorage.update((formData as any).id, formData)
      ElMessage.success('更新成功')
    } else {
      sensitiveWordStorage.create(formData)
      ElMessage.success('创建成功')
    }
    formVisible.value = false
    loadData()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除敏感词 "${row.word}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    if (row.id) {
      sensitiveWordStorage.delete(row.id)
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 切换状态
const handleToggleStatus = async (row: any) => {
  if (!row.id) return

  row.statusLoading = true
  try {
    sensitiveWordStorage.update(row.id, { is_enabled: row.is_enabled })
    ElMessage.success(row.is_enabled ? '启用成功' : '禁用成功')
  } catch (error: any) {
    row.is_enabled = !row.is_enabled // 回滚状态
    ElMessage.error(error.message || '操作失败')
  } finally {
    row.statusLoading = false
  }
}

// 移除批量导入和测试检测功能

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个敏感词吗？`, '确认批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    selectedRows.value.filter((item) => item.id).forEach((item) => sensitiveWordStorage.delete(item.id))
    ElMessage.success('批量删除成功')
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量删除失败')
    }
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  try {
    selectedRows.value
      .filter((item) => item.id)
      .forEach((item) => sensitiveWordStorage.update(item.id, { is_enabled: false }))

    ElMessage.success('批量禁用成功')
    loadData()
  } catch (error: any) {
    ElMessage.error(error.message || '批量禁用失败')
  }
}

// 批量启用
const handleBatchEnable = async () => {
  try {
    selectedRows.value
      .filter((item) => item.id)
      .forEach((item) => sensitiveWordStorage.update(item.id, { is_enabled: true }))

    ElMessage.success('批量启用成功')
    loadData()
  } catch (error: any) {
    ElMessage.error(error.message || '批量启用失败')
  }
}

// 移除分页变化方法

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

<style lang="scss" scoped>
.sensitive-word-manager {
  .search-bar {
    margin-bottom: 20px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 6px;
  }

  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }

  .batch-actions {
    margin-top: 20px;
  }

  .text-right {
    text-align: right;
  }

  .sensitive-word {
    font-weight: bold;

    &.level-low {
      color: #409eff;
    }

    &.level-medium {
      color: #e6a23c;
    }

    &.level-high {
      color: #f56c6c;
    }
  }

  .test-result {
    margin-top: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 6px;

    .result-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      gap: 10px;

      .result-word {
        font-weight: bold;
        color: #f56c6c;
      }

      .result-position {
        color: #909399;
        font-size: 12px;
      }
    }
  }
}
</style>
