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