| import React, { useState, useEffect } from 'react'; |
| import '../style/Admin.css'; |
| import { Select, message, Table } from 'antd'; |
| import { fetchUserList, giveUser, giveAdmin, giveSuperAdmin } from '../api/posts_trm'; |
| |
| const { Option } = Select; |
| const ROLE_LIST = ['用户', '管理员', '超级管理员']; |
| |
| function UserManagement({ superAdminId }) { |
| const [users, setUsers] = useState([]); |
| |
| useEffect(() => { |
| async function load() { |
| try { |
| const data = superAdminId |
| ? await fetchUserList(superAdminId) |
| : await fetch('/api/users').then(res => res.json()); |
| setUsers(data); |
| } catch (e) { |
| console.error(e); |
| } |
| } |
| load(); |
| }, [superAdminId]); |
| |
| // handle role changes |
| const handleRoleChange = async (userId, newRole) => { |
| try { |
| if (newRole === '用户') await giveUser(superAdminId, userId); |
| else if (newRole === '管理员') await giveAdmin(superAdminId, userId); |
| else if (newRole === '超级管理员') await giveSuperAdmin(superAdminId, userId); |
| setUsers(us => us.map(u => u.id === userId ? { ...u, role: newRole } : u)); |
| message.success('修改成功'); |
| } catch (e) { |
| console.error(e); |
| message.error('修改失败'); |
| } |
| }; |
| |
| // define table columns |
| const columns = [ |
| { title: '用户名', dataIndex: 'username', key: 'username' }, |
| { title: '角色', dataIndex: 'role', key: 'role' }, |
| { |
| title: '操作', |
| key: 'action', |
| render: (_, record) => { |
| const orderedRoles = [record.role, ...ROLE_LIST.filter(r => r !== record.role)]; |
| return ( |
| <Select |
| value={record.role} |
| style={{ width: 120 }} |
| onChange={value => handleRoleChange(record.id, value)} |
| > |
| {orderedRoles.map(r => ( |
| <Option key={r} value={r}>{r}</Option> |
| ))} |
| </Select> |
| ); |
| }, |
| }, |
| ]; |
| |
| return ( |
| <div className="admin-container"> |
| <Table |
| dataSource={users} |
| columns={columns} |
| rowKey="id" |
| pagination={false} |
| /> |
| </div> |
| ); |
| } |
| |
| export default UserManagement; |