package com.sqx.modules.file.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.sqx.modules.common.service.CommonInfoService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Base64;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;

/**
 * 文件上传工具类
 * 
 * @author ruoyi
 */
public class FileUploadUtils
{
    /**
     * 默认大小 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;

    private static CommonInfoService commonRepository;

    @Autowired
    public void setCommonRepository(CommonInfoService commonRepository) {
        FileUploadUtils.commonRepository = commonRepository;
    }

    public static String getDefaultBaseDir()
    {
        return commonRepository.findOne(19).getValue();
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static final String upload(MultipartFile file) throws IOException
    {
        try
        {
            return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException
    {
        try
        {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 返回上传成功的文件名
     */
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
    throws DescribeException,IOException
    {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new DescribeException("文件名太长",-100);
        }

        assertAllowed(file, allowedExtension);

        String fileName = extractFilename(file);

        File desc = getAbsoluteFile(baseDir, fileName);

//        try {
//            byte[] compressedImage = compressImage(desc, 0.5f); // 压缩比例，如0.5表示压缩50%
//            // 将压缩后的图片保存到文件
//            ImageIO.write(ImageIO.read(new ByteArrayInputStream(compressedImage)), "png", desc);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //
        OutputStream out = Files.newOutputStream(desc.toPath());
        IoUtil.copy(file.getInputStream(), out);
        //file.transferTo(desc);
        IoUtil.close(out);
        String pathFileName = getPathFileName(baseDir, fileName);

        String extension = getExtension(file);
        String[] imgExtension = {"bmp", "gif", "jpg", "jpeg", "png"};
        boolean isImg = false;
        for (String str : imgExtension)
        {
            if (str.equalsIgnoreCase(extension))
            {
                isImg = true;
            }
        }
//        try {
//            File input = new File(baseDir+"/"+fileName);
//            BufferedImage image = ImageIO.read(input);
////            int width = image.getWidth();
////            int height = image.getHeight();
//            double scaleFactor = 0.1; // 压缩比例为50%
//            int width = (int) (image.getWidth() * scaleFactor);
//            int height = (int) (image.getHeight() * scaleFactor);
//
//            BufferedImage compressedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//            Graphics2D g2d = compressedImage.createGraphics();
//            g2d.drawImage(image, 0, 0, width, height, null);
//            g2d.dispose();
//            ImageIO.write(compressedImage, "png", input);
//
//            System.out.println("压缩成功！");
//        } catch (Exception e) {
//            System.out.println("压缩失败：" + e.getMessage());
//        }
        //如果是图片则压缩
        if(isImg){
            try {
                Date date = new Date();
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                Random random = new Random();
                int randomNumber = random.nextInt(900000) + 100000; // 生成一个介于100000到999999之间的随机数
                String outfilename = fileName.substring(0,fileName.lastIndexOf("/"))+"/"+sdf.format(date)+randomNumber+fileName.substring(fileName.lastIndexOf("."),fileName.length());

                File inputFile = new File(baseDir + File.separator + fileName);
                File outputFile =  new File(baseDir + File.separator + outfilename); // 输出图片文件
                String retImgName = "/file/uploadPath/"+outfilename;
                float quality = 0.45f; // 压缩质量，范围0.0到1.0
                compressImage(inputFile, outputFile, quality);
                pathFileName = retImgName;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return pathFileName;
    }


    public static void compressImage(File inputFile, File outputFile, float quality) throws IOException {
        // 读取图片
        BufferedImage image = ImageIO.read(inputFile);

        // 获取图片写入工具
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
        ImageWriter writer = writers.next();

        // 设置写入参数
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality); // 设置压缩质量

        // 将BufferedImage写入文件
        FileImageOutputStream output = new FileImageOutputStream(outputFile);
        writer.setOutput(output);
        writer.write(null, new IIOImage(image, null, null), param);

        output.close();
        writer.dispose();
    }
    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file)
    {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName =datePath() + "/" + encodingFilename(fileName) + "." + extension;
        return fileName;
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }



    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists())
        {
            desc.createNewFile();
        }
        return desc;
    }

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

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

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws DescribeException
    {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
        {
            throw new DescribeException("文件太大",-100);
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
        {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
            {
                throw new DescribeException("",-100);
            }
            else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
            {
                throw new DescribeException("",-100);
            }
            else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
            {
                throw new DescribeException("",-100);
            }
            else
            {
                throw new DescribeException("",-100);
            }
        }

    }

    /**
     * 判断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;
    }

    //在线图片转base64
    public static String encodeImageToBase64(String imageUrl) {
        try (InputStream inputStream = new URL(imageUrl).openStream()) {
            BufferedImage image = ImageIO.read(inputStream);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, FileUtil.extName(imageUrl), outputStream); // 指定图片格式为jpg
            byte[] imageBytes = outputStream.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}