Files.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. import React, { useState } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { Button } from '@/client/components/ui/button';
  4. import { Input } from '@/client/components/ui/input';
  5. import { Card, CardContent, CardHeader, CardTitle } from '@/client/components/ui/card';
  6. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
  7. import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
  8. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
  9. import { Badge } from '@/client/components/ui/badge';
  10. import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/client/components/ui/alert-dialog';
  11. import { useForm } from 'react-hook-form';
  12. import { zodResolver } from '@hookform/resolvers/zod';
  13. import { toast } from 'sonner';
  14. import { Eye, Download, Edit, Trash2, Search, FileText } from 'lucide-react';
  15. import { fileClient } from '@/client/api';
  16. import type { InferResponseType, InferRequestType } from 'hono/client';
  17. import dayjs from 'dayjs';
  18. import MinioUploader from '@/client/admin-shadcn/components/MinioUploader';
  19. import { UpdateFileDto } from '@/server/modules/files/file.schema';
  20. import * as z from 'zod';
  21. // 定义类型
  22. type FileItem = InferResponseType<typeof fileClient.$get, 200>['data'][0];
  23. type FileListResponse = InferResponseType<typeof fileClient.$get, 200>;
  24. type UpdateFileRequest = InferRequestType<typeof fileClient[':id']['$put']>['json'];
  25. type FileFormData = z.infer<typeof UpdateFileDto>;
  26. export const FilesPage: React.FC = () => {
  27. const [isModalOpen, setIsModalOpen] = useState(false);
  28. const [editingFile, setEditingFile] = useState<FileItem | null>(null);
  29. const [searchText, setSearchText] = useState('');
  30. const [pagination, setPagination] = useState({
  31. current: 1,
  32. pageSize: 10,
  33. total: 0,
  34. });
  35. const [deleteFileId, setDeleteFileId] = useState<number | null>(null);
  36. const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  37. const queryClient = useQueryClient();
  38. // 表单初始化
  39. const form = useForm<FileFormData>({
  40. resolver: zodResolver(UpdateFileDto),
  41. defaultValues: {
  42. name: '',
  43. description: '',
  44. },
  45. });
  46. // 获取文件列表数据
  47. const fetchFiles = async ({ page, pageSize }: { page: number; pageSize: number }): Promise<FileListResponse> => {
  48. const response = await fileClient.$get({ query: { page, pageSize, keyword: searchText } });
  49. if (!response.ok) throw new Error('Failed to fetch files');
  50. return await response.json() as FileListResponse;
  51. };
  52. const { data, isLoading, error } = useQuery({
  53. queryKey: ['files', pagination.current, pagination.pageSize, searchText],
  54. queryFn: () => fetchFiles({ page: pagination.current, pageSize: pagination.pageSize }),
  55. });
  56. // 更新文件记录
  57. const updateFile = useMutation({
  58. mutationFn: ({ id, data }: { id: number; data: UpdateFileRequest }) =>
  59. fileClient[':id'].$put({ param: { id: id.toString() }, json: data }),
  60. onSuccess: () => {
  61. toast.success('文件记录更新成功');
  62. queryClient.invalidateQueries({ queryKey: ['files'] });
  63. setIsModalOpen(false);
  64. setEditingFile(null);
  65. },
  66. onError: (error: Error) => {
  67. toast.error(`操作失败: ${error.message}`);
  68. }
  69. });
  70. // 删除文件记录
  71. const deleteFile = useMutation({
  72. mutationFn: (id: number) => fileClient[':id'].$delete({ param: { id: id.toString() } }),
  73. onSuccess: () => {
  74. toast.success('文件记录删除成功');
  75. queryClient.invalidateQueries({ queryKey: ['files'] });
  76. },
  77. onError: (error: Error) => {
  78. toast.error(`删除失败: ${error.message}`);
  79. }
  80. });
  81. // 处理文件下载
  82. const handleDownload = (record: FileItem) => {
  83. const a = document.createElement('a');
  84. a.href = record.fullUrl;
  85. a.download = record.name;
  86. document.body.appendChild(a);
  87. a.click();
  88. document.body.removeChild(a);
  89. };
  90. // 处理文件预览
  91. const handlePreview = (record: FileItem) => {
  92. if (isPreviewable(record.type)) {
  93. window.open(record.fullUrl, '_blank');
  94. } else {
  95. toast.warning('该文件类型不支持预览');
  96. }
  97. };
  98. // 检查是否为可预览的文件类型
  99. const isPreviewable = (fileType: string | null) => {
  100. if (!fileType) return false;
  101. return fileType.startsWith('image/') || fileType.startsWith('video/');
  102. };
  103. // 处理上传成功回调
  104. const handleUploadSuccess = (fileKey: string, fileUrl: string, file: File) => {
  105. toast.success('文件上传成功');
  106. queryClient.invalidateQueries({ queryKey: ['files'] });
  107. };
  108. // 处理上传失败回调
  109. const handleUploadError = (error: Error, file: File) => {
  110. toast.error(`上传失败: ${error instanceof Error ? error.message : '未知错误'}`);
  111. };
  112. // 显示编辑弹窗
  113. const showEditModal = (record: FileItem) => {
  114. setEditingFile(record);
  115. setIsModalOpen(true);
  116. form.reset({
  117. name: record.name,
  118. description: record.description || '',
  119. });
  120. };
  121. // 处理表单提交
  122. const handleFormSubmit = async (data: FileFormData) => {
  123. if (editingFile) {
  124. await updateFile.mutateAsync({
  125. id: editingFile.id,
  126. data: {
  127. name: data.name,
  128. description: data.description,
  129. }
  130. });
  131. }
  132. };
  133. // 处理删除确认
  134. const handleDeleteConfirm = () => {
  135. if (deleteFileId) {
  136. deleteFile.mutate(deleteFileId);
  137. setIsDeleteDialogOpen(false);
  138. setDeleteFileId(null);
  139. }
  140. };
  141. const handleSearch = () => {
  142. setPagination({ ...pagination, current: 1 });
  143. };
  144. // 格式化文件大小
  145. const formatFileSize = (bytes: number | null) => {
  146. if (!bytes || bytes === 0) return '0 Bytes';
  147. const k = 1024;
  148. const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  149. const i = Math.floor(Math.log(bytes) / Math.log(k));
  150. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  151. };
  152. // 分页数据
  153. const tablePagination = data?.pagination || pagination;
  154. if (error) {
  155. return (
  156. <div className="p-6">
  157. <Card>
  158. <CardContent className="text-center py-8">
  159. <FileText className="h-12 w-12 mx-auto text-gray-400 mb-4" />
  160. <p className="text-gray-600">获取文件列表失败</p>
  161. </CardContent>
  162. </Card>
  163. </div>
  164. );
  165. }
  166. return (
  167. <div className="p-6 space-y-6">
  168. <div className="flex justify-between items-center">
  169. <h1 className="text-3xl font-bold">文件管理</h1>
  170. </div>
  171. {/* MinioUploader 文件上传组件 */}
  172. <MinioUploader
  173. uploadPath="/files"
  174. maxSize={500}
  175. multiple={false}
  176. onUploadSuccess={handleUploadSuccess}
  177. onUploadError={handleUploadError}
  178. buttonText="点击或拖拽上传文件"
  179. tipText="支持单文件上传,单个文件大小不超过500MB"
  180. size="minimal"
  181. />
  182. <Card>
  183. <CardHeader>
  184. <CardTitle>文件列表</CardTitle>
  185. </CardHeader>
  186. <CardContent>
  187. <div className="mb-4 flex gap-4">
  188. <div className="flex-1">
  189. <Input
  190. placeholder="搜索文件名称或类型"
  191. value={searchText}
  192. onChange={(e) => setSearchText(e.target.value)}
  193. onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
  194. className="max-w-sm"
  195. />
  196. </div>
  197. <Button onClick={handleSearch}>
  198. <Search className="h-4 w-4 mr-2" />
  199. 搜索
  200. </Button>
  201. </div>
  202. <div className="overflow-x-auto">
  203. <Table>
  204. <TableHeader>
  205. <TableRow>
  206. <TableHead className="w-16">ID</TableHead>
  207. <TableHead>文件名称</TableHead>
  208. <TableHead>文件类型</TableHead>
  209. <TableHead>文件大小</TableHead>
  210. <TableHead>上传时间</TableHead>
  211. <TableHead>上传用户</TableHead>
  212. <TableHead className="text-right">操作</TableHead>
  213. </TableRow>
  214. </TableHeader>
  215. <TableBody>
  216. {isLoading ? (
  217. <TableRow>
  218. <TableCell colSpan={7} className="text-center">
  219. <div className="flex justify-center items-center py-8">
  220. <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
  221. </div>
  222. </TableCell>
  223. </TableRow>
  224. ) : data?.data?.length === 0 ? (
  225. <TableRow>
  226. <TableCell colSpan={7} className="text-center py-8">
  227. <FileText className="h-12 w-12 mx-auto text-gray-400 mb-4" />
  228. <p className="text-gray-600">暂无文件</p>
  229. </TableCell>
  230. </TableRow>
  231. ) : (
  232. data?.data?.map((file) => (
  233. <TableRow key={file.id}>
  234. <TableCell className="font-medium">{file.id}</TableCell>
  235. <TableCell>
  236. <div className="max-w-xs truncate" title={file.name}>
  237. {file.name}
  238. </div>
  239. </TableCell>
  240. <TableCell>
  241. <Badge variant="secondary">{file.type}</Badge>
  242. </TableCell>
  243. <TableCell>{formatFileSize(file.size)}</TableCell>
  244. <TableCell>
  245. {file.uploadTime ? dayjs(file.uploadTime).format('YYYY-MM-DD HH:mm:ss') : '-'}
  246. </TableCell>
  247. <TableCell>
  248. {file.uploadUser ? (file.uploadUser.nickname || file.uploadUser.username) : '-'}
  249. </TableCell>
  250. <TableCell className="text-right">
  251. <div className="flex justify-end gap-2">
  252. <Button
  253. variant="ghost"
  254. size="sm"
  255. onClick={() => handlePreview(file)}
  256. disabled={!isPreviewable(file.type)}
  257. title={isPreviewable(file.type) ? '预览文件' : '该文件类型不支持预览'}
  258. >
  259. <Eye className="h-4 w-4" />
  260. </Button>
  261. <Button
  262. variant="ghost"
  263. size="sm"
  264. onClick={() => handleDownload(file)}
  265. title="下载文件"
  266. >
  267. <Download className="h-4 w-4" />
  268. </Button>
  269. <Button
  270. variant="ghost"
  271. size="sm"
  272. onClick={() => showEditModal(file)}
  273. title="编辑文件信息"
  274. >
  275. <Edit className="h-4 w-4" />
  276. </Button>
  277. <Button
  278. variant="ghost"
  279. size="sm"
  280. onClick={() => {
  281. setDeleteFileId(file.id);
  282. setIsDeleteDialogOpen(true);
  283. }}
  284. className="text-red-600 hover:text-red-700"
  285. title="删除文件"
  286. >
  287. <Trash2 className="h-4 w-4" />
  288. </Button>
  289. </div>
  290. </TableCell>
  291. </TableRow>
  292. ))
  293. )}
  294. </TableBody>
  295. </Table>
  296. </div>
  297. {/* 分页 */}
  298. {tablePagination.total > 0 && (
  299. <div className="flex justify-between items-center mt-4">
  300. <div className="text-sm text-gray-600">
  301. 显示 {((tablePagination.current - 1) * tablePagination.pageSize + 1)}-
  302. {Math.min(tablePagination.current * tablePagination.pageSize, tablePagination.total)} 条,
  303. 共 {tablePagination.total} 条
  304. </div>
  305. <div className="flex gap-2">
  306. <Button
  307. variant="outline"
  308. size="sm"
  309. disabled={tablePagination.current <= 1}
  310. onClick={() => setPagination({ ...pagination, current: tablePagination.current - 1 })}
  311. >
  312. 上一页
  313. </Button>
  314. <span className="px-3 py-1 text-sm">
  315. 第 {tablePagination.current} 页
  316. </span>
  317. <Button
  318. variant="outline"
  319. size="sm"
  320. disabled={tablePagination.current >= Math.ceil(tablePagination.total / tablePagination.pageSize)}
  321. onClick={() => setPagination({ ...pagination, current: tablePagination.current + 1 })}
  322. >
  323. 下一页
  324. </Button>
  325. </div>
  326. </div>
  327. )}
  328. </CardContent>
  329. </Card>
  330. {/* 编辑对话框 */}
  331. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  332. <DialogContent className="sm:max-w-[500px]">
  333. <DialogHeader>
  334. <DialogTitle>编辑文件信息</DialogTitle>
  335. <DialogDescription>
  336. 修改文件的基本信息
  337. </DialogDescription>
  338. </DialogHeader>
  339. <Form {...form}>
  340. <form onSubmit={form.handleSubmit(handleFormSubmit)} className="space-y-4">
  341. <FormField
  342. control={form.control}
  343. name="name"
  344. render={({ field }) => (
  345. <FormItem>
  346. <FormLabel>文件名称</FormLabel>
  347. <FormControl>
  348. <Input placeholder="请输入文件名称" {...field} />
  349. </FormControl>
  350. <FormMessage />
  351. </FormItem>
  352. )}
  353. />
  354. <FormField
  355. control={form.control}
  356. name="description"
  357. render={({ field }) => (
  358. <FormItem>
  359. <FormLabel>文件描述</FormLabel>
  360. <FormControl>
  361. <Input placeholder="请输入文件描述" {...field} />
  362. </FormControl>
  363. <FormMessage />
  364. </FormItem>
  365. )}
  366. />
  367. <DialogFooter>
  368. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  369. 取消
  370. </Button>
  371. <Button type="submit" disabled={updateFile.isPending}>
  372. {updateFile.isPending ? '保存中...' : '保存'}
  373. </Button>
  374. </DialogFooter>
  375. </form>
  376. </Form>
  377. </DialogContent>
  378. </Dialog>
  379. {/* 删除确认对话框 */}
  380. <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
  381. <AlertDialogContent>
  382. <AlertDialogHeader>
  383. <AlertDialogTitle>确认删除</AlertDialogTitle>
  384. <AlertDialogDescription>
  385. 确定要删除这个文件记录吗?此操作不可恢复。
  386. </AlertDialogDescription>
  387. </AlertDialogHeader>
  388. <AlertDialogFooter>
  389. <AlertDialogCancel>取消</AlertDialogCancel>
  390. <AlertDialogAction onClick={handleDeleteConfirm} className="bg-red-600 hover:bg-red-700">
  391. 确认删除
  392. </AlertDialogAction>
  393. </AlertDialogFooter>
  394. </AlertDialogContent>
  395. </AlertDialog>
  396. </div>
  397. );
  398. };