package com.ai.da.common.utils;

import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.common.constant.CommonConstant;
import com.ai.da.common.response.ResultEnum;
import com.ai.da.mapper.primary.entity.ObjectItem;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.*;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @description： minio工具类
 * @version：3.0
 */
@Slf4j
@Component
public class MinioUtil {
    @Autowired
    private MinioClient minioClient;

    /**
     * description: 判断bucket是否存在，不存在则创建
     *
     * @return: void
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * description: 上传文件
     *
     * @param bucketName
     * @param path
     * @param multipartFile
     * @return: java.lang.String
     */
    public List<String> uploadBatch(String bucketName, String path, MultipartFile[] multipartFile) {
        List<String> names = new ArrayList<>(multipartFile.length);
        for (MultipartFile file : multipartFile) {
            String fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            if (split.length > 1) {
                fileName = path + "/" + UUID.randomUUID() + "." + split[1];
            } else {
                fileName = path + "/" + UUID.randomUUID();
            }
            InputStream in = null;
            try {
                in = file.getInputStream();
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(in, in.available(), -1)
                        .contentType(file.getContentType())
                        .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            names.add(fileName);
        }
        return names;
    }

    public String uploadImageFromBase64(String bucketName, String base64Image, String imageType) {
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        String fileName = UUID.randomUUID().toString() + "." + imageType; // or any other image format

        try (InputStream in = new ByteArrayInputStream(imageBytes)) {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(in, in.available(), -1)
                    .contentType("image/png") // Set the content type according to your image format
                    .build()
            );

            return bucketName + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null; // or throw an exception
        }
    }

    /**
     * description: 上传文件
     *
     * @param bucketName
     * @param path
     * @param file
     * @return: java.lang.String
     */
    public String upload(String bucketName, String path, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String[] split = fileName.split("\\.");
        if (split.length > 1) {
            fileName = path + "/" + UUID.randomUUID() + "." + split[split.length - 1];
        } else {
            fileName = path + "/" + UUID.randomUUID();
        }
        InputStream in = null;
        try {
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bucketName + "/" + fileName;
    }

    public String upload(String bucketName, String path, MultipartFile file, String copy) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(path)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bucketName + "/" + path;
    }

//    public String upload(String bucketName, String path, File file) {
//        InputStream in = null;
//        try {
//            in = new FileInputStream(file);
//            minioClient.putObject(PutObjectArgs.builder()
//                    .bucket(bucketName)
//                    .object(path)
//                    .stream(in, in.available(), -1)
//                    .contentType(file.getContentType())
//                    .build()
//            );
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return fileName;
//    }

    public InputStream download(String bucketName, String objectName) throws MinioException, IOException {
        try {
            return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public InputStream download(String path) throws MinioException, IOException {
        if (!path.contains("/")) {
            throw new BusinessException("the.path.is.error");
        }
        int index = path.indexOf("/");
        String bucketName = path.substring(0, index);
        String objectName = path.substring(index + 1);
        return download(bucketName, objectName);
    }

    /**
     * description: 下载文件
     *
     * @param path
     * @param bucketName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
//    public ResponseEntity<byte[]> download(String path, String bucketName) {
//        ResponseEntity<byte[]> responseEntity = null;
//        InputStream in = null;
//        ByteArrayOutputStream out = null;
//        try {
//            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(path).build());
//            out = new ByteArrayOutputStream();
//            IOUtils.copy(in, out);
//            //封装返回值
//            byte[] bytes = out.toByteArray();
//            HttpHeaders headers = new HttpHeaders();
//            try {
//                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(path, "UTF-8"));
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            headers.setContentLength(bytes.length);
//            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
//            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (in != null) {
//                    try {
//                        in.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//                if (out != null) {
//                    out.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return responseEntity;
//    }

    /**
     * 查看文件对象
     *
     * @param bucketName 存储bucket名称
     * @return 存储bucket内文件对象信息
     */
    public List<ObjectItem> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<ObjectItem> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                ObjectItem objectItem = new ObjectItem();
                objectItem.setObjectName(item.objectName());
                objectItem.setSize(item.size());
                objectItems.add(objectItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectItems;
    }

    /**
     * 批量删除文件对象
     *
     * @param bucketName 存储bucket名称
     * @param objects    对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }

    public void deleteObject(String bucketName, String objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            System.out.println("Object " + objectName + " successfully removed from bucket " + bucketName);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Error while removing object " + objectName + " from bucket " + bucketName + ": " + e.getMessage());
        }
    }

    public void deleteObject(String path) {
        if (!path.contains("/")) {
            throw new BusinessException("the.path.is.error");
        }
        int index = path.indexOf("/");
        String bucketName = path.substring(0, index);
        String objectName = path.substring(index + 1);
        deleteObject(bucketName, objectName);
    }

    /**
     * 获取文件的临时URL
     *
     * @param bucketName 存储桶名称
     * @param fileName   文件名
     * @param expiry     过期时间（单位：分）
     * @return 文件的临时URL，如果出现异常则返回null
     */
    public String getPreSignedUrl(String bucketName, String fileName, int expiry) {
        try {

            String lowerName = fileName.toLowerCase();
            boolean isImage = lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg")
                    || lowerName.endsWith(".png") || lowerName.endsWith(".gif");

            GetPresignedObjectUrlArgs.Builder builder = GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .expiry(expiry, TimeUnit.MINUTES)
                    .method(Method.GET);

            if (isImage) {
                // 根据后缀名设置正确的 content-type
                String contentType = "image/jpeg";
                if (lowerName.endsWith(".png")) {
                    contentType = "image/png";
                } else if (lowerName.endsWith(".gif")) {  // 新增 GIF
                    contentType = "image/gif";
                }

                Map<String, String> queryParams = new HashMap<>();
                queryParams.put("response-content-type", contentType);
                queryParams.put("response-content-disposition", "inline");

                builder.extraQueryParams(queryParams);
            }

            return minioClient.getPresignedObjectUrl(builder.build());
        } catch (MinioException | InvalidKeyException
                 | IOException | NoSuchAlgorithmException | IllegalArgumentException e) {
            e.printStackTrace();
            log.error("bucket: {}, object:{}", bucketName, fileName);
            throw new BusinessException(e.getMessage());
        }
    }

    public String getPreSignedUrl(String path, int expiry) {
        if (LocalCacheUtils.getPresignedUrlCache(path) != null) {
            return LocalCacheUtils.getPresignedUrlCache(path);
        } else {
            if (!path.contains("/")) {
                throw new BusinessException("the.path.is.error");
            }
            int index = path.indexOf("/");
            String bucketName = path.substring(0, index);
            String fileName = path.substring(index + 1);
            String presignedUrl = getPreSignedUrl(bucketName, fileName, expiry);
            LocalCacheUtils.setPresignedUrlCache(path, presignedUrl);
            return presignedUrl;
        }
    }

    public String getPreSignedUrl(String path, int expiry, boolean resetCache) {
        if (resetCache || LocalCacheUtils.getPresignedUrlCache(path) == null) {
            if (!path.contains("/")) {
                throw new BusinessException("the.path.is.error");
            }
            int index = path.indexOf("/");
            String bucketName = path.substring(0, index);
            String fileName = path.substring(index + 1);
            String presignedUrl = getPreSignedUrl(bucketName, fileName, expiry);
            LocalCacheUtils.setPresignedUrlCache(path, presignedUrl);
            return presignedUrl;
        } else {
            return LocalCacheUtils.getPresignedUrlCache(path);
        }
    }

    /**
     * 将桶名、文件名从url中分离出来
     *
     * @param url    带桶名、文件名的url
     * @param expiry 图片过期时间
     * @return 可以直接访问的minio图片地址
     */
    public String splitThenGetPreviewUrl(String url, int expiry) {
        String[] parts = url.split("/");
        String bucketName = parts[0];
        StringBuilder fileName = new StringBuilder();
        for (int i = 1; i < parts.length; i++) {
            fileName.append(parts[i]);
            if (i != parts.length - 1) {
                fileName.append("/");
            }
        }
        return getPreSignedUrl(bucketName, String.valueOf(fileName), expiry);
    }

    public boolean doesObjectExist(String path) {
        if (!path.contains("/")) {
            throw new BusinessException("the.path.is.error");
        }
        int index = path.indexOf("/");
        String bucketName = path.substring(0, index);
        String objectName = path.substring(index + 1);
        return doesObjectExist(bucketName, objectName);
    }

    public boolean doesObjectExist(String bucketName, String objectName) {
        try {
            minioClient.statObject(
                    StatObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .build()
            );
            return true;
        } catch (Exception e) {
            // 如果发生异常，说明文件不存在或者出现了其他错误
            return false;
        }
    }

    public String base64UploadToPath(String base64, String bucketName, String path){
        String[] parts = base64.split(",");
        String imageType = parts[0].split("/")[1].split(";")[0];
        String base64Data = parts[1];

        byte[] imageBytes = Base64.getDecoder().decode(base64Data);
        String fileName;
        if (!StringUtil.isNullOrEmpty(path)){
            fileName = path + "." + imageType; // or any other image format
        }else {
            fileName = UUID.randomUUID() + "." + imageType;
        }

        try (InputStream in = new ByteArrayInputStream(imageBytes)) {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(in, in.available(), -1)
                    .contentType("image/" + imageType) // Set the content type according to your image format
                    .build()
            );

            return bucketName + "/" + fileName;
        } catch (Exception e) {
            log.info("base64上传minio失败:{}",e.getMessage());
            log.error(e.getMessage());
            return null; // or throw an exception
        }
    }

    /**
     * 从 MinIO 下载对象到本地路径
     *
     * @param bucketName   存储桶名称
     * @param objectName   MinIO 上对象的名称
     * @param localFilePath 本地文件路径
     */
    public void downloadMinioObjectToLocal(String bucketName, String objectName, String localFilePath) {
        File localFile = new File(localFilePath);
        File parentDir = localFile.getParentFile();
        if (parentDir != null) {
            parentDir.mkdirs(); // 创建文件夹，确保路径结构与 MinIO 一致
        }

        try (InputStream stream = minioClient.getObject(
                GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
             FileOutputStream out = new FileOutputStream(localFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = stream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            log.info("Downloaded object {} to {}", objectName, localFilePath);
        } catch (Exception e) {
            log.error("Error while downloading object {}: {}", objectName, e.getMessage());
        }
    }

    /**
     * 从路径中提取存储桶名称
     *
     * @param path MinIO 路径
     * @return 存储桶名称
     */
    public String getBucketNameFromPath(String path) {
        int index = path.indexOf("/");
        return path.substring(0, index); // 获取第一级路径作为 bucket 名称
    }

    /**
     * 从路径中提取对象名称
     *
     * @param path MinIO 路径
     * @return 对象名称
     */
    public String getObjectNameFromPath(String path) {
        int index = path.indexOf("/");
        return path.substring(index + 1); // 获取路径的其余部分作为对象名称
    }

    public List<Integer> getImagesWidthAndHeight(String path){
        int index = path.indexOf("/");
        String bucketName = path.substring(0, index);
        String objectName = path.substring(index + 1);
        try {
            // 从 MinIO 下载图片
            GetObjectResponse response = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .build()
            );

            BufferedImage image = ImageIO.read(response);
            int width = image.getWidth();
            int height = image.getHeight();

            log.info("Image path {}, Width: {}, Height: {}", path, width, height);
            response.close();
            return Arrays.asList(width, height);
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("图片:{}, 获取宽高异常", path);
            throw new BusinessException(e.getMessage());
        }
    }

    public void upload(String url, File file) {
        try {
            // 分割桶名和对象路径
            int firstSlashIndex = url.indexOf("/");
            if (firstSlashIndex == -1) {
                throw new IllegalArgumentException("URL 格式不正确，无法解析桶名和对象路径");
            }
            String bucketName = url.substring(0, firstSlashIndex);
            String objectName = url.substring(firstSlashIndex + 1);

            // 读取文件流
            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                // 上传到 MinIO
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName)
                                .object(objectName)
                                .stream(fileInputStream, file.length(), -1)
                                .contentType("application/zip")
                                .build()
                );
                System.out.println("文件上传成功: " + url);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("文件上传失败: " + e.getMessage());
        }
    }

    public String getImageAsBase64(String path) throws IOException {
        int index = path.indexOf("/");
        String bucketName = path.substring(0, index);
        String fileName = path.substring(index + 1);

        // 检查桶是否存在
        boolean found = doesObjectExist(bucketName, fileName);
        if (!found) {
            throw new IOException("Bucket " + bucketName + " does not exist");
        }

        try (InputStream stream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .build())) {

            byte[] bytes = IOUtils.toByteArray(stream);
            return Base64.getEncoder().encodeToString(bytes);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取压缩后的图片Base64编码
     * @param path 图片的minio路径
     * @param targetWidth 目标宽度
     * @param targetHeight 目标高度
     * @return 压缩后的图片Base64编码
     * @throws IOException
     */
    public String getCompressedImageAsBase64(String path, int targetWidth, int targetHeight) throws IOException {
        int index = path.indexOf("/");
        String bucketName = path.substring(0, index);
        String fileName = path.substring(index + 1);

        // 检查桶是否存在
        boolean found = doesObjectExist(bucketName, fileName);
        if (!found) {
            throw new IOException("Bucket " + bucketName + " does not exist");
        }

        try (InputStream stream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .build())) {

            // 读取原始图片
            BufferedImage originalImage = ImageIO.read(stream);
            if (originalImage == null) {
                throw new IOException("无法读取图片: " + path);
            }

            // 计算压缩比例，保持宽高比
            int originalWidth = originalImage.getWidth();
            int originalHeight = originalImage.getHeight();
            
            double scaleX = (double) targetWidth / originalWidth;
            double scaleY = (double) targetHeight / originalHeight;
            double scale = Math.min(scaleX, scaleY); // 选择较小的缩放比例以保持宽高比
            
            int newWidth = (int) (originalWidth * scale);
            int newHeight = (int) (originalHeight * scale);

            // 创建压缩后的图片
            BufferedImage compressedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = compressedImage.createGraphics();
            
            // 设置高质量渲染
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            
            // 绘制压缩后的图片
            g2d.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
            g2d.dispose();

            // 转换为Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(compressedImage, "JPEG", baos); // 使用JPEG格式以减小文件大小
            byte[] imageBytes = baos.toByteArray();
            
            log.info("图片压缩完成: {} -> {}x{} (原始: {}x{})", path, newWidth, newHeight, originalWidth, originalHeight);
            return Base64.getEncoder().encodeToString(imageBytes);

        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 压缩base64格式的图片
     * @param base64Image 包含前缀的base64图片字符串 (如: "data:image/png;base64,...")
     * @param targetWidth 目标宽度
     * @param targetHeight 目标高度
     * @return 压缩后的base64图片字符串（保持原有前缀格式）
     */
    public String compressBase64Image(String base64Image, int targetWidth, int targetHeight) {
        if (base64Image == null || base64Image.isEmpty()) {
            return base64Image;
        }

        try {
            // 解析base64字符串
            String[] parts = base64Image.split(",");
            if (parts.length != 2) {
                log.warn("无效的base64图片格式: {}", base64Image.substring(0, Math.min(50, base64Image.length())));
                return base64Image;
            }
            
            String prefix = parts[0] + ","; // 保留前缀，如 "data:image/png;base64,"
            String base64Data = parts[1];

            // 解码base64数据
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);
            
            // 读取图片
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageBytes));
            if (originalImage == null) {
                log.warn("无法读取base64图片数据");
                return base64Image;
            }

            // 计算压缩比例，保持宽高比
            int originalWidth = originalImage.getWidth();
            int originalHeight = originalImage.getHeight();
            
            double scaleX = (double) targetWidth / originalWidth;
            double scaleY = (double) targetHeight / originalHeight;
            double scale = Math.min(scaleX, scaleY); // 选择较小的缩放比例以保持宽高比
            
            int newWidth = (int) (originalWidth * scale);
            int newHeight = (int) (originalHeight * scale);

            // 如果图片已经比目标尺寸小，则不进行压缩
            if (scale >= 1.0) {
                log.info("图片尺寸 {}x{} 已小于目标尺寸 {}x{}，无需压缩", originalWidth, originalHeight, targetWidth, targetHeight);
                return base64Image;
            }

            // 创建压缩后的图片
            BufferedImage compressedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = compressedImage.createGraphics();
            
            // 设置高质量渲染
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            
            // 绘制压缩后的图片
            g2d.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
            g2d.dispose();

            // 转换为Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(compressedImage, "PNG", baos); // 保持PNG格式以支持透明度
            byte[] compressedBytes = baos.toByteArray();
            String compressedBase64 = Base64.getEncoder().encodeToString(compressedBytes);
            
            log.info("Base64图片压缩完成: {}x{} -> {}x{} (压缩比: {:.2f})", 
                    originalWidth, originalHeight, newWidth, newHeight, scale);
            
            return prefix + compressedBase64;

        } catch (Exception e) {
            log.error("压缩base64图片失败", e);
            return base64Image; // 出错时返回原图
        }
    }

    public void uploadToMinio(byte[] data, String bucket, String objectName, String contentType) /*throws Exception*/ {
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .stream(new ByteArrayInputStream(data), data.length, -1)
                    .contentType(contentType)
                    .build());
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e){
            log.error("图片上传到minio出错，{}", e.getMessage());
            throw new BusinessException("file.upload.fail");
        }
    }

    public String changeToWhiteBackground(String minioPath){
        try {
            // 1. 使用URL读取远程图片
            BufferedImage originalImage = ImageIO.read(new URL(getPreSignedUrl(minioPath, CommonConstant.MINIO_IMAGE_EXPIRE_TIME)));

            // 2. 透明图检查（新增核心逻辑）
            if (!hasTransparency(originalImage)) {
                log.info("图片 {} 无透明通道，无需添加白底", minioPath);
                return null; // 返回空
            }
            // 3. 处理图片（例如：转换为白底）
            BufferedImage newImage = new BufferedImage(
                    originalImage.getWidth(),
                    originalImage.getHeight(),
                    BufferedImage.TYPE_INT_RGB
            );

            // 4. 填充白色背景
            java.awt.Graphics2D g = newImage.createGraphics();
            g.setColor(java.awt.Color.WHITE);
            g.fillRect(0, 0, newImage.getWidth(), newImage.getHeight());
            g.drawImage(originalImage, 0, 0, null);
            g.dispose();

            // 5. 输出为Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(newImage, "PNG", baos);
            String base64Image = java.util.Base64.getEncoder().encodeToString(baos.toByteArray());
            log.info("为图片 {} 添加白色背景", minioPath);
//            System.out.println("data:image/png;base64," + base64Image);
            return "data:image/png;base64," + base64Image;
//            return base64Image;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BusinessException("white.bg.add.fail", ResultEnum.PROMPT.getCode());
        }
    }

    /**
     * 检测图片是否包含透明通道
     */
    private boolean hasTransparency(BufferedImage image) {
        // 情况1：图像本身支持透明（如TYPE_INT_ARGB）
        if (image.getTransparency() == Transparency.TRANSLUCENT) {
            return true;
        }

        // 情况2：检查像素级透明度（适用于TYPE_INT_RGB等格式）
        if (image.getColorModel().hasAlpha()) {
            // 抽样检查前100x100像素（避免全图扫描的性能问题）
            int width = Math.min(image.getWidth(), 100);
            int height = Math.min(image.getHeight(), 100);

            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if ((image.getRGB(x, y) >> 24) == 0x00) {
                        return true; // 发现透明像素
                    }
                }
            }
        }
        return false;
    }

    /**
     * 将A桶中的对象复制到B桶中
     * @return
     */
    public void copyObject(String sourceBucket, String sourceObject, String targetBucket, String targetObject) {
        // 检查目标桶是否存在
        boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(targetBucket)
                    .build());
        } catch (Exception e) {
            log.error("目标桶{}，不存在", targetBucket);
            throw new BusinessException("Copy object failed");
        }

        if (found) {
            // 复制对象
            try {
                minioClient.copyObject(
                        CopyObjectArgs.builder()
                                .bucket(targetBucket)
                                .object(targetObject)
                                .source(
                                        CopySource.builder()
                                                .bucket(sourceBucket)
                                                .object(sourceObject)
                                                .build()
                                )
                                .build()
                );
            } catch (Exception e) {
                log.error("对象复制失败");
                throw new BusinessException("Copy object failed");
            }
            log.info("对象复制成功");
        } else {
            log.error("目标桶{}，不存在", targetBucket);
            throw new BusinessException("Copy object failed");
        }
    }

}


