package com.changfa.utils;

import cn.hutool.core.img.ImgUtil;
import com.changfa.config.ObjectItem;
import com.changfa.entity.FileData;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

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

    @Autowired
    private MinioProperties minioProperties;

    private final static List<String> images = Arrays.asList("jpg", "jpeg", "png", "bmp", "gif");


    /**
     * 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 multipartFile
     * @return: java.lang.String
     */
    public List<FileData> upload(MultipartFile file) {
        List<FileData> fileList = new ArrayList<>();
        String bucketName = minioProperties.getBucketName();
        String separator = minioProperties.getSeparator();
        String showPath = minioProperties.getShowPath();
        String downloadPath = minioProperties.getDownloadPath();
        String originalFilename = file.getOriginalFilename();
        String[] split = originalFilename.split("\\.");
        String fileExe = "." + split[split.length - 1];
        String fileName = UUID.randomUUID().toString().replace("-", "");
        FileData fileData = new FileData(showPath + separator + fileName, file.getSize(), fileExe, fileName, originalFilename.substring(0, originalFilename.lastIndexOf(".")), minioProperties.getFilePath(), downloadPath + separator + fileName, bucketName);
        InputStream in = null;
        try {
            existBucket(bucketName);
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName + fileExe)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
            fileList.add(fileData);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return fileList;
    }

    /**
     * description: 下载文件
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    public ResponseEntity<byte[]> download(String fileName, String extension, String type) {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName + extension).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                headers.add("Content-Disposition", "" + type + ";filename=" + URLEncoder.encode(fileName + extension, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
          /*  //增加水印
            if(haveSY){
                try{
                  //  this.getClass().getResourceAsStream("/icon/1673150714346.png")
                    BufferedImage shuiyin = ImgUtil.read(this.getClass().getResourceAsStream("/icon/1673150714346.png"));
                    ImgUtil.pressImage(in, out, shuiyin, 0, 0, 1f);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }*/
            headers.setContentLength(bytes.length);
            if (!"inline".equalsIgnoreCase(type)) {
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            } else {
                if (extension.contains("pdf")) {
                    headers.setContentType(MediaType.APPLICATION_PDF);
                } else if (images.contains(extension)) {
                    headers.setContentType(MediaType.IMAGE_JPEG);
                } else {
                    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 removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }
}

