package com.infoepoch.pms.dispatchassistant.common.utils;


import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import org.springframework.web.multipart.MultipartFile;

public class FileCheckTool {

    private static final String allowedExtensions = ".jpg,.jpeg,.gif,.png,.bmp,.tif,.tiff,.psd,.ai,.pdf,.rtf,.doc,.docx,.csv,.xls,.xlsx,.ppt,.pptx,.vsd,.vsdx,.mpp,.rp,.zip,.rar,.7z,.tar,.tgz,.gz,.iso,.fla,.flv,.swf,.mp4";

    public static String checkFileExtensionAndSize(MultipartFile file) {
        String resultStr = "success";
        String fullname = file.getOriginalFilename();
        String extension = "";
        int i = fullname.lastIndexOf(46);
        if (i > 0) {
            extension = "." + fullname.substring(i + 1);
        }

        if (file.isEmpty()) {
            resultStr = fullname + "上传失败，不能上传空文件。";
            throw new ValidationException(resultStr);
        } else if (".".equals(extension)) {
            resultStr = "上传失败:不允许上传此类型文件，允许上传的文件扩展名为：.jpg,.jpeg,.gif,.png,.bmp,.tif,.tiff,.psd,.ai,.pdf,.rtf,.doc,.docx,.csv,.xls,.xlsx,.ppt,.pptx,.vsd,.vsdx,.mpp,.rp,.zip,.rar,.7z,.tar,.tgz,.gz,.iso,.fla,.flv,.swf,.mp4";
            throw new ValidationException(resultStr);
        } else if (!".jpg,.jpeg,.gif,.png,.bmp,.tif,.tiff,.psd,.ai,.pdf,.rtf,.doc,.docx,.csv,.xls,.xlsx,.ppt,.pptx,.vsd,.vsdx,.mpp,.rp,.zip,.rar,.7z,.tar,.tgz,.gz,.iso,.fla,.flv,.swf,.mp4".contains(extension.toLowerCase())) {
            resultStr = "上传失败:不允许上传此类型文件，允许上传的文件扩展名为：.jpg,.jpeg,.gif,.png,.bmp,.tif,.tiff,.psd,.ai,.pdf,.rtf,.doc,.docx,.csv,.xls,.xlsx,.ppt,.pptx,.vsd,.vsdx,.mpp,.rp,.zip,.rar,.7z,.tar,.tgz,.gz,.iso,.fla,.flv,.swf,.mp4";
            throw new ValidationException(resultStr);
        } else {
            long maxSize = 1073741824L;
            if (file.getSize() > maxSize) {
                resultStr = "上传失败，文件大小不能超过" + autoUnitSize(maxSize) + "。";
                throw new ValidationException(resultStr);
            } else {
                return resultStr;
            }
        }
    }

    private static String autoUnitSize(long size) {
        if (size < 1024L) {
            return size + "B";
        } else if (size < 1048576L) {
            return size / 1024L + "KB";
        } else {
            return size < 1073741824L ? size / 1048576L + "MB" : size / 1073741824L + "GB";
        }
    }

}
