<template>
  <div class="sensitive-person-manager">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.name"
            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="name" label="姓名" min-width="120">
        <template #default="{ row }">
          <span :class="{ 'sensitive-person': true, [`level-${row.level}`]: true }">
            {{ row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="aliases" label="别名" min-width="200">
        <template #default="{ row }">
          <el-tag v-for="alias in row.aliases" :key="alias" size="small" class="alias-tag">
            {{ alias }}
          </el-tag>
        </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="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="600px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入敏感人物姓名" />
        </el-form-item>
        <el-form-item label="别名" prop="aliases">
          <el-input
            v-model="aliasesText"
            type="textarea"
            :rows="3"
            placeholder="请输入别名，每行一个"
            @blur="handleAliasesChange" />
          <div class="form-tip">每行输入一个别名，系统会自动识别</div>
        </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="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 { sensitivePersonStorage } from '@/utils/llmStorage'

// 搜索表单
const searchForm = reactive({
  name: '',
  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({
  name: '',
  aliases: [],
  level: 'medium',
  is_enabled: true,
})
const aliasesText = ref('')

// 移除测试相关变量

// 表单验证规则
const rules: FormRules = {
  name: [
    { 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 handleAliasesChange = () => {
  const aliases = aliasesText.value
    .split('\n')
    .map((alias) => alias.trim())
    .filter((alias) => alias)
  formData.aliases = aliases as any
}

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

    // 应用搜索过滤
    if (searchForm.name) {
      allData = allData.filter(
        (item: any) =>
          item.name.toLowerCase().includes(searchForm.name.toLowerCase()) ||
          item.aliases.some((alias: string) => alias.toLowerCase().includes(searchForm.name.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, {
    name: '',
    level: '',
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  Object.assign(formData, {
    name: '',
    aliases: [],
    level: 'medium',
    is_enabled: true,
  })
  aliasesText.value = ''
  formVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(formData, row)
  aliasesText.value = row.aliases.join('\n')
  formVisible.value = true
}

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

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

  // 更新别名
  handleAliasesChange()

  submitting.value = true
  try {
    if (isEdit.value && (formData as any).id) {
      sensitivePersonStorage.update((formData as any).id, formData)
      ElMessage.success('更新成功')
    } else {
      sensitivePersonStorage.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.name}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    if (row.id) {
      sensitivePersonStorage.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 {
    sensitivePersonStorage.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) => sensitivePersonStorage.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) => sensitivePersonStorage.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) => sensitivePersonStorage.update(item.id, { is_enabled: true }))

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

// 移除分页变化方法

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

<style lang="scss" scoped>
.sensitive-person-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-person {
    font-weight: bold;

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

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

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

  .alias-tag {
    margin-right: 5px;
    margin-bottom: 5px;
  }

  .form-tip {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
  }

  .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-name {
        font-weight: bold;
        color: #f56c6c;
      }

      .result-alias {
        color: #909399;
        font-size: 12px;
      }

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