Users.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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.email('请输入有效的邮箱地址').optional().or(z.literal('')).transform(val => val || null),
  30. phone: z.string().regex(/^1[3-9]\d{9}$/, '请输入有效的手机号').optional().or(z.literal('')).transform(val => val || null),
  31. name: z.string().optional().or(z.literal('')).transform(val => val || null),
  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. const submitData = {
  116. ...data,
  117. isDisabled: data.isDisabled ? 1 : 0,
  118. };
  119. if (editingUser) {
  120. // 编辑用户
  121. const res = await userClient[':id']['$put']({
  122. param: { id: editingUser.id },
  123. json: submitData as UpdateUserRequest
  124. });
  125. if (res.status !== 200) {
  126. throw new Error('更新用户失败');
  127. }
  128. toast.success('用户更新成功');
  129. } else {
  130. // 创建用户
  131. const res = await userClient.$post({
  132. json: submitData as CreateUserRequest
  133. });
  134. if (res.status !== 201) {
  135. throw new Error('创建用户失败');
  136. }
  137. toast.success('用户创建成功');
  138. }
  139. setIsModalOpen(false);
  140. refetch();
  141. } catch (error) {
  142. console.error('操作失败:', error);
  143. toast.error('操作失败,请重试');
  144. }
  145. };
  146. // 处理删除用户
  147. const handleDeleteUser = (id: number) => {
  148. setUserToDelete(id);
  149. setDeleteDialogOpen(true);
  150. };
  151. const confirmDelete = async () => {
  152. if (!userToDelete) return;
  153. try {
  154. const res = await userClient[':id']['$delete']({
  155. param: { id: userToDelete }
  156. });
  157. if (res.status !== 204) {
  158. throw new Error('删除用户失败');
  159. }
  160. toast.success('用户删除成功');
  161. refetch();
  162. } catch (error) {
  163. console.error('删除用户失败:', error);
  164. toast.error('删除失败,请重试');
  165. } finally {
  166. setDeleteDialogOpen(false);
  167. setUserToDelete(null);
  168. }
  169. };
  170. // 渲染加载骨架
  171. if (isLoading) {
  172. return (
  173. <div className="space-y-4">
  174. <div className="flex justify-between items-center">
  175. <h1 className="text-2xl font-bold">用户管理</h1>
  176. <Button disabled>
  177. <Plus className="mr-2 h-4 w-4" />
  178. 创建用户
  179. </Button>
  180. </div>
  181. <Card>
  182. <CardHeader>
  183. <Skeleton className="h-6 w-1/4" />
  184. </CardHeader>
  185. <CardContent>
  186. <div className="space-y-2">
  187. <Skeleton className="h-4 w-full" />
  188. <Skeleton className="h-4 w-full" />
  189. <Skeleton className="h-4 w-full" />
  190. </div>
  191. </CardContent>
  192. </Card>
  193. </div>
  194. );
  195. }
  196. return (
  197. <div className="space-y-4">
  198. <div className="flex justify-between items-center">
  199. <h1 className="text-2xl font-bold">用户管理</h1>
  200. <Button onClick={handleCreateUser}>
  201. <Plus className="mr-2 h-4 w-4" />
  202. 创建用户
  203. </Button>
  204. </div>
  205. <Card>
  206. <CardHeader>
  207. <CardTitle>用户列表</CardTitle>
  208. <CardDescription>
  209. 管理系统中的所有用户,共 {totalCount} 位用户
  210. </CardDescription>
  211. </CardHeader>
  212. <CardContent>
  213. <div className="mb-4">
  214. <form onSubmit={handleSearch} className="flex gap-2">
  215. <div className="relative flex-1 max-w-sm">
  216. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  217. <Input
  218. placeholder="搜索用户名、昵称或邮箱..."
  219. value={searchParams.search}
  220. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  221. className="pl-8"
  222. />
  223. </div>
  224. <Button type="submit" variant="outline">
  225. 搜索
  226. </Button>
  227. </form>
  228. </div>
  229. <div className="rounded-md border">
  230. <Table>
  231. <TableHeader>
  232. <TableRow>
  233. <TableHead>用户名</TableHead>
  234. <TableHead>昵称</TableHead>
  235. <TableHead>邮箱</TableHead>
  236. <TableHead>真实姓名</TableHead>
  237. <TableHead>角色</TableHead>
  238. <TableHead>状态</TableHead>
  239. <TableHead>创建时间</TableHead>
  240. <TableHead className="text-right">操作</TableHead>
  241. </TableRow>
  242. </TableHeader>
  243. <TableBody>
  244. {users.map((user) => (
  245. <TableRow key={user.id}>
  246. <TableCell className="font-medium">{user.username}</TableCell>
  247. <TableCell>{user.nickname || '-'}</TableCell>
  248. <TableCell>{user.email || '-'}</TableCell>
  249. <TableCell>{user.name || '-'}</TableCell>
  250. <TableCell>
  251. <Badge
  252. variant={user.role === 'admin' ? 'destructive' : 'default'}
  253. className="capitalize"
  254. >
  255. {user.role === 'admin' ? '管理员' : '普通用户'}
  256. </Badge>
  257. </TableCell>
  258. <TableCell>
  259. <Badge
  260. variant={user.isDisabled === 1 ? 'secondary' : 'default'}
  261. >
  262. {user.isDisabled === 1 ? '禁用' : '启用'}
  263. </Badge>
  264. </TableCell>
  265. <TableCell>
  266. {format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm')}
  267. </TableCell>
  268. <TableCell className="text-right">
  269. <div className="flex justify-end gap-2">
  270. <Button
  271. variant="ghost"
  272. size="icon"
  273. onClick={() => handleEditUser(user)}
  274. >
  275. <Edit className="h-4 w-4" />
  276. </Button>
  277. <Button
  278. variant="ghost"
  279. size="icon"
  280. onClick={() => handleDeleteUser(user.id)}
  281. >
  282. <Trash2 className="h-4 w-4" />
  283. </Button>
  284. </div>
  285. </TableCell>
  286. </TableRow>
  287. ))}
  288. </TableBody>
  289. </Table>
  290. </div>
  291. <div className="flex justify-between items-center mt-4">
  292. <div className="text-sm text-muted-foreground">
  293. 第 {searchParams.page} 页,共 {Math.ceil(totalCount / searchParams.limit)} 页
  294. </div>
  295. <div className="flex gap-2">
  296. <Button
  297. variant="outline"
  298. size="sm"
  299. disabled={searchParams.page <= 1}
  300. onClick={() => handlePageChange(searchParams.page - 1, searchParams.limit)}
  301. >
  302. 上一页
  303. </Button>
  304. <Button
  305. variant="outline"
  306. size="sm"
  307. disabled={searchParams.page >= Math.ceil(totalCount / searchParams.limit)}
  308. onClick={() => handlePageChange(searchParams.page + 1, searchParams.limit)}
  309. >
  310. 下一页
  311. </Button>
  312. </div>
  313. </div>
  314. </CardContent>
  315. </Card>
  316. {/* 创建/编辑用户对话框 */}
  317. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  318. <DialogContent className="sm:max-w-[500px]">
  319. <DialogHeader>
  320. <DialogTitle>
  321. {editingUser ? '编辑用户' : '创建用户'}
  322. </DialogTitle>
  323. <DialogDescription>
  324. {editingUser ? '编辑现有用户信息' : '创建一个新的用户账户'}
  325. </DialogDescription>
  326. </DialogHeader>
  327. <Form {...form}>
  328. <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
  329. <FormField
  330. control={form.control}
  331. name="username"
  332. render={({ field }) => (
  333. <FormItem>
  334. <FormLabel>用户名</FormLabel>
  335. <FormControl>
  336. <Input placeholder="请输入用户名" {...field} />
  337. </FormControl>
  338. <FormMessage />
  339. </FormItem>
  340. )}
  341. />
  342. <FormField
  343. control={form.control}
  344. name="nickname"
  345. render={({ field }) => (
  346. <FormItem>
  347. <FormLabel>昵称</FormLabel>
  348. <FormControl>
  349. <Input placeholder="请输入昵称" {...field} />
  350. </FormControl>
  351. <FormMessage />
  352. </FormItem>
  353. )}
  354. />
  355. <FormField
  356. control={form.control}
  357. name="email"
  358. render={({ field }) => (
  359. <FormItem>
  360. <FormLabel>邮箱</FormLabel>
  361. <FormControl>
  362. <Input type="email" placeholder="请输入邮箱" {...field} />
  363. </FormControl>
  364. <FormMessage />
  365. </FormItem>
  366. )}
  367. />
  368. <FormField
  369. control={form.control}
  370. name="phone"
  371. render={({ field }) => (
  372. <FormItem>
  373. <FormLabel>手机号</FormLabel>
  374. <FormControl>
  375. <Input placeholder="请输入手机号" {...field} />
  376. </FormControl>
  377. <FormMessage />
  378. </FormItem>
  379. )}
  380. />
  381. <FormField
  382. control={form.control}
  383. name="name"
  384. render={({ field }) => (
  385. <FormItem>
  386. <FormLabel>真实姓名</FormLabel>
  387. <FormControl>
  388. <Input placeholder="请输入真实姓名" {...field} />
  389. </FormControl>
  390. <FormMessage />
  391. </FormItem>
  392. )}
  393. />
  394. {!editingUser && (
  395. <FormField
  396. control={form.control}
  397. name="password"
  398. render={({ field }) => (
  399. <FormItem>
  400. <FormLabel>密码</FormLabel>
  401. <FormControl>
  402. <Input type="password" placeholder="请输入密码" {...field} />
  403. </FormControl>
  404. <FormMessage />
  405. </FormItem>
  406. )}
  407. />
  408. )}
  409. <FormField
  410. control={form.control}
  411. name="isDisabled"
  412. render={({ field }) => (
  413. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  414. <div className="space-y-0.5">
  415. <FormLabel className="text-base">用户状态</FormLabel>
  416. <FormDescription>
  417. 禁用后用户将无法登录系统
  418. </FormDescription>
  419. </div>
  420. <FormControl>
  421. <Switch
  422. checked={field.value}
  423. onCheckedChange={field.onChange}
  424. />
  425. </FormControl>
  426. </FormItem>
  427. )}
  428. />
  429. <DialogFooter>
  430. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  431. 取消
  432. </Button>
  433. <Button type="submit">
  434. {editingUser ? '更新用户' : '创建用户'}
  435. </Button>
  436. </DialogFooter>
  437. </form>
  438. </Form>
  439. </DialogContent>
  440. </Dialog>
  441. {/* 删除确认对话框 */}
  442. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  443. <DialogContent>
  444. <DialogHeader>
  445. <DialogTitle>确认删除</DialogTitle>
  446. <DialogDescription>
  447. 确定要删除这个用户吗?此操作无法撤销。
  448. </DialogDescription>
  449. </DialogHeader>
  450. <DialogFooter>
  451. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  452. 取消
  453. </Button>
  454. <Button variant="destructive" onClick={confirmDelete}>
  455. 删除
  456. </Button>
  457. </DialogFooter>
  458. </DialogContent>
  459. </Dialog>
  460. </div>
  461. );
  462. };