package com.huimv.receive.common.utils;


import net.coobird.thumbnailator.Thumbnails;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


import javax.imageio.*;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 获取图片尺寸和截图 工具类
 *
 * @author zhangxiaoyan
 */
public class ImageSizeUtil {

//    private final static Logger logger = LoggerFactory.getLogger(ImageSizeUtil.class);



    /**
     * 获取图片最长边长度
     * @param params
     * @return
     */
//    public static int getImageLengthOfSide(MultipartFile params){
//        int lengthSize = 0;
//        Map<String, Integer> result = new HashMap<>();
//        long beginTime = new Date().getTime();
//        // 获取图片格式
//        String suffixName = getSuffixNameInfo(params);
//        try {
//            Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(suffixName);
//            ImageReader reader = (ImageReader) readers.next();
//            ImageInputStream iis = ImageIO.createImageInputStream(params.getInputStream());
//            reader.setInput(iis, true);
//            result.put("width",reader.getWidth(0));
//            result.put("height",reader.getHeight(0));
//            if(reader.getWidth(0) > reader.getHeight(0)){
//                lengthSize = reader.getWidth(0);
//            }else{
//                lengthSize = reader.getHeight(0);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return lengthSize;
//    }

    /**
     * 获取图片格式
     * @param params
     * @return
     */
    public static String getSuffixNameInfo(MultipartFile params){
        String result = "";
        // 图片后缀
        String suffixName = params.getOriginalFilename().substring(
                params.getOriginalFilename().lastIndexOf("."));
        if(suffixName.indexOf("png")>0){
            result = "png";
        }else if(suffixName.indexOf("jpg")>0){
            result = "jpg";
        }else if(suffixName.indexOf("jpeg")>0){
            result = "jpeg";
        }

        return result;
    }




    /**
     * 根据指定大小压缩图片
     *
     * @param imageBytes  源图片字节数组
     * @param desFileSize 指定图片大小，单位kb
     * @return 压缩质量后的图片字节数组
     */
    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
        if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / 1024);
//        double accuracy = 0.85;
        try {
            while (imageBytes.length > desFileSize * 1024) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                        .scale(accuracy)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
//            logger.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
//                    "", srcSize / 1024, imageBytes.length / 1024);
        } catch (Exception e) {
//            logger.error("【图片压缩】msg=图片压缩失败!", e);
        }
        return imageBytes;
    }

    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小，单位kb
     * @return 图片压缩质量比
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.85;
        } else if (size < 2047) {
//            accuracy = 0.6;
            accuracy = 0.8;
        } else if (size < 3275) {
//            accuracy = 0.44;
            accuracy = 0.7;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }

    /**
     * base64 转MultipartFile
     * @param base64
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            // 注意base64是否有头信息，如：data:image/jpeg;base64,。。。
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);

            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            return new BASE64DecodedMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 压缩图片
     * @return
     */
    public static MultipartFile byte2Base64StringFun(MultipartFile fileImg) throws IOException {
        MultipartFile result = fileImg;
        // 获取图片最长边
//        int imageLengthSize = ImageSizeUtil.getImageLengthOfSide(fileImg);
//        Long swd = fileImg.getSize();
            BASE64Encoder encoder = new BASE64Encoder();
            String imgData1 = null;
            try {
                InputStream inputStream = fileImg.getInputStream();
                byte[] imgData = ImageSizeUtil.compressPicForScale(ToolsUtil.getByteArray(inputStream),100);
                imgData1 = "data:"+fileImg.getContentType()+";base64,"+encoder.encode(imgData);
                MultipartFile def = ImageSizeUtil.base64ToMultipart(imgData1);
                result = def;
            } catch (IOException e) {
                e.printStackTrace();
            }
        return result;
    }



    /**
     * 将MultipartFile中的图片转换为JPG格式，保持原始尺寸并返回转换后的图片大小
     * @param multipartFile 原始图片文件
     * @return 转换后的JPG格式图片的大小（字节）
     * @throws IOException 处理图片过程中可能出现的IO异常
     */
    public static long convertToJpgAndGetSize(MultipartFile multipartFile) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(multipartFile.getInputStream());

        // 获取原始图片的宽度和高度
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        // 创建一个新的BufferedImage，类型为RGB（JPG不支持透明通道）
        BufferedImage jpgImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 将原始图片绘制到新的BufferedImage中，确保尺寸不变
        jpgImage.createGraphics().drawImage(originalImage, 0, 0, width, height, null);

        // 创建字节数组输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);

        try {
            // 获取JPG格式的ImageWriter
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            if (!writers.hasNext()) {
                throw new IllegalStateException("No JPG image writer found");
            }
            ImageWriter writer = writers.next();
            writer.setOutput(ios);

            // 设置JPG编码参数，质量为1.0（最高质量）
            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(1.0f);

            // 写入图片
            writer.write(null, new IIOImage(jpgImage, null, null), param);

            // 返回图片大小（字节）
            return baos.size();
        } finally {
            // 关闭资源
            ios.close();
            baos.close();
        }
    }


}

