package com.ai.da.common.utils;

import com.ai.da.common.config.exception.BusinessException;
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.image.BufferedImage;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
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");

            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";
                }

                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 e) {
            e.printStackTrace();
            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.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);
        }
    }

    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 exception");
        }
    }


}


