'use strict'; const Service = require('egg').Service; const xlsx = require('xlsx'); const fs = require('fs'); class HandleService extends Service { constructor(ctx) { super(ctx); this.progressModel = this.ctx.model.Progress; this.config = this.app.config; } // 导入处理 async import({ type, taskId }) { const files = this.ctx.request.files[0]; const workbook = xlsx.readFile(files.filepath); const name = workbook.SheetNames[0]; const sheet = workbook.Sheets[name]; const data = xlsx.utils.sheet_to_json(sheet); const total = data.length; let progress = 0; for (let i = 0; i < data.length; i++) { // 此处根据类型调用不同的数据存储服务 const item = data[i]; const fun = this.ctx.service.imperts[`import${type}`]; await fun({ item, _this: this }); // 此处调用进度存储 progress = (i + 1) / total * 100; await this.ctx.service.progress.updateProgress({ taskId, progress, type }); } } // 导出处理 async export({ type, taskId, filters, ids, fileType }) { // 创建过滤条件 const filter = {}; let res; // 默认总数 let total = (ids && ids.length) || 0; // 如果条件存在 if (filters) { filter.$or = []; for (const i in filters) { const data = `{ "${i}": { "$regex": "${filters[i]}" } }`; filter.$or.push(JSON.parse(data)); } } // 获取查询总数函数 const totalfun = this.ctx.service.total[`total${type}`]; // 赋值总数 total = await totalfun({ ...filter, _this: this }); console.log(total); // 获取查询函数 const fun = this.ctx.service.exports[`exports${type}`]; // 计算页数 const pages = Math.ceil(total / 10); console.log(pages); // 此处调用创建文件 const file = await this.establishFile({ taskId, type, fileType }); if (file === 'success') { for (let i = 0; i < pages; i++) { // 进度 const progress = (i + 1) / pages * 100; console.log(taskId, ':', progress); // 更新进度 await this.ctx.service.progress.updateProgress({ taskId, progress, type }); // 调用查询数据函数 res = await fun({ skip: i, filter, ids, _this: this }); // 此处调用写入文件 if (res.length <= 0) return; await this.insertFile({ type, data: res, taskId, fileType }); } } } // 创建文件 async establishFile({ taskId, type, fileType }) { const fun = this.ctx.service[fileType].establish; return await fun({ fileName: taskId, type, _this: this }); } // 持续写入文件 async insertFile({ type, data, taskId, fileType }) { const fun = this.ctx.service[fileType].insertFile; await fun({ type, fileName: taskId, data, _this: this }); } // 模板下载 async template({ type, fileType, fileName }) { const fun = this.ctx.service.template[fileType]; const url = await fun({ fileName, type, _this: this }); const postfix = url.split('.')[1]; this.ctx.attachment(`${fileName}.${postfix}`); return fs.createReadStream(url); } // 文件下载 async exportsDownload({ taskId, fileName }) { const url = `${this.app.config.exportsPath}/${taskId}.xlsx`; const postfix = url.split('.')[1]; this.ctx.attachment(`${fileName}.${postfix}`); return fs.createReadStream(url); } } module.exports = HandleService;