import { api } from '@/api/index'
import { BatchFileUploadParam, FileUploadParam, ResultDomain, TbSysFileDTO } from '@/types';

export const fileAPI = {
    baseUrl: "/file",

    /**
     * 上传文件
     * @param param 文件上传参数
     * @returns Promise<ResultDomain<SysFile>>
     */
    async uploadFile(param: FileUploadParam): Promise<ResultDomain<TbSysFileDTO>> {
        const formData = new FormData();
        formData.append('file', param.file);
        if (param.module) {
            formData.append('module', param.module);
        }
        if (param.optsn) {
            formData.append('optsn', param.optsn);
        }
        if (param.uploader) {
            formData.append('uploader', param.uploader);
        }
        const response = await api.upload<TbSysFileDTO>(`${this.baseUrl}/upload`, formData);
        return response.data;
    },

    /**
     * 批量上传文件
     * @param param 批量文件上传参数
     * @returns Promise<ResultDomain<SysFile>>
     */
    async batchUploadFiles(param: BatchFileUploadParam): Promise<ResultDomain<TbSysFileDTO>> {
        const formData = new FormData();
        param.files.forEach(file => {
            formData.append('files', file);
        });
        if (param.module) {
            formData.append('module', param.module);
        }
        if (param.optsn) {
            formData.append('optsn', param.optsn);
        }
        if (param.uploader) {
            formData.append('uploader', param.uploader);
        }
        const response = await api.upload<TbSysFileDTO>(`${this.baseUrl}/batch-upload`, formData);
        return response.data;
    },

    /**
     * 下载文件
     * @param fileId 文件ID
     * @param filename 保存的文件名（可选）
     * @returns Promise<void>
     */
    async downloadFile(fileId: string, filename?: string): Promise<void> {
        return api.download(`${this.baseUrl}/download/${fileId}`, filename);
    },
}