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.MinioException;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @description： minio工具类
 * @version：3.0
 */
@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;
    }

    /**
     * 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 {
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .expiry(expiry, TimeUnit.MINUTES)
                            .method(Method.GET)
                            .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;
        }
    }

    /**
     * 将桶名、文件名从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 bucketName, String objectName) {
        try {
            minioClient.statObject(
                    StatObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .build()
            );
            return true;
        } catch (Exception e) {
            // 如果发生异常，说明文件不存在或者出现了其他错误
            return false;
        }
    }
}


