package com.ruoyi.dataprocess.common;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.UUID;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

/**
 * @Description: 图片工具类
 * @ClassName: ImageUtils
 * @Author : xins
 * @Date :2023-09-04  15:57
 * @Version :1.0
 */
public class ImageUtils {

    public static final String BASE64_PREFIX = "data:image/";//base64图片前缀
    public static final String BASE64_SUFFIX = ";base64";//base64图片后缀

    /**
     * @param imagePatternArr
     * @return String
     * @param: base64Str
     * @description 校验base64字符串是否是图片, 并且返回图片类型
     * @author xins
     * @date 2023-09-04 16:05
     */
    public static String getImageType(String base64Str, String[] imagePatternArr) {
        for (String imagePattern : imagePatternArr) {
            String base64Pattern = BASE64_PREFIX + imagePattern + BASE64_SUFFIX;
            if (base64Str.indexOf(base64Pattern) > -1) {
                return imagePattern;
            }
        }
        return "";
    }

    /**
     * @return String
     * @param: imageFileName
     * @description 图片转base64
     * @author xins
     * @date 2023-09-04 15:58
     */
    public static String convertImageToBase64(String imageFileName) {
        ByteArrayOutputStream baos = null;
        try {
            //获取图片类型
            String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            //构建文件
            File imageFile = new File(imageFileName);
            //通过ImageIO把文件读取成BufferedImage对象
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            //构建字节数组输出流
            baos = new ByteArrayOutputStream();
            //写入流
            ImageIO.write(bufferedImage, suffix, baos);
            //通过字节数组流获取字节数组
            byte[] bytes = baos.toByteArray();
            //获取JDK8里的编码器Base64.Encoder转为base64字符
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * @param: base64
     * @param: imageFileName
     * @description base64字符串转图片
     * @author xins
     * @date 2023-09-04 15:59
     */
    public static String convertBase64ToImage(String base64Str, String imagePath, String imageType, Long deviceId) {
        // 解密
        try {
            String fileName = UUID.randomUUID().toString().concat(".").concat(imageType);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            String dateStr = format.format(date);

            String fullPath = imagePath + File.separator + deviceId
                    + File.separator + dateStr;
            File file = new File(fullPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            // 去掉base64前缀 data:image/jpeg;base64,
            String imageFileName = fullPath + File.separator + fileName;
            base64Str = base64Str.substring(base64Str.indexOf(",", 1) + 1);
            // 解密，解密的结果是一个byte数组
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] imgbytes = decoder.decode(base64Str);
            for (int i = 0; i < imgbytes.length; ++i) {
                if (imgbytes[i] < 0) {
                    imgbytes[i] += 256;
                }
            }

            // 保存图片
            OutputStream out = new FileOutputStream(imageFileName);
            out.write(imgbytes);
            out.flush();
            out.close();
            // 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
            return imageFileName;
        } catch (IOException e) {
            return null;
        }

    }


    public static String getFileContent(FileInputStream fis, String encoding) throws IOException {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(fis, encoding))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        }
    }


    public static void main(String[] args) throws IOException {
        // 从txt文件中读取base64字符串
        FileInputStream fis = new FileInputStream("e://base64test/base64test5.txt");
        String base64Str = getFileContent(fis, "UTF-8");
        String[] imagePatternArr = {"png", "jpg", "jpeg"};
        String imageType = ImageUtils.getImageType(base64Str, imagePatternArr);
        ImageUtils.convertBase64ToImage(base64Str,"images",imageType,2L);

        // 将base64字符串翻译成图片


    }

}
