import { Button, message } from "antd" import { AxiosResponse } from "axios" import React from "react" import { useCallback, useContext, useEffect, useState } from "react" import DragModal from "../drag-modal/DragModal" import DownloadItem from "./download-item" import './download-panel.less' interface Iprops { //该api返回一个url getFileUrl?: (params?: {}) => Promise> downloadContext: React.Context } //下载组件上下文接口 export interface DownloadState { files: DownloadFile[] visible: boolean startDownload: (file: DownloadFile[], onCloseCallbackFn?: () => void) => void onEnd: () => void } export interface DownloadFile { //如果要调用api传递文件需要前四个变量不为空 如果直接通过url传递文件则需要后三项不为空 objectName?: string bucketName?: string filename: string suffix: string url?: string } export const useDownloadService = () => { const [files, setFiles] = useState(null); const [visible, setVisible] = useState(false); const [onCloseCallbackFn, setOnCloseCallbackFn] = useState<() => void>(); const startDownload = useCallback((dfile: DownloadFile[], onCloseCallbackFn) => { setFiles([...dfile]) setOnCloseCallbackFn(onCloseCallbackFn); }, []) const onEnd = useCallback(() => { setVisible(false) if (!!onCloseCallbackFn) { onCloseCallbackFn(); } }, []) useEffect(() => { if (files != null) { setVisible(true); } }, [files]) return { files, visible, startDownload, onEnd, } as DownloadState } export default function DownloadPanel(props: Iprops) { const downloadContext = useContext(props.downloadContext); const [stopSignal, setStopSignal] = useState(false); const [uploadCounter, setUploadCounter] = useState(0); useEffect(() => { if (downloadContext.visible) { setStopSignal(false) let files = downloadContext.files; if (files == null || files.length === 0) { message.warning('没有要下载的文件,下载被取消'); onClose(); return; } } }, [downloadContext.visible]) useEffect(() => { if (uploadCounter && uploadCounter === downloadContext.files?.length) { onClose(500); } }, [uploadCounter]) const stop = () => { setStopSignal(true) onClose(0); } const onClose = (time = 1000) => { setTimeout(() => { downloadContext.onEnd(); setUploadCounter(0); setStopSignal(false); }, time) } return (
{downloadContext.files?.map((item, idx) => ( setUploadCounter(pre => pre + 1)} /> ))}
) } //如果需要默认值可取消下面注释 DownloadPanel.defaultProps = { // downloadContext: DownloadContext, // getFileUrl: getFileUrl }