Users.tsx 17 KB

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