import { DIRNAMEENUM } from "../config/enum";
import { ERRORENUM } from "../config/errorEnum";
import { BizError } from "../util/bizError";

var formidable = require("formidable");
const path = require('path');

export async function parseFormParam(req, res, next) {
    let upType = DIRNAMEENUM.系统上传;

    var form = new formidable.IncomingForm({
        uploadDir: path.join(__dirname.substring(0,__dirname.indexOf("out")),'files', `${upType}`),
        maxFildsSize: 10*1024*1024,
        keepExtensions: true
    });

    form.parse(req, (err, fields, files)=>{
        if (err) {
            return next(err);
        } else if (!files || !Object.keys(files).length) {
            return next(new BizError(ERRORENUM.空文件失败));
        }
        else {
            req.fields = fields;
            req.files = {};

            if (!files.formData && !files.file ) return next(new BizError(ERRORENUM.文件上传失败) );
            if (files.formData) {
                req.files.formData = files.formData;
                req.files.formData.upType = upType;   
            }
            else {
                req.files.formData = files.file;
                req.files.formData.upType = upType;
            }
            if (!req.files.formData || !req.files.formData.name) {
                return next(new BizError(ERRORENUM.文件上传失败) );
            }
            console.log(req.files.formData.type);
            //获取文件扩展名
            const fileExtension = req.files.formData.name.split('.').pop().toLowerCase();
            if ( req.files.formData.type == 'image/png') {
                req.fileType = '.png';
                return next();
            } else if (req.files.formData.type == 'image/jpg' || req.files.formData.type == 'image/jpeg') {
                req.fileType = '.jpg';
                return next();
            } else if (req.files.formData.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || fileExtension == 'docx') {
                req.fileType = '.docx';
                return next();
            } else if (req.files.formData.type == "application/msword") {
                req.fileType = '.doc';
                return next();
            } else if (req.files.formData.type == "application/pdf") {
                req.fileType = '.pdf';
                return next();
            } else if (req.files.formData.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
                req.fileType = '.xlsx';
                return next();
            } else if (req.files.formData.type == "application/vnd.ms-excel"){
                req.fileType = '.xls';
                return next();
            } else {
                return next(new BizError(ERRORENUM.只能上传doc或docx或excel或png或jpg图片) )
            }
        }
    })
}




