<template>
  <div class="page-container">
    <h2 class="page-title">分类分级标准</h2>

    <!-- Data Levels -->
    <div class="section">
      <div class="section-title">数据分级定义</div>
      <el-row :gutter="12">
        <el-col v-for="level in levels" :key="level.id" :xs="24" :sm="12" :md="8" :lg="5">
          <div class="level-card card-shadow" :style="{ borderLeft: `4px solid ${level.color}` }">
            <div class="level-header">
              <el-tag :color="level.color" effect="dark" size="small">{{ level.code }}</el-tag>
              <span class="level-name">{{ level.name }}</span>
            </div>
            <p class="level-desc">{{ level.description }}</p>
            <div v-if="level.control_requirements" class="level-ctrl">
              <div v-for="(v, k) in level.control_requirements" :key="k" class="ctrl-item">
                <span class="ctrl-key">{{ k }}:</span>
                <span class="ctrl-val">{{ v }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- Category Tree -->
    <div class="section">
      <div class="section-header">
        <span class="section-title">数据分类目录</span>
        <el-button type="primary" size="small" @click="handleAddCategory">
          <el-icon><Plus /></el-icon>新增分类
        </el-button>
      </div>
      <div class="category-tree card-shadow">
        <el-tree
          :data="categoryTree"
          :props="{ children: 'children', label: 'name' }"
          node-key="id"
          default-expand-all
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span class="node-label">
                <el-tag size="small" type="info" class="code-tag">{{ data.code }}</el-tag>
                {{ node.label }}
              </span>
              <span class="node-actions">
                <el-button type="primary" link size="small" @click.stop="handleEditCategory(data)">编辑</el-button>
                <el-button type="danger" link size="small" @click.stop="handleDeleteCategory(data)">删除</el-button>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
    </div>

    <!-- Recognition Rules -->
    <div class="section">
      <div class="section-header">
        <span class="section-title">识别规则</span>
        <el-button type="primary" size="small" @click="handleAddRule">
          <el-icon><Plus /></el-icon>新增规则
        </el-button>
      </div>
      <div class="table-card card-shadow">
        <el-table :data="ruleList" v-loading="ruleLoading" stripe size="default">
          <el-table-column prop="rule_name" label="规则名称" min-width="140" />
          <el-table-column prop="rule_type" label="类型" width="90">
            <template #default="{ row }">
              <el-tag size="small" :type="row.rule_type === 'regex' ? 'warning' : row.rule_type === 'similarity' ? 'success' : 'info'">
                {{ ({ regex: '正则', keyword: '关键词', enum: '枚举', similarity: '语义相似' } as Record<string, string>)[row.rule_type as string] || row.rule_type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="category_name" label="分类" min-width="120" />
          <el-table-column prop="level_name" label="分级" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.level_name" size="small" :color="row.level_color" effect="dark">
                {{ row.level_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="target_field" label="匹配目标" width="100" />
          <el-table-column prop="rule_content" label="规则内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="priority" label="优先级" width="80" />
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEditRule(row)">编辑</el-button>
              <el-button type="danger" link size="small" @click="handleDeleteRule(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Category Dialog -->
    <el-dialog v-model="catDialogVisible" :title="isEditCat ? '编辑分类' : '新增分类'" width="480px" destroy-on-close>
      <el-form ref="catFormRef" :model="catForm" :rules="catRules" label-width="100px">
        <el-form-item label="父分类">
          <el-cascader
            v-model="catForm.parent_id"
            :options="categoryTree"
            :props="{ value: 'id', label: 'name', checkStrictly: true, emitPath: false }"
            clearable
            placeholder="不选则为一级分类"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="catForm.code" placeholder="分类编码，如 CUST_PERSONAL" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="catForm.name" placeholder="分类名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="catForm.description" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="catForm.sort_order" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="catDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitCategory">确定</el-button>
      </template>
    </el-dialog>

    <!-- Rule Dialog -->
    <el-dialog v-model="ruleDialogVisible" :title="isEditRule ? '编辑规则' : '新增规则'" width="560px" destroy-on-close>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="ruleRules" label-width="100px">
        <el-form-item label="规则名称">
          <el-input v-model="ruleForm.rule_name" placeholder="规则名称" />
        </el-form-item>
        <el-form-item label="规则类型" prop="rule_type">
          <el-radio-group v-model="ruleForm.rule_type">
            <el-radio-button label="regex">正则匹配</el-radio-button>
            <el-radio-button label="keyword">关键词</el-radio-button>
            <el-radio-button label="enum">枚举</el-radio-button>
            <el-radio-button label="similarity">语义相似</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属分类" prop="category_id">
          <el-cascader
            v-model="ruleForm.category_id"
            :options="categoryTree"
            :props="{ value: 'id', label: 'name', checkStrictly: true, emitPath: false }"
            clearable
            placeholder="选择分类"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="数据分级" prop="level_id">
          <el-select v-model="ruleForm.level_id" placeholder="选择分级" style="width: 100%">
            <el-option v-for="l in levels" :key="l.id" :label="l.name" :value="l.id">
              <el-tag size="small" :color="l.color" effect="dark">{{ l.code }}</el-tag>
              {{ l.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="匹配目标" prop="target_field">
          <el-radio-group v-model="ruleForm.target_field">
            <el-radio-button label="column_name">字段名</el-radio-button>
            <el-radio-button label="comment">注释</el-radio-button>
            <el-radio-button label="sample_data">采样数据</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规则内容" prop="rule_content">
          <el-input v-model="ruleForm.rule_content" type="textarea" :rows="3" :placeholder="ruleContentPlaceholder" />
        </el-form-item>
        <el-form-item label="优先级">
          <el-input-number v-model="ruleForm.priority" :min="1" :max="999" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="ruleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitRule">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getCategoryTree, getDataLevels, getRules,
  createCategory, updateCategory, deleteCategory,
  createRule, updateRule, deleteRule, getTemplates,
} from '@/api/classification'
import type { CategoryItem, DataLevel, RecognitionRule } from '@/api/classification'

const levels = ref<DataLevel[]>([])
const categoryTree = ref<CategoryItem[]>([])
const ruleList = ref<RecognitionRule[]>([])
const ruleLoading = ref(false)
const templates = ref<any[]>([])

// Category dialog
const catDialogVisible = ref(false)
const isEditCat = ref(false)
const catEditId = ref<number | null>(null)
const catFormRef = ref()
const catForm = reactive({
  parent_id: undefined as number | undefined,
  code: '',
  name: '',
  description: '',
  sort_order: 0,
})
const catRules = {
  code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
}

// Rule dialog
const ruleDialogVisible = ref(false)
const isEditRule = ref(false)
const ruleEditId = ref<number | null>(null)
const ruleFormRef = ref()
const ruleForm = reactive({
  template_id: undefined as number | undefined,
  rule_name: '',
  rule_type: 'keyword',
  category_id: undefined as number | undefined,
  level_id: undefined as number | undefined,
  target_field: 'column_name',
  rule_content: '',
  priority: 100,
})
const ruleRules = {
  rule_type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  rule_content: [{ required: true, message: '请输入规则内容', trigger: 'blur' }],
}

const ruleContentPlaceholder = computed(() => {
  const map: Record<string, string> = {
    regex: '正则表达式，如：(\\d{15}|\\d{18}|\\d{17}[xX])',
    keyword: '关键词列表，逗号分隔，如：手机,mobile,phone',
    enum: '枚举值列表，逗号分隔，如：男,女,未知',
    similarity: '基准词列表，逗号分隔，如：phone,mobile,telephone',
  }
  return map[ruleForm.rule_type] || '请输入规则内容'
})

async function fetchLevels() {
  try {
    const res: any = await getDataLevels()
    levels.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e?.message || '加载分级失败')
  }
}

async function fetchCategories() {
  try {
    const res: any = await getCategoryTree()
    categoryTree.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e?.message || '加载分类失败')
  }
}

async function fetchRules() {
  ruleLoading.value = true
  try {
    const tpl = templates.value[0]
    const res: any = await getRules({ template_id: tpl?.id, page: 1, page_size: 100 })
    ruleList.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e?.message || '加载规则失败')
  } finally {
    ruleLoading.value = false
  }
}

async function fetchTemplates() {
  try {
    const res: any = await getTemplates()
    templates.value = res.data || []
  } catch (e: any) {
    // ignore
  }
}

function handleAddCategory() {
  isEditCat.value = false
  catEditId.value = null
  catForm.parent_id = undefined
  catForm.code = ''
  catForm.name = ''
  catForm.description = ''
  catForm.sort_order = 0
  catDialogVisible.value = true
}

function handleEditCategory(data: CategoryItem) {
  isEditCat.value = true
  catEditId.value = data.id
  catForm.parent_id = data.parent_id
  catForm.code = data.code
  catForm.name = data.name
  catForm.description = data.description || ''
  catForm.sort_order = data.sort_order
  catDialogVisible.value = true
}

async function handleSubmitCategory() {
  const valid = await catFormRef.value?.validate().catch(() => false)
  if (!valid) return
  try {
    if (isEditCat.value && catEditId.value) {
      await updateCategory(catEditId.value, { ...catForm })
      ElMessage.success('更新成功')
    } else {
      await createCategory({ ...catForm, level: catForm.parent_id ? 2 : 1 })
      ElMessage.success('创建成功')
    }
    catDialogVisible.value = false
    fetchCategories()
  } catch (e: any) {
    ElMessage.error(e?.message || '操作失败')
  }
}

async function handleDeleteCategory(data: CategoryItem) {
  try {
    await ElMessageBox.confirm('确认删除该分类？', '提示', { type: 'warning' })
    await deleteCategory(data.id)
    ElMessage.success('删除成功')
    fetchCategories()
  } catch (e: any) {
    if (e !== 'cancel') ElMessage.error(e?.message || '删除失败')
  }
}

function handleAddRule() {
  isEditRule.value = false
  ruleEditId.value = null
  ruleForm.template_id = templates.value[0]?.id
  ruleForm.rule_name = ''
  ruleForm.rule_type = 'keyword'
  ruleForm.category_id = undefined
  ruleForm.level_id = undefined
  ruleForm.target_field = 'column_name'
  ruleForm.rule_content = ''
  ruleForm.priority = 100
  ruleDialogVisible.value = true
}

function handleEditRule(row: RecognitionRule) {
  isEditRule.value = true
  ruleEditId.value = row.id
  ruleForm.template_id = row.template_id
  ruleForm.rule_name = row.rule_name || ''
  ruleForm.rule_type = row.rule_type
  ruleForm.category_id = row.category_id
  ruleForm.level_id = row.level_id
  ruleForm.target_field = row.target_field
  ruleForm.rule_content = row.rule_content
  ruleForm.priority = row.priority
  ruleDialogVisible.value = true
}

async function handleSubmitRule() {
  const valid = await ruleFormRef.value?.validate().catch(() => false)
  if (!valid) return
  try {
    if (isEditRule.value && ruleEditId.value) {
      await updateRule(ruleEditId.value, { ...ruleForm })
      ElMessage.success('更新成功')
    } else {
      await createRule({ ...ruleForm })
      ElMessage.success('创建成功')
    }
    ruleDialogVisible.value = false
    fetchRules()
  } catch (e: any) {
    ElMessage.error(e?.message || '操作失败')
  }
}

async function handleDeleteRule(row: RecognitionRule) {
  try {
    await ElMessageBox.confirm('确认删除该规则？', '提示', { type: 'warning' })
    await deleteRule(row.id)
    ElMessage.success('删除成功')
    fetchRules()
  } catch (e: any) {
    if (e !== 'cancel') ElMessage.error(e?.message || '删除失败')
  }
}

onMounted(async () => {
  await fetchTemplates()
  await fetchLevels()
  await fetchCategories()
  await fetchRules()
})
</script>

<style scoped lang="scss">
.page-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #303133;
}

.section {
  margin-bottom: 24px;

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

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.level-card {
  padding: 16px;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 8px;

  .level-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
  }

  .level-name {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
  }

  .level-desc {
    font-size: 13px;
    color: #606266;
    line-height: 1.5;
    margin-bottom: 8px;
  }

  .level-ctrl {
    .ctrl-item {
      font-size: 12px;
      color: #909399;
      margin-bottom: 2px;

      .ctrl-key {
        font-weight: 500;
        color: #606266;
      }
    }
  }
}

.category-tree {
  padding: 16px;
  background: #fff;
  border-radius: 8px;

  .custom-tree-node {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex: 1;
    overflow: hidden;

    .node-label {
      display: flex;
      align-items: center;
      gap: 8px;
      overflow: hidden;

      .code-tag {
        font-size: 11px;
        flex-shrink: 0;
      }
    }

    .node-actions {
      flex-shrink: 0;
    }
  }
}

.table-card {
  padding: 16px;
  background: #fff;
  border-radius: 8px;
}
</style>
