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) {
    if (!req.headers) req.headers = {};

    let subPath = '';
    if (req.originalUrl.indexOf("policy") > -1) subPath = "policy";
    else subPath = "doc";

    var form = new formidable.IncomingForm({
        uploadDir:path.join(__dirname.substring(0,__dirname.indexOf("out")),'files', 'admin', subPath),
        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;
            }
            else {
                req.files.formData = files.file;
            }
            if (!req.files.formData || !req.files.formData.name) {
                return next(new BizError(ERRORENUM.文件上传失败) );
            }
            
            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") {
                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 {
                return next(new BizError(ERRORENUM.只能上传doc或docx或png或jpg图片) )
            }
        }
    })
}
