Users.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import React, { useState } from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { format } from 'date-fns';
  4. import { Plus, Search, Edit, Trash2, User, Mail, Phone } from 'lucide-react';
  5. import { userClient, roleClient } from '@/client/api';
  6. import type { InferResponseType, InferRequestType } from 'hono/client';
  7. import { Button } from '@/client/components/ui/button';
  8. import { Input } from '@/client/components/ui/input';
  9. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
  10. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
  11. import { Badge } from '@/client/components/ui/badge';
  12. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
  13. import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
  14. import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
  15. import { useForm } from 'react-hook-form';
  16. import { zodResolver } from '@hookform/resolvers/zod';
  17. import { z } from 'zod';
  18. import { toast } from 'sonner';
  19. import { Skeleton } from '@/client/components/ui/skeleton';
  20. import { Switch } from '@/client/components/ui/switch';
  21. import { Label } from '@/client/components/ui/label';
  22. type UserListResponse = InferResponseType<typeof userClient.$get, 200>;
  23. type CreateUserRequest = InferRequestType<typeof userClient.$post>['json'];
  24. type UpdateUserRequest = InferRequestType<typeof userClient[':id']['$put']>['json'];
  25. // 表单验证Schema
  26. const userFormSchema = z.object({
  27. username: z.string().min(3, '用户名至少3个字符'),
  28. nickname: z.string().optional(),
  29. email: z.string().email('请输入有效的邮箱地址').optional().or(z.literal('')),
  30. phone: z.string().regex(/^1[3-9]\d{9}$/, '请输入有效的手机号').optional().or(z.literal('')),
  31. name: z.string().optional(),
  32. password: z.string().min(6, '密码至少6个字符').optional(),
  33. isDisabled: z.boolean().default(false),
  34. });
  35. type UserFormData = z.infer<typeof userFormSchema>;
  36. export const UsersPage = () => {
  37. const [searchParams, setSearchParams] = useState({
  38. page: 1,
  39. limit: 10,
  40. search: ''
  41. });
  42. const [isModalOpen, setIsModalOpen] = useState(false);
  43. const [editingUser, setEditingUser] = useState<any>(null);
  44. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  45. const [userToDelete, setUserToDelete] = useState<number | null>(null);
  46. const form = useForm<UserFormData>({
  47. resolver: zodResolver(userFormSchema),
  48. defaultValues: {
  49. username: '',
  50. nickname: '',
  51. email: '',
  52. phone: '',
  53. name: '',
  54. password: '',
  55. isDisabled: false,
  56. },
  57. });
  58. const { data: usersData, isLoading, refetch } = useQuery({
  59. queryKey: ['users', searchParams],
  60. queryFn: async () => {
  61. const res = await userClient.$get({
  62. query: {
  63. page: searchParams.page,
  64. pageSize: searchParams.limit,
  65. keyword: searchParams.search
  66. }
  67. });
  68. if (res.status !== 200) {
  69. throw new Error('获取用户列表失败');
  70. }
  71. return await res.json();
  72. }
  73. });
  74. const users = usersData?.data || [];
  75. const totalCount = usersData?.pagination?.total || 0;
  76. // 处理搜索
  77. const handleSearch = (e: React.FormEvent) => {
  78. e.preventDefault();
  79. setSearchParams(prev => ({ ...prev, page: 1 }));
  80. };
  81. // 处理分页
  82. const handlePageChange = (page: number, limit: number) => {
  83. setSearchParams(prev => ({ ...prev, page, limit }));
  84. };
  85. // 打开创建用户对话框
  86. const handleCreateUser = () => {
  87. setEditingUser(null);
  88. form.reset({
  89. username: '',
  90. nickname: '',
  91. email: '',
  92. phone: '',
  93. name: '',
  94. password: '',
  95. isDisabled: false,
  96. });
  97. setIsModalOpen(true);
  98. };
  99. // 打开编辑用户对话框
  100. const handleEditUser = (user: any) => {
  101. setEditingUser(user);
  102. form.reset({
  103. username: user.username,
  104. nickname: user.nickname || '',
  105. email: user.email || '',
  106. phone: user.phone || '',
  107. name: user.name || '',
  108. isDisabled: user.isDisabled === 1,
  109. });
  110. setIsModalOpen(true);
  111. };
  112. // 处理表单提交
  113. const handleSubmit = async (data: UserFormData) => {
  114. try {
  115. if (editingUser) {
  116. // 编辑用户
  117. const res = await userClient[':id']['$put']({
  118. param: { id: editingUser.id },
  119. json: {
  120. ...data,
  121. isDisabled: data.isDisabled ? 1 : 0,
  122. } as UpdateUserRequest
  123. });
  124. if (res.status !== 200) {
  125. throw new Error('更新用户失败');
  126. }
  127. toast.success('用户更新成功');
  128. } else {
  129. // 创建用户
  130. const res = await userClient.$post({
  131. json: {
  132. ...data,
  133. isDisabled: data.isDisabled ? 1 : 0,
  134. } as CreateUserRequest
  135. });
  136. if (res.status !== 201) {
  137. throw new Error('创建用户失败');
  138. }
  139. toast.success('用户创建成功');
  140. }
  141. setIsModalOpen(false);
  142. refetch();
  143. } catch (error) {
  144. console.error('操作失败:', error);
  145. toast.error('操作失败,请重试');
  146. }
  147. };
  148. // 处理删除用户
  149. const handleDeleteUser = (id: number) => {
  150. setUserToDelete(id);
  151. setDeleteDialogOpen(true);
  152. };
  153. const confirmDelete = async () => {
  154. if (!userToDelete) return;
  155. try {
  156. const res = await userClient[':id']['$delete']({
  157. param: { id: userToDelete }
  158. });
  159. if (res.status !== 204) {
  160. throw new Error('删除用户失败');
  161. }
  162. toast.success('用户删除成功');
  163. refetch();
  164. } catch (error) {
  165. console.error('删除用户失败:', error);
  166. toast.error('删除失败,请重试');
  167. } finally {
  168. setDeleteDialogOpen(false);
  169. setUserToDelete(null);
  170. }
  171. };
  172. // 渲染加载骨架
  173. if (isLoading) {
  174. return (
  175. <div className="space-y-4">
  176. <div className="flex justify-between items-center">
  177. <h1 className="text-2xl font-bold">用户管理</h1>
  178. <Button disabled>
  179. <Plus className="mr-2 h-4 w-4" />
  180. 创建用户
  181. </Button>
  182. </div>
  183. <Card>
  184. <CardHeader>
  185. <Skeleton className="h-6 w-1/4" />
  186. </CardHeader>
  187. <CardContent>
  188. <div className="space-y-2">
  189. <Skeleton className="h-4 w-full" />
  190. <Skeleton className="h-4 w-full" />
  191. <Skeleton className="h-4 w-full" />
  192. </div>
  193. </CardContent>
  194. </Card>
  195. </div>
  196. );
  197. }
  198. return (
  199. <div className="space-y-4">
  200. <div className="flex justify-between items-center">
  201. <h1 className="text-2xl font-bold">用户管理</h1>
  202. <Button onClick={handleCreateUser}>
  203. <Plus className="mr-2 h-4 w-4" />
  204. 创建用户
  205. </Button>
  206. </div>
  207. <Card>
  208. <CardHeader>
  209. <CardTitle>用户列表</CardTitle>
  210. <CardDescription>
  211. 管理系统中的所有用户,共 {totalCount} 位用户
  212. </CardDescription>
  213. </CardHeader>
  214. <CardContent>
  215. <div className="mb-4">
  216. <form onSubmit={handleSearch} className="flex gap-2">
  217. <div className="relative flex-1 max-w-sm">
  218. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  219. <Input
  220. placeholder="搜索用户名、昵称或邮箱..."
  221. value={searchParams.search}
  222. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  223. className="pl-8"
  224. />
  225. </div>
  226. <Button type="submit" variant="outline">
  227. 搜索
  228. </Button>
  229. </form>
  230. </div>
  231. <div className="rounded-md border">
  232. <Table>
  233. <TableHeader>
  234. <TableRow>
  235. <TableHead>用户名</TableHead>
  236. <TableHead>昵称</TableHead>
  237. <TableHead>邮箱</TableHead>
  238. <TableHead>真实姓名</TableHead>
  239. <TableHead>角色</TableHead>
  240. <TableHead>状态</TableHead>
  241. <TableHead>创建时间</TableHead>
  242. <TableHead className="text-right">操作</TableHead>
  243. </TableRow>
  244. </TableHeader>
  245. <TableBody>
  246. {users.map((user) => (
  247. <TableRow key={user.id}>
  248. <TableCell className="font-medium">{user.username}</TableCell>
  249. <TableCell>{user.nickname || '-'}</TableCell>
  250. <TableCell>{user.email || '-'}</TableCell>
  251. <TableCell>{user.name || '-'}</TableCell>
  252. <TableCell>
  253. <Badge
  254. variant={user.role === 'admin' ? 'destructive' : 'default'}
  255. className="capitalize"
  256. >
  257. {user.role === 'admin' ? '管理员' : '普通用户'}
  258. </Badge>
  259. </TableCell>
  260. <TableCell>
  261. <Badge
  262. variant={user.isDisabled === 1 ? 'secondary' : 'default'}
  263. >
  264. {user.isDisabled === 1 ? '禁用' : '启用'}
  265. </Badge>
  266. </TableCell>
  267. <TableCell>
  268. {format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm')}
  269. </TableCell>
  270. <TableCell className="text-right">
  271. <div className="flex justify-end gap-2">
  272. <Button
  273. variant="ghost"
  274. size="icon"
  275. onClick={() => handleEditUser(user)}
  276. >
  277. <Edit className="h-4 w-4" />
  278. </Button>
  279. <Button
  280. variant="ghost"
  281. size="icon"
  282. onClick={() => handleDeleteUser(user.id)}
  283. >
  284. <Trash2 className="h-4 w-4" />
  285. </Button>
  286. </div>
  287. </TableCell>
  288. </TableRow>
  289. ))}
  290. </TableBody>
  291. </Table>
  292. </div>
  293. <div className="flex justify-between items-center mt-4">
  294. <div className="text-sm text-muted-foreground">
  295. 第 {searchParams.page} 页,共 {Math.ceil(totalCount / searchParams.limit)} 页
  296. </div>
  297. <div className="flex gap-2">
  298. <Button
  299. variant="outline"
  300. size="sm"
  301. disabled={searchParams.page <= 1}
  302. onClick={() => handlePageChange(searchParams.page - 1, searchParams.limit)}
  303. >
  304. 上一页
  305. </Button>
  306. <Button
  307. variant="outline"
  308. size="sm"
  309. disabled={searchParams.page >= Math.ceil(totalCount / searchParams.limit)}
  310. onClick={() => handlePageChange(searchParams.page + 1, searchParams.limit)}
  311. >
  312. 下一页
  313. </Button>
  314. </div>
  315. </div>
  316. </CardContent>
  317. </Card>
  318. {/* 创建/编辑用户对话框 */}
  319. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  320. <DialogContent className="sm:max-w-[500px]">
  321. <DialogHeader>
  322. <DialogTitle>
  323. {editingUser ? '编辑用户' : '创建用户'}
  324. </DialogTitle>
  325. <DialogDescription>
  326. {editingUser ? '编辑现有用户信息' : '创建一个新的用户账户'}
  327. </DialogDescription>
  328. </DialogHeader>
  329. <Form {...form}>
  330. <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
  331. <FormField
  332. control={form.control}
  333. name="username"
  334. render={({ field }) => (
  335. <FormItem>
  336. <FormLabel>用户名</FormLabel>
  337. <FormControl>
  338. <Input placeholder="请输入用户名" {...field} />
  339. </FormControl>
  340. <FormMessage />
  341. </FormItem>
  342. )}
  343. />
  344. <FormField
  345. control={form.control}
  346. name="nickname"
  347. render={({ field }) => (
  348. <FormItem>
  349. <FormLabel>昵称</FormLabel>
  350. <FormControl>
  351. <Input placeholder="请输入昵称" {...field} />
  352. </FormControl>
  353. <FormMessage />
  354. </FormItem>
  355. )}
  356. />
  357. <FormField
  358. control={form.control}
  359. name="email"
  360. render={({ field }) => (
  361. <FormItem>
  362. <FormLabel>邮箱</FormLabel>
  363. <FormControl>
  364. <Input type="email" placeholder="请输入邮箱" {...field} />
  365. </FormControl>
  366. <FormMessage />
  367. </FormItem>
  368. )}
  369. />
  370. <FormField
  371. control={form.control}
  372. name="phone"
  373. render={({ field }) => (
  374. <FormItem>
  375. <FormLabel>手机号</FormLabel>
  376. <FormControl>
  377. <Input placeholder="请输入手机号" {...field} />
  378. </FormControl>
  379. <FormMessage />
  380. </FormItem>
  381. )}
  382. />
  383. <FormField
  384. control={form.control}
  385. name="name"
  386. render={({ field }) => (
  387. <FormItem>
  388. <FormLabel>真实姓名</FormLabel>
  389. <FormControl>
  390. <Input placeholder="请输入真实姓名" {...field} />
  391. </FormControl>
  392. <FormMessage />
  393. </FormItem>
  394. )}
  395. />
  396. {!editingUser && (
  397. <FormField
  398. control={form.control}
  399. name="password"
  400. render={({ field }) => (
  401. <FormItem>
  402. <FormLabel>密码</FormLabel>
  403. <FormControl>
  404. <Input type="password" placeholder="请输入密码" {...field} />
  405. </FormControl>
  406. <FormMessage />
  407. </FormItem>
  408. )}
  409. />
  410. )}
  411. <FormField
  412. control={form.control}
  413. name="isDisabled"
  414. render={({ field }) => (
  415. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  416. <div className="space-y-0.5">
  417. <FormLabel className="text-base">用户状态</FormLabel>
  418. <FormDescription>
  419. 禁用后用户将无法登录系统
  420. </FormDescription>
  421. </div>
  422. <FormControl>
  423. <Switch
  424. checked={field.value}
  425. onCheckedChange={field.onChange}
  426. />
  427. </FormControl>
  428. </FormItem>
  429. )}
  430. />
  431. <DialogFooter>
  432. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  433. 取消
  434. </Button>
  435. <Button type="submit">
  436. {editingUser ? '更新用户' : '创建用户'}
  437. </Button>
  438. </DialogFooter>
  439. </form>
  440. </Form>
  441. </DialogContent>
  442. </Dialog>
  443. {/* 删除确认对话框 */}
  444. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  445. <DialogContent>
  446. <DialogHeader>
  447. <DialogTitle>确认删除</DialogTitle>
  448. <DialogDescription>
  449. 确定要删除这个用户吗?此操作无法撤销。
  450. </DialogDescription>
  451. </DialogHeader>
  452. <DialogFooter>
  453. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  454. 取消
  455. </Button>
  456. <Button variant="destructive" onClick={confirmDelete}>
  457. 删除
  458. </Button>
  459. </DialogFooter>
  460. </DialogContent>
  461. </Dialog>
  462. </div>
  463. );
  464. };