Files.tsx 16 KB

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