package com.tmerclub.cloud.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.common.exception.LuckException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 图片处理工具类
 *
 * @author lanhai
 */
public class ImageUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtil.class);

    private static final String JPG = "jpg";
    public static final String PNG = "png";
    private static final String JPEG = "jpeg";

    /**
     * 将图片转为二进制数组
     *
     * @param imgUrl
     * @return
     */
    public static byte[] imgToBinary(String imgUrl, String fileType) {
        try {
            BufferedImage bufferedImage = ImageIO.read(new URL(imgUrl));
            if (bufferedImage == null) {
                // 图片格式不兼容,可能是webp格式,推荐使用jpg或png
                throw new LuckException("图片格式不兼容,可能是webp格式,推荐使用jpg或png");
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //ImageIO无法写入jpeg文件 报Invalid argument to native writeImage，需重画
            if (JPG.equalsIgnoreCase(fileType) || JPEG.equalsIgnoreCase(fileType)) {
                BufferedImage tag;
                tag = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_BGR);
                Graphics g = tag.getGraphics();
                g.drawImage(bufferedImage, 0, 0, null);
                g.dispose();
                bufferedImage = tag;
            }
            ImageIO.write(bufferedImage, fileType, baos);
            return baos.toByteArray();
        } catch (IOException e) {
            // 图片丢失，请重新上传图片
            throw new LuckException("图片丢失，请重新上传图片");
        }
    }

    /**
     * @param imgUrl
     * @return 文件得后缀，文件类型 jpg ,  png , ...
     */
    public static String imgUrlFileType(String imgUrl) {
        if (StrUtil.isBlank(imgUrl)) {
            return imgUrl;
        }
        imgUrl = imgUrl.trim();
        String[] split = imgUrl.split("\\.");
        return split[split.length - 1];
    }

    /**
     * @param imgUrl
     * @return 获取文件名称
     */
    public static String imgUrlFileName(String imgUrl) {
        if (StrUtil.isBlank(imgUrl)) {
            return imgUrl;
        }
        imgUrl = imgUrl.trim();
        String[] split = imgUrl.split("/");
        return split[split.length - 1];
    }

    /**
     * @param imgUrl
     * @return 获取文件名称 45d3631e97d8438d80f9db1369595b8c
     */
    public static String imgUrlFileNameNoSuffix(String imgUrl) {
        if (StrUtil.isBlank(imgUrl)) {
            return imgUrl;
        }
        imgUrl = imgUrl.trim();
        String[] split = imgUrl.split("/");
        String s = split[split.length - 1];
        String[] split1 = s.split("\\.");
        return split1[0];
    }

    /**
     * 将图片转为base64处理后的字符串
     *
     * @param imageFile
     * @param imageType
     * @return
     */
    public static String encodeImageToBase64(InputStream imageFile, String imageType) {
        if (!imageType.equalsIgnoreCase(JPG) && !imageType.equalsIgnoreCase(PNG)) {
            throw new LuckException("仅支持上传jpg、png格式的图片");
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, imageType, outputStream);
            return Base64.encode(outputStream.toByteArray());
        } catch (IOException e) {
            throw new LuckException("图片丢失，请重新上传图片");
        }
    }

    /**
     * 将图片转为base64处理后的字符串
     *
     * @param imgUrl    图片路径
     * @param imageType
     * @return
     */
    public static String encodeImageToBase64(String imgUrl, String imageType) {
        if (!imageType.equalsIgnoreCase(JPG) && !imageType.equalsIgnoreCase(PNG)) {
            throw new LuckException("仅支持上传jpg、png格式的图片");
        }
        try {
            LOGGER.info("开始把图片{}转换为base64", imgUrl);
            BufferedImage bufferedImage = ImageIO.read(new URL(imgUrl));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, imageType, outputStream);
            String encode = Base64.encode(outputStream.toByteArray());
            LOGGER.info("图片转换base64转换结果{}", encode);
            return encode;
        } catch (IOException e) {
            throw new LuckException("图片丢失，请重新上传图片");
        }
    }
}
