package org.jeecg.module.custom.ocr.utils;

import net.coobird.thumbnailator.Thumbnails;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Title:
 * @Description: 图片设置
 * @Author 郭向斌
 * @Date 2024-03-18 15:29
 * @Version V1.0
 */
public class ImageUtils {
    public static String generateThumbnail(String inputImagePath, Integer newWidth) throws IOException {
        if (newWidth == null) {
            newWidth = 182;
        }
        // 获取目录路径
        String directoryPath = inputImagePath.substring(0, inputImagePath.lastIndexOf("/") + 1);
        File inputFile = new File(inputImagePath);

        // 获取文件扩展名
        String fileExtension = getFileExtension(inputFile.getName());

        // 生成随机 ID 替换中文
        String fileName = inputFile.getName();
        String newFileName = replaceChineseWithRandomId(fileName);

        // 构造输出路径
        String outputImagePath = directoryPath + "thumbnail_" + newFileName;

        // 生成缩略图
        BufferedImage bufferedImage = Thumbnails.of(inputFile).scale(1).asBufferedImage();
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        int newHeight = (int) Math.round((double) height * newWidth / width);

        Thumbnails.of(inputFile)
                .size(newWidth, newHeight)
                .outputFormat(fileExtension)
                .toFile(new File(outputImagePath));

        return outputImagePath;
    }

    private static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf(".");
        return lastDotIndex > 0 ? fileName.substring(lastDotIndex + 1) : "";
    }

    private static String replaceChineseWithRandomId(String fileName) {
        // 正则表达式匹配中文字符
        Pattern chinesePattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
        Matcher matcher = chinesePattern.matcher(fileName);

        // 如果找到中文，替换为随机 UUID（取前 8 位以保持简洁）
        if (matcher.find()) {
            String randomId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
            return matcher.replaceAll(randomId);
        }

        // 如果没有中文，直接返回原文件名
        return fileName;
    }


    public static void main(String[] args) throws IOException {
        String url="C:\\Users\\郭向斌\\Downloads\\1-星浩.png";
        String s = generateThumbnail(url,180);
        System.out.println(s);
        String st="http://47.93.59.251/api/image/";
        String s1 = ImageUtils.generateThumbnail(url, 182);
        String stri=st+getFileName(s1);
        System.out.println(stri);
    }
    public static String getFileName(String filePath) {
        File file = new File(filePath);
        return file.getName();
    }
}
