<!-- 角色管理:内置角色 + 自定义角色 CRUD,权限字符串编辑 -->
<template>
  <div class="page-content">
    <div class="mb-5 flex items-center justify-between gap-4">
      <div>
        <h2 class="text-xl font-semibold">角色管理</h2>
        <p class="text-g-500 mt-1 text-sm">内置角色不可修改;自定义角色权限在分配账号时展开生效</p>
      </div>
      <ElButton type="primary" @click="openCreate">新增角色</ElButton>
    </div>

    <ElTable v-loading="loading" :data="roles" row-key="id">
      <ElTableColumn prop="code" label="代码" width="160" />
      <ElTableColumn prop="name" label="名称" min-width="140" />
      <ElTableColumn prop="description" label="描述" min-width="180" show-overflow-tooltip />
      <ElTableColumn label="类型" width="100">
        <template #default="{ row }">
          <ElTag :type="row.builtin ? 'info' : 'success'">{{ row.builtin ? '内置' : '自定义' }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn label="权限数" width="90">
        <template #default="{ row }">{{ (row.permissions || []).length }}</template>
      </ElTableColumn>
      <ElTableColumn label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <ElButton link type="primary" :disabled="row.builtin" @click="openEdit(row)">编辑</ElButton>
          <ElButton link type="danger" :disabled="row.builtin" @click="remove(row)">删除</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElDialog v-model="dialogVisible" :title="editingId ? '编辑角色' : '新增角色'" width="640px">
      <ElForm ref="formRef" :model="form" :rules="rules" label-width="90px">
        <ElFormItem label="代码" prop="code">
          <ElInput v-model="form.code" :disabled="!!editingId" placeholder="小写字母开头,如 ops-lead" />
        </ElFormItem>
        <ElFormItem label="名称" prop="name"><ElInput v-model="form.name" maxlength="64" /></ElFormItem>
        <ElFormItem label="描述"><ElInput v-model="form.description" maxlength="512" /></ElFormItem>
        <ElFormItem label="权限">
          <ElSelect v-model="form.permissions" multiple filterable collapse-tags class="w-full" placeholder="选择权限字符串">
            <ElOption v-for="permission in permissionOptions" :key="permission.value" :label="permission.label" :value="permission.value" />
          </ElSelect>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" :loading="saving" @click="submit">保存</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
  import request from '@/utils/http'

  interface Role {
    id: string
    code: string
    name: string
    description: string
    permissions: string[]
    builtin: boolean
  }

  const permissionOptions = [
    { label: '身份管理 identity:manage', value: 'identity:manage' },
    { label: '供应商管理 provider:manage', value: 'provider:manage' },
    { label: '供应商查看 provider:read', value: 'provider:read' },
    { label: 'API Key 管理 api_key:manage', value: 'api_key:manage' },
    { label: 'API Key 查看 api_key:read', value: 'api_key:read' },
    { label: '审计查看 audit:read', value: 'audit:read' },
    { label: '用量查看 usage:read', value: 'usage:read' },
    { label: 'Outbox 管理 outbox:manage', value: 'outbox:manage' },
    { label: '内容策略管理 content_policy:manage', value: 'content_policy:manage' },
    { label: '定价管理 pricing:manage', value: 'pricing:manage' },
    { label: 'Prompt 管理 prompt:manage', value: 'prompt:manage' },
    { label: '知识库管理 knowledge:manage', value: 'knowledge:manage' },
    { label: '工具管理 tool:manage', value: 'tool:manage' },
    { label: '应用管理 application:manage', value: 'application:manage' },
    { label: '通知管理 notification:manage', value: 'notification:manage' },
    { label: 'MCP 管理 mcp_server:manage', value: 'mcp_server:manage' },
    { label: 'Skill 管理 skill:manage', value: 'skill:manage' },
    { label: '数字员工管理 digital_employee:manage', value: 'digital_employee:manage' },
    { label: '市场管理 marketplace:manage', value: 'marketplace:manage' },
    { label: '文件管理 file:manage', value: 'file:manage' },
    { label: '消息管理 inbox:manage', value: 'inbox:manage' },
    { label: '定时任务管理 scheduled_task:manage', value: 'scheduled_task:manage' },
    { label: 'Trace 查看 trace:read', value: 'trace:read' },
    { label: '智能体节点管理 agent_node:manage', value: 'agent_node:manage' },
    { label: '系统管理 system:manage', value: 'system:manage' }
  ]

  const roles = ref<Role[]>([])
  const loading = ref(false)
  const saving = ref(false)
  const dialogVisible = ref(false)
  const editingId = ref('')
  const formRef = ref<FormInstance>()
  const form = reactive({ code: '', name: '', description: '', permissions: [] as string[] })
  const rules: FormRules = {
    code: [{ required: true, message: '请输入角色代码', trigger: 'blur' }],
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
  }

  async function load() {
    loading.value = true
    try {
      roles.value = await request.get<Role[]>({ url: '/api/v1/admin/roles' })
    } finally {
      loading.value = false
    }
  }

  function openCreate() {
    editingId.value = ''
    Object.assign(form, { code: '', name: '', description: '', permissions: [] })
    dialogVisible.value = true
  }

  function openEdit(row: Role) {
    editingId.value = row.id
    Object.assign(form, { code: row.code, name: row.name, description: row.description, permissions: [...row.permissions] })
    dialogVisible.value = true
  }

  async function submit() {
    if (!(await formRef.value?.validate())) return
    saving.value = true
    try {
      if (editingId.value) {
        await request.put({ url: `/api/v1/admin/roles/${editingId.value}`, params: { ...form } })
        ElMessage.success('角色已更新')
      } else {
        await request.post({ url: '/api/v1/admin/roles', params: { ...form } })
        ElMessage.success('角色已创建')
      }
      dialogVisible.value = false
      await load()
    } finally {
      saving.value = false
    }
  }

  async function remove(row: Role) {
    try {
      await ElMessageBox.confirm(`确认删除角色「${row.name}」？已分配该角色的账号权限不会自动回收。`, '删除角色', { type: 'warning' })
    } catch {
      return
    }
    try {
      await request.del({ url: `/api/v1/admin/roles/${row.id}` })
      ElMessage.success('已删除')
      await load()
    } catch { /* 全局错误提示 */ }
  }

  onMounted(load)
</script>
