import { formatDate } from "@/utils/downloadFile";
import { CloudDownloadOutlined } from "@ant-design/icons";
import { Button, message } from "antd";
import moment from "moment";
import React from 'react'
/**
 *  
 * @param api 需要再请求设置 responseType: 'blob' 返回blob数据
 * @returns 
 */
function DownloadExcel(props: { api: any, querys: any }) {
    const { api, querys } = props
    const downloadFile = (data: any, type: any, fileName: string) => {
        let blob = new Blob([data], { type: `application/${type};charset=utf-8` });
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = fileName;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
    }
    const download = () => {
        // 判断querys是否是函数，函数执行函数，否则直接赋值
        let params = typeof querys === 'function' ? querys() : querys
        if (params?.date) {
            params['startTime'] = moment(params.date[0]).format('YYYY-MM-DD')
            params['endTime'] = moment(params.date[1]).format('YYYY-MM-DD')
        } else {
            delete params['startTime']
            delete params['endTime']
        }
        delete params['date']
        api.run({ ...params, pageSize: 20, pageNum: 1 }).then((res: any) => {
            downloadFile(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
            message.success("下载成功！")
        })
    }
    return <Button type='primary' onClick={download} loading={api?.loading}><CloudDownloadOutlined />下载Excel</Button>
}
export default DownloadExcel