<template>
  <div class="page-content">
    <div class="mb-5 flex items-start justify-between">
      <div><h2 class="text-xl font-semibold">内容策略</h2><p class="text-g-500 mt-1 text-sm">使用 RE2 规则审计、阻断或脱敏提示词中的敏感内容；不会改写工具定义和二进制字段</p></div>
      <ElButton type="primary" @click="openCreate">新建策略</ElButton>
    </div>
    <ElAlert class="mb-4" type="info" :closable="false" title="规则按优先级从高到低执行。阻断立即结束；脱敏只作用于 content、text、input、prompt、instructions 文本字段。" />
    <ElTable v-loading="loading" :data="items" row-key="id">
      <ElTableColumn prop="name" label="名称" min-width="180" />
      <ElTableColumn label="动作" width="100"><template #default="{ row }"><ElTag :type="actionType(row.action)">{{ actionText(row.action) }}</ElTag></template></ElTableColumn>
      <ElTableColumn prop="priority" label="优先级" width="90" />
      <ElTableColumn label="范围" min-width="190"><template #default="{ row }">{{ scopeText(row) }}</template></ElTableColumn>
      <ElTableColumn label="规则" min-width="180"><template #default="{ row }">{{ row.rules.map((r: ContentRule) => r.name).join('、') }}</template></ElTableColumn>
      <ElTableColumn label="状态" width="90"><template #default="{ row }"><ElTag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</ElTag></template></ElTableColumn>
      <ElTableColumn label="操作" width="150" fixed="right"><template #default="{ row }"><ElButton link type="primary" @click="openEdit(row)">编辑</ElButton><ElButton link type="danger" @click="remove(row)">删除</ElButton></template></ElTableColumn>
    </ElTable>

    <ElDialog v-model="visible" :title="editing ? '编辑内容策略' : '新建内容策略'" width="760px">
      <ElForm label-width="100px">
        <div class="grid grid-cols-2 gap-x-4"><ElFormItem label="名称"><ElInput v-model="form.name" /></ElFormItem><ElFormItem label="动作"><ElSelect v-model="form.action" class="w-full"><ElOption label="脱敏" value="redact" /><ElOption label="阻断" value="block" /><ElOption label="仅审计" value="audit" /></ElSelect></ElFormItem></div>
        <div class="grid grid-cols-2 gap-x-4"><ElFormItem label="优先级"><ElInputNumber v-model="form.priority" :min="-100000" :max="100000" /></ElFormItem><ElFormItem label="状态"><ElSwitch v-model="form.enabled" active-text="启用" /></ElFormItem></div>
        <ElFormItem label="描述"><ElInput v-model="form.description" type="textarea" /></ElFormItem>
        <ElFormItem label="端点范围"><ElSelect v-model="form.paths" multiple allow-create filterable class="w-full" placeholder="留空表示全部，例如 /v1/chat/completions" /></ElFormItem>
        <ElFormItem label="模型范围"><ElSelect v-model="form.models" multiple allow-create filterable class="w-full" placeholder="留空表示全部，填写精确模型名" /></ElFormItem>
        <ElFormItem label="API Key"><ElSelect v-model="form.api_key_ids" multiple allow-create filterable class="w-full" placeholder="留空表示全部，填写 API Key UUID" /></ElFormItem>
        <ElDivider content-position="left">RE2 规则</ElDivider>
        <div v-for="(rule, index) in form.rules" :key="index" class="mb-3 grid grid-cols-[150px_1fr_180px_40px] gap-2">
          <ElInput v-model="rule.name" placeholder="规则名称" /><ElInput v-model="rule.pattern" placeholder="RE2 正则" /><ElInput v-model="rule.replacement" placeholder="替换文本" /><ElButton text type="danger" @click="form.rules.splice(index, 1)">删</ElButton>
        </div>
        <ElButton text type="primary" @click="form.rules.push({ name: '', pattern: '', replacement: '[REDACTED]' })">+ 添加规则</ElButton>
      </ElForm>
      <template #footer><ElButton @click="visible=false">取消</ElButton><ElButton type="primary" :loading="saving" @click="save">保存</ElButton></template>
    </ElDialog>
  </div>
</template>
<script setup lang="ts">
  import { ContentPolicy, ContentPolicyInput, ContentRule, createContentPolicy, deleteContentPolicy, fetchContentPolicies, updateContentPolicy } from '@/api/content-policy'
  import { ElMessage, ElMessageBox } from 'element-plus'
  const loading=ref(false),saving=ref(false),visible=ref(false);const items=ref<ContentPolicy[]>([]);const editing=ref('')
  const blank=():ContentPolicyInput=>({name:'',description:'',action:'redact',priority:0,paths:[],models:[],api_key_ids:[],rules:[{name:'敏感词',pattern:'',replacement:'[REDACTED]'}],enabled:true});const form=reactive<ContentPolicyInput>(blank())
  async function load(){loading.value=true;try{items.value=await fetchContentPolicies()}finally{loading.value=false}}
  function assign(value:ContentPolicyInput){Object.assign(form,{name:value.name,description:value.description,action:value.action,priority:value.priority,paths:[...value.paths],models:[...value.models],api_key_ids:[...value.api_key_ids],rules:value.rules.map(rule=>({...rule})),enabled:value.enabled})}
  function openCreate(){editing.value='';assign(blank());visible.value=true}
  function openEdit(row:ContentPolicy){editing.value=row.id;assign(row);visible.value=true}
  async function save(){saving.value=true;try{editing.value?await updateContentPolicy(editing.value,form):await createContentPolicy(form);visible.value=false;ElMessage.success('策略已保存并生效');await load()}finally{saving.value=false}}
  async function remove(row:ContentPolicy){await ElMessageBox.confirm(`确认删除“${row.name}”？`,'删除策略',{type:'warning'});await deleteContentPolicy(row.id);ElMessage.success('已删除');await load()}
  function actionText(v:string){return({redact:'脱敏',block:'阻断',audit:'审计'} as Record<string,string>)[v]||v} function actionType(v:string){return v==='block'?'danger':v==='redact'?'warning':'info'}
  function scopeText(row:ContentPolicy){const parts=[];if(row.paths.length)parts.push(`${row.paths.length} 个端点`);if(row.models.length)parts.push(`${row.models.length} 个模型`);if(row.api_key_ids.length)parts.push(`${row.api_key_ids.length} 个 Key`);return parts.join(' / ')||'全部请求'}
  onMounted(load)
</script>
