package com.ruoyi.common.utils.file;

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.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

public class ImageUtils {
    public static MultipartFile imageMethod(MultipartFile file) {
        //region/-------创建缩略图存放的文件夹-------/
        //获得项目根目录
        String path = System.getProperty("user.dir");
        //定义新文件夹路径
        String dirPath = path + File.separator + "imagecache";
        //根据路径生成文件夹
        File dir = new File(dirPath);
        dir.mkdirs();
        //endregion
        //定义缩略图的全路径
        String fileSuffix = "image.jpg";
        String contextPath = dirPath + File.separator + fileSuffix;
        //压缩图片
        MultipartFile newFile = null;
        try {
            //自定义宽高压缩（压缩方法很多，可以根据需求更改）
//            Thumbnails.of(file.getInputStream()).forceSize(100, 100).toFile(contextPath);
            Thumbnails.of(file.getInputStream()).scale(0.1f).toFile(contextPath);//按比例缩小
            //压缩完成后将缩略图生成MultipartFile
            FileItem fileItem = createFileItem(contextPath);
            newFile = new CommonsMultipartFile(fileItem);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //endregion
        //上面的“newFile”就是缩略图转换后的MultipartFile，就可以拿来用了
        //程序处理完后把生成的缩略图删除
        File image = new File(contextPath);
        if (image.exists()) {
            image.delete();
        }
        return newFile;
    }

    /**
     * 获取压缩后的图片,File 转为 MultipartFile
     */
    public static FileItem createFileItem(String contextPath) {
        {
            FileItemFactory factory = new DiskFileItemFactory(16, null);
            String textFieldName = "textField";
            int num = contextPath.lastIndexOf(".");
            String extFile = contextPath.substring(num);
            FileItem item = factory.createItem(textFieldName, "text/plain", true,
                    "MyFileName" + extFile);
            File newfile = new File(contextPath);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            try {
                FileInputStream fis = new FileInputStream(newfile);
                OutputStream os = item.getOutputStream();
                while ((bytesRead = fis.read(buffer, 0, 8192))
                        != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return item;
        }
    }

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

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(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();
        }
    }

    /**
     * File转为MultipartFile
     *
     * @param file
     * @return
     */
    public static MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
