<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createUser } from '@/api/modules/system'
import type { CreateUserPayload, PermissionCode } from '@/types'

const router = useRouter()
const submitting = ref(false)

const form = reactive<CreateUserPayload>({
  username: '',
  display_name: '',
  password: 'platform123',
  role: 'viewer',
  status: 'active',
  permissions: ['dashboard'],
})

const permissionOptions: PermissionCode[] = [
  'dashboard',
  'fine-tune',
  'model-eval',
  'model-inference',
  'model-manage',
  'dataset',
  'data-process',
  'data-convert',
  'compute',
  'hardware',
  'logs',
  'user-settings',
]

async function submit() {
  submitting.value = true
  try {
    await createUser(form)
    ElMessage.success('用户已创建')
    router.push('/user-settings')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <section class="user-create">
    <h1>创建用户</h1>
    <el-form :model="form" label-width="110px" class="user-form">
      <el-form-item label="账号">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="显示名称">
        <el-input v-model="form.display_name" />
      </el-form-item>
      <el-form-item label="初始密码">
        <el-input v-model="form.password" type="password" show-password />
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="form.role">
          <el-option label="管理员" value="admin" />
          <el-option label="操作员" value="operator" />
          <el-option label="观察员" value="viewer" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio value="active">启用</el-radio>
          <el-radio value="disabled">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="页面权限">
        <el-checkbox-group v-model="form.permissions">
          <el-checkbox v-for="item in permissionOptions" :key="item" :value="item">{{ item }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="router.back()">返回</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<style scoped>
.user-create {
  padding: 24px;
}

.user-form {
  max-width: 760px;
}
</style>
