package com.dayou.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.dayou.exception.file.FileNameLengthLimitExceededException;
import com.dayou.exception.file.FileSizeLimitExceededException;
import com.dayou.exception.file.InvalidExtensionException;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.Objects;

/**
 * 文件上传工具类
 *
 * @author xysy
 */
@Slf4j
public class FileUploadUtils {
    // 图片默认缩放比率
    private static final double DEFAULT_SCALE = 0.7d;
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    private static int counter = 0;

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws FileSizeLimitExceededException,
            FileNameLengthLimitExceededException,
            InvalidExtensionException, IOException {
        return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, null);
    }

    /**
     * @param baseDir
     * @param file
     * @param assginName 自定义文件名 包含扩展名
     * @return
     * @throws FileSizeLimitExceededException
     * @throws FileNameLengthLimitExceededException
     * @throws InvalidExtensionException
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file, String assginName) throws FileSizeLimitExceededException,
            FileNameLengthLimitExceededException,
            InvalidExtensionException, IOException {
        return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, assginName);
    }

    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension, String assignName)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        assertAllowed(file, allowedExtension);
        String fileName = extractFilename(file, assignName);
        fileName = createDateIndexFileName(fileName);
        File desc = getAbsoluteFile(baseDir, fileName);
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream()); // 通过MultipartFile得到InputStream
            // ，从而得到BufferedImage
            if (bufferedImage == null) {
                // 证明上传的文件不是图片，获取图片流失败，不进行下面的操作
                file.transferTo(desc);
            } else {
                //不能使用bufferedImage 否则会出现翻转
                Thumbnails.of(file.getInputStream())
                        .scale(FileUploadUtils.DEFAULT_SCALE)
                        .toFile(desc.getAbsolutePath());
            }
            // 省略逻辑判断
        } catch (Exception e) {
            // 省略异常操作
            log.error("图片压缩失败", e);
            file.transferTo(desc);
        }
        String pathFileName = fileName;
        return pathFileName;

    }


    public static String createDateIndexFileName(String fileName) {
        Date now = new Date();
        String year = DateUtil.format(now, "yyyy");
        String month = DateUtil.format(now, "MM");
        String day = DateUtil.format(new Date(), "dd");
//        String index =
//                File.separator + year + File.separator + month + File.separator + day + File.separator + fileName;
        //能够兼容win 和linux
        String spliter = "/";
        String index = spliter + year + spliter + month + spliter + day + spliter + fileName;
        return index;
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if ("".equals(file) || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(RandomUtil.randomString(32) + file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file, String assignName) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = Objects.nonNull(assignName) ? assignName : encodingFilename(fileName) + "-" + DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + "." + extension;
        return fileName;
    }

    public static final String generateDocName(){
        String fileName = "/reports/"+DateUtil.format(new Date(), "yyyyMMddHHmmss") + "-" + Md5Utils.hash("" + System.nanoTime() + counter++) + ".docx";
        return fileName;
    }
    /**
     * 编码文件名
     */
    public static final String extractFilename(File file) {
        String fileName = file.getName();
        String extension = getExtension(file);
        fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "-" + encodingFilename(fileName) + "." + extension;
        return fileName;
    }

    private static final String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = uploadDir.lastIndexOf("/") + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
//        String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        String pathFileName = currentDir + "/" + fileName;
        return pathFileName;
    }

    public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);
        // 高版本spring中CommonsMultipartFile会自动创建desc,如果创建会报错
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
//         if (!desc.exists())
//         {
//         desc.createNewFile();
//         }
        return desc;
    }

    public static boolean isImage(String extension) {
        String[] imageExtension = new String[]{"jpeg", "jpg", "gif", "bmp", "png"};

        for (String e : imageExtension) if (extension.toLowerCase().equals(e)) return true;

        return false;
    }

    /**
     * 编码文件名
     */
    private static final String encodingFilename(String fileName) {
        fileName = fileName.replace("_", " ");
        fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++);
        return fileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            } else {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(File file) {
        String extension = FilenameUtils.getExtension(file.getName());
        return extension;
    }

    /**
     * 获取封装得MultipartFile
     *
     * @param inputStream inputStream
     * @param fileName    fileName
     * @return MultipartFile
     */
    public static MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
        FileItem fileItem = createFileItem(inputStream, fileName);
        //CommonsMultipartFile是feign对multipartFile的封装，但是要FileItem类对象
        return new CommonsMultipartFile(fileItem);
    }


    /**
     * FileItem类对象创建
     *
     * @param inputStream inputStream
     * @param fileName    fileName
     * @return FileItem
     */
    public static FileItem createFileItem(InputStream inputStream, String fileName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "file";
        FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[10 * 1024 * 1024];
        OutputStream os = null;
        //使用输出流输出输入流的字节
        try {
            os = item.getOutputStream();
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (IOException e) {
            log.error("Stream copy exception", e);
            throw new IllegalArgumentException("文件上传失败");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error("Stream close exception", e);

                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("Stream close exception", e);
                }
            }
        }

        return item;
    }

}