/** * 下载API返回的PDF文件 * @param {Object} apiResponse - 接口返回的数据 * @param {boolean} [showLoading=true] - 是否显示加载提示 */ import {IMAGE_BASE_URL,BASE_URL} from '@/utils/config'; export const downloadPdfFiles = (file, showLoading = true) => { return new Promise((resolve, reject) => { const filesToDownload = [{url:file.url,name:file.name}]; // 2. 收集需要下载的文件 // if (applyPdf) filesToDownload.push({ url: BASE_URL+applyPdf, name: '申请表.docx' }); // if (covenantPdf) filesToDownload.push({ url: BASE_URL+covenantPdf, name: '协议书.docx' }); if (filesToDownload.length === 0) { return reject(new Error('未找到可下载的文件')); } // 3. 显示加载提示 if (showLoading) { wx.showLoading({ title: `正在下载文件(0/${filesToDownload.length})`, mask: true }); } // 4. 逐个下载文件 const downloadedFiles = []; let completedCount = 0; const updateProgress = () => { if (showLoading) { wx.showLoading({ title: `正在下载文件(${completedCount}/${filesToDownload.length})`, mask: true }); } }; filesToDownload.forEach((file, index) => { wx.downloadFile({ url: file.url, success: (res) => { if (res.statusCode === 200) { downloadedFiles.push({ tempPath: res.tempFilePath, name: file.name, }); // 下载完成后自动打开 wx.openDocument({ filePath: res.tempFilePath, fileType: 'docx', showMenu: true,// 显示Android分享菜单 success: () => { console.log(`${file.name} 打开成功`); }, fail: (err) => { console.error(`${file.name} 打开失败:`, err); } }); } else { console.error(`${file.name} 下载失败,状态码: ${res.statusCode}`); } }, fail: (err) => { console.error(`${file.name} 下载失败:`, err); }, complete: () => { completedCount++; updateProgress(); // 全部下载完成 if (completedCount === filesToDownload.length) { if (showLoading) wx.hideLoading(); if (downloadedFiles.length > 0) { resolve({ success: true, files: downloadedFiles, message: `成功下载 ${downloadedFiles.length} 个文件` }); } else { reject(new Error('所有文件下载失败')); } } } }); }); }); };