Files.tsx 17 KB

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