import {GlassButton, html, TextField, useState, useToast} from 'vendor'; import {api, useFetch} from '../api.js'; import {ROLE_NAME} from '../format.js'; import {DataTable} from '../components/DataTable.js'; import {FormDialog} from '../components/FormDialog.js'; import {Loading, Section, Select} from '../components/ui.js'; const ROLES = [{value: 'user', label: '普通用户'}, {value: 'admin', label: '管理员'}]; export default function Users() { const toast = useToast(); const {data, reload} = useFetch('/api/users'); const [adding, setAdding] = useState(false); const [resetting, setResetting] = useState(null); /** 发送请求:成功提示并刷新列表;失败提示后继续抛出(让表单弹窗保持打开) */ const send = async (url, options, message) => { try { await api(url, options); } catch (e) { toast({message: e.message, tone: 'error'}); throw e; } toast({message, tone: 'success'}); reload(); }; const checkPassword = password => { if (password.length >= 6) return; toast({message: '密码至少 6 位', tone: 'error'}); throw new Error('invalid'); }; const addUser = d => { checkPassword(d.password); return send('/api/users', {json: d}, '已新增'); }; const resetPassword = d => { checkPassword(d.password); return send(`/api/users/${resetting.id}`, {method: 'PUT', json: d}, '密码已重置'); }; const toggleRole = u => send(`/api/users/${u.id}`, {method: 'PUT', json: {role: u.role === 'admin' ? 'user' : 'admin'}}, '角色已更新').catch(() => {}); const removeUser = u => { if (confirm(`确认删除用户「${u.username}」?`)) send(`/api/users/${u.id}`, {method: 'DELETE'}, '已删除').catch(() => {}); }; const columns = [ {key: 'id', title: 'ID'}, {key: 'username', title: '用户名'}, {key: 'role', title: '角色', render: v => ROLE_NAME[v]}, {key: 'created_at', title: '创建时间'}, {key: '_ops', title: '操作', render: (_, u) => html`