Files.tsx 17 KB

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