package com.persagy.dmp.file.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.file.config.FileExceptionHandler;
import com.persagy.dmp.file.constant.FileCommonConst;
import com.persagy.dmp.file.service.IFileStorageService;
import io.minio.*;
import io.minio.errors.ErrorResponseException;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * MinIO存储服务实现类
 * @author Charlie Yu
 */
@Slf4j
@RequiredArgsConstructor
public class MinioStorageServiceImpl implements IFileStorageService, InitializingBean {

    private final MinioClient minioClient;

    @Value("${persagy.common.file.minio.bucket.chunk:bdtp}")
    private String chunkBucKet;

    private static final Long CHUCK_MIN_FILE_SIZE=5242880L;

    /**排序*/
    public final static boolean SORT = true;
    /**不排序*/
    public final static boolean NOT_SORT = false;
    /**默认过期时间(分钟)*/
    private final static Integer DEFAULT_EXPIRY = 60;

    @Override
    public void afterPropertiesSet() {
        //方便管理分片文件，则单独创建一个分片文件的存储桶
        if (!isBucketExist(chunkBucKet)){
            createBucket(chunkBucKet);
        }
    }

    @Override
    public void upload(String bucketName, String fileName, InputStream input) {
        // 容错判断
        if(StrUtil.isBlank(fileName) || input == null) {
            throw new BusinessException("上传文件参数有误！");
        }
        try {
            // 确认桶是否存在
            bucketName = ensureBucket(bucketName);
            if (exists(bucketName,fileName)){
                return;
            }
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).
                            stream(input, input.available(), -1).build());
        } catch (Exception e) {
            FileExceptionHandler.handleException(e);
        }
    }
    /***
     * Description: 上传分片
     * @param chuckBucketName : bucketName
     * @param fileMd5 : 文件的md5值
     * @param inputStream : 文件流
     * @param totalChunks : 总分片数
     * @param currentChuckNumber : 当前分片数
     * return : void
     * @author : lijie
     * Update By 2021/12/17 15:18
     */
    @Override
    public void uploadChuck(String chuckBucketName, String fileMd5, InputStream inputStream,Integer totalChunks,
                            Integer currentChuckNumber) {
        byte[] bytes = IoUtil.readBytes(inputStream);
        // 如果分片大小大于5M则直接上传
        upload(chuckBucketName,fileMd5+StrUtil.SLASH+currentChuckNumber+FileCommonConst.CHUCK_FILE_SUFFIX,IoUtil.toStream(bytes));
        // 2021年12月17日15:53:47 暂时不考虑
//        if (bytes.length>CHUCK_MIN_FILE_SIZE){
//            // 如果分片大小大于5M则跳过检查
//            return;
//        }
//        int groupSize = (int)Math.ceil(CHUCK_MIN_FILE_SIZE / (bytes.length * 0.1));
//        int groupNum = (int)Math.ceil(currentChuckNumber / (groupSize * 0.1));
//        int startChuckNumber = (groupNum-1)*groupSize;
    }

    /***
     * Description: 合并小分片
     * @param bucketName : bucket的名称
     * @param fileName : 文件名称
     * @param bytes : 字节内容
     * return : void
     * @author : lijie
     * Update By 2021/12/17 12:23
     */
    @SneakyThrows
    private void mergeMinFile(String bucketName, String fileName, byte[] bytes) {
        String prefix = fileName.substring(0, fileName.lastIndexOf("/"));
        List<String> objectNames = listObjectNames(bucketName, prefix, Boolean.TRUE);
        if (CollUtil.isEmpty(objectNames)){
            ByteArrayInputStream inputStream = IoUtil.toStream(bytes);
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).
                    stream(inputStream, inputStream.available(), -1).build());
            return;
        }
        // 开始检查分片,每次都从头到尾检查一遍.防止出现并发上传的分片
        String lastObjName = objectNames.get(objectNames.size() - 1);
        StatObjectResponse objectResponse = minioClient
                .statObject(StatObjectArgs.builder().bucket(bucketName).object(lastObjName).build());
        if (objectResponse.size()>CHUCK_MIN_FILE_SIZE){
            ByteArrayInputStream inputStream = IoUtil.toStream(bytes);
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).
                    stream(inputStream, inputStream.available(), -1).build());
            return;
        }
        InputStream lastObj = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(lastObjName).build());
        byte[] lastBytes = IoUtil.readBytes(lastObj);
    }

    @Override
    public InputStream download(String bucketName, String fileName) {
        return download(bucketName,fileName,null,null);
    }
    /**
     * 文件下载
     * @param bucketName 桶名
     * @param fileName 文件名
     * @param response 响应对象
     */
    @Override
    public InputStream download(String bucketName, String fileName, HttpServletResponse response,String realFileName) {
        // 容错判断
        if(StrUtil.isBlank(fileName)) {
            throw new BusinessException("下载文件参数有误！");
        }
        try {
            // 确认桶是否存在
            bucketName = ensureBucket(bucketName);
            // 下载文件
            GetObjectResponse objectResponse = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            if (null!=response){
                // 添加header
                Headers headers = objectResponse.headers();
                headers.names().forEach(name->{
                    if (FileCommonConst.REPONSE_HEAD_CONTENT_TYPE.equalsIgnoreCase(name)
                            && response.containsHeader(FileCommonConst.REPONSE_HEAD_CONTENT_TYPE)){
                        return;
                    }
                    response.addHeader(name,headers.get(name));
                });
                if (StrUtil.isNotBlank(realFileName)){
                    response.addHeader(FileCommonConst.REPONSE_HEAD_CONTENT_DISPOSITION, StrUtil
                            .format(FileCommonConst.REPONSE_HEAD_CONTENT_DISPOSITION_ATTACHMENT,
                                    URLEncoder.encode(realFileName, "UTF-8")));
                }
            }
            return objectResponse;
        } catch (Exception e) {
            FileExceptionHandler.handleException(e);
        }
        return null;
    }

    @Override
    public String fetchUrl(String bucketName, String fileName,Map<String,String> extraQueryParamsMap) {
        // 容错判断
        if(StrUtil.isBlank(fileName)) {
            throw new BusinessException("下载文件参数有误！");
        }
        try {
            // 确认桶是否存在
            bucketName = ensureBucket(bucketName);
            GetPresignedObjectUrlArgs.Builder builder = GetPresignedObjectUrlArgs
                    .builder()
                    .method(Method.GET)
                    .bucket(bucketName).object(fileName)
                    .expiry(FileCommonConst.URL_EXPIRES);
            if (MapUtil.isNotEmpty(extraQueryParamsMap)){
                builder.extraQueryParams(extraQueryParamsMap);
            }
            return minioClient.getPresignedObjectUrl(builder.build());
        } catch (Exception e) {
            FileExceptionHandler.handleException(e);
        }
        return null;
    }

    @Override
    public String fetchUrl(String bucketName, String fileName) {
        return fetchUrl(bucketName,fileName,new HashMap<>(0));
    }

    @Override
    public boolean exists(String bucketName, String fileName) {
        // 容错判断
        if(StrUtil.isBlank(fileName)) {
            throw new BusinessException("检查文件参数有误！");
        }
        try {
            // 确认桶是否存在
            bucketName = ensureBucket(bucketName);
            // 查看文件元数据
//            ObjectStat stat = minioClient.statObject(bucketName, fileName);
//            return stat != null;
            //Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).startAfter(fileName).build());
            StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
            return stat != null;
        }catch (ErrorResponseException errorResponseException){
          if ("NoSuchKey".equals(errorResponseException.errorResponse().code())){
              return false;
          }
          FileExceptionHandler.handleException(errorResponseException);
        } catch (Exception e) {
            FileExceptionHandler.handleException(e);
        }
        return false;
    }

    @Override
    public void delete(String bucketName, String fileName) {
        // 容错判断
        if(StrUtil.isBlank(fileName)) {
            throw new BusinessException("删除文件参数有误！");
        }
        try {
            // 确认桶是否存在
            bucketName = ensureBucket(bucketName);
            // 删除文件
//            minioClient.removeObject(bucketName, fileName);
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            FileExceptionHandler.handleException(e);
        }
    }

    @Override
    public void deletePath(String bucketName) {
        // 容错判断 桶名为空时也不让删
        if(StrUtil.isBlank(bucketName)) {
            throw new BusinessException("删除文件参数有误！");
        }
        try {
            // 确认桶是否存在
            bucketName = ensureBucket(bucketName);
            // 删除桶
//            minioClient.removeBucket(bucketName);
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            FileExceptionHandler.handleException(e);
        }
    }

    /**
     * 桶ensure
     * @param bucketName 桶名
     * @return 确认后的桶名
     */
    private String ensureBucket(String bucketName){
        // 桶名为空时，使用默认桶
        if(StrUtil.isBlank(bucketName)) {
            bucketName = FileCommonConst.DEFAULT_BUCKET;
        }
        if (log.isDebugEnabled()){
            log.debug("开始检查桶名：[{}]是否存在", bucketName);
        }
        if(isBucketExist(bucketName)) {
            if (log.isDebugEnabled()) {
                log.debug("桶名：[{}]已存在", bucketName);
            }
            return bucketName;
        }
        createBucket(bucketName);
        if (log.isDebugEnabled()){
            log.debug("桶名：[{}]不存在，创建成功", bucketName);
        }
        return bucketName;
    }

    /***
     * Description: 存储桶是否存在
     * @param bucketName: 存储桶名称
     * @return true/false
     * @author : lijie
     * Update By lijie 2021/10/16 14:35
     */
    @Override
    @SneakyThrows
    public boolean isBucketExist(String bucketName){
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /***
     * Description:  创建存储桶
     * @param bucketName : 存储桶名称
     * @return : true/false
     * @author : lijie
     * Update By lijie 2021/10/16 14:35
     */
    @Override
    @SneakyThrows
    public boolean createBucket(String bucketName){
        minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        return true;
    }

    /***
     * Description: 获取访问对象的外链地址
     * @param bucketName : 存储桶名称
     * @param objectName : 对象名称
     * @param expiry : 过期时间(分钟) 最大为7天 超过7天则默认最大值
     * @return : viewUrl
     * @author : lijie
     * Update By lijie 2021/10/16 14:41
     */
    @Override
    @SneakyThrows
    public String getObjectUrl(String bucketName, String objectName, Integer expiry){
        expiry = expiryHandle(expiry);
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(objectName)
                        .expiry(expiry)
                        .build()
        );
    }

    /***
     * Description: 创建上传文件对象的外链
     * @param bucketName : 存储桶名称
     * @param objectName : 欲上传文件对象的名称
     * @param expiry : 过期时间(分钟) 最大为7天 超过7天则默认最大值
     * @return : uploadUrl
     * @author : lijie
     * Update By lijie 2021/10/16 14:41
     */
    @Override
    @SneakyThrows
    public String createUploadUrl(String bucketName, String objectName, Integer expiry){
        ensureBucket(bucketName);
        expiry = expiryHandle(expiry);
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.PUT)
                        .bucket(bucketName)
                        .object(objectName)
                        .expiry(expiry)
                        .build()
        );
    }

    /***
     * Description: 创建上传文件对象的外链
     * @param bucketName : 存储桶名称
     * @param objectName : 欲上传文件对象的名称
     * @return : java.lang.String
     * @author : lijie
     * Update By lijie 2021/10/16 14:42
     */
    @Override
    public String createUploadUrl(String bucketName, String objectName){
        return createUploadUrl(bucketName,objectName,DEFAULT_EXPIRY);
    }

    /***
     * Description: 批量创建分片上传外链
     * @param bucketName : 存储桶名称
     * @param objectMd5 : 欲上传分片文件主文件的MD5
     * @param chunkCount : 分片数量
     * @return : uploadChunkUrls
     * @author : lijie
     * Update By lijie 2021/10/16 14:43
     */
    @Override
    public List<String> createUploadChunkUrlList(String bucketName, String objectMd5, Integer chunkCount){
        if (StrUtil.isBlank(bucketName)){
            bucketName = chunkBucKet;
        }
        if (StrUtil.isBlank(objectMd5)){
            return null;
        }
        objectMd5 += "/";
        if(null == chunkCount || 0 == chunkCount){
            return null;
        }
        List<String> urlList = new ArrayList<>(chunkCount);
        for (int i = 1; i <= chunkCount; i++){
            String objectName = objectMd5 + i + FileCommonConst.CHUCK_FILE_SUFFIX;
            urlList.add(createUploadUrl(bucketName,objectName,DEFAULT_EXPIRY));
        }
        return urlList;
    }

    /***
     * Description: 创建指定序号的分片文件上传外链
     * @param bucketName : 存储桶名称
     * @param objectMd5 : 欲上传分片文件主文件的MD5
     * @param partNumber : 分片序号
     * @return : uploadChunkUrl
     * @author : lijie
     * Update By lijie 2021/10/16 14:44
     */
    @Override
    public String createUploadChunkUrl(String bucketName, String objectMd5, Integer partNumber){
        if (StrUtil.isBlank(bucketName)){
            bucketName = chunkBucKet;
        }
        if (StrUtil.isBlank(objectMd5)){
            return null;
        }
        objectMd5 += "/" + partNumber + FileCommonConst.CHUCK_FILE_SUFFIX;
        return createUploadUrl(bucketName,objectMd5,DEFAULT_EXPIRY);
    }

    /***
     * Description: 获取对象文件名称列表
     * @param bucketName : 存储桶名称
     * @param prefix : 对象名称前缀
     * @param sort : 是否排序(升序)
     * @return : objectNames
     * @author : lijie
     * Update By lijie 2021/10/16 14:45
     */
    @Override
    @SneakyThrows
    public List<String> listObjectNames(String bucketName, String prefix, Boolean sort){
        ListObjectsArgs listObjectsArgs;
        if(StrUtil.isBlank(prefix)){
            listObjectsArgs = ListObjectsArgs.builder()
                    .bucket(bucketName)
                    .recursive(true)
                    .build();
        }else {
            listObjectsArgs = ListObjectsArgs.builder()
                    .bucket(bucketName)
                    .prefix(prefix)
                    .recursive(true)
                    .build();
        }
        Iterable<Result<Item>> chunks = minioClient.listObjects(listObjectsArgs);
        List<String> chunkPaths = new ArrayList<>();
        for (Result<Item> item : chunks){
            chunkPaths.add(item.get().objectName());
        }
        if (sort){
            return chunkPaths.stream().distinct().collect(Collectors.toList());
        }
        return chunkPaths;
    }

    /***
     * Description: 获取对象文件名称列表
     * @param bucketName : 存储桶名称
     * @param prefix : 对象名称前缀
     * @return : objectNames
     * @author : lijie
     * Update By lijie 2021/10/16 14:47
     */
    @Override
    public List<String> listObjectNames(String bucketName, String prefix){
        return listObjectNames(bucketName, prefix, NOT_SORT);
    }

    /***
     * Description: 获取分片文件名称列表
     * @param bucketName : 存储桶名称
     * @param objectMd5 : 对象Md5
     * @return : objectChunkNames
     * @author : lijie
     * Update By lijie 2021/10/16 14:48
     */
    @Override
    public List<String> listChunkObjectNames(String bucketName, String objectMd5){
        if (StrUtil.isBlank(bucketName)){
            bucketName = chunkBucKet;
        }
        if (StrUtil.isBlank(objectMd5)){
            return null;
        }
        return listObjectNames(bucketName,objectMd5,SORT);
    }

    /***
     * Description: 获取分片名称地址HashMap key=分片序号 value=分片文件地址
     * @param bucketName : 存储桶名称
     * @param objectMd5 : 对象Md5
     * @return : objectChunkNameMap
     * @author : lijie
     * Update By lijie 2021/10/16 14:49
     */
    @Override
    public Map<Integer, String> mapChunkObjectNames(String bucketName, String objectMd5){
        if (StrUtil.isBlank(bucketName)){
            bucketName = chunkBucKet;
        }
        if (StrUtil.isBlank(objectMd5)){
            return new HashMap<>();
        }
        List<String> chunkPaths = listObjectNames(bucketName,objectMd5);
        if (CollUtil.isEmpty(chunkPaths)){
            return new HashMap<>();
        }
        Map<Integer, String> chunkMap = new HashMap<>(chunkPaths.size());
        for (String chunkName : chunkPaths) {
            Integer partNumber = Integer.parseInt(chunkName.substring(chunkName.indexOf("/") + 1,chunkName.lastIndexOf(".")));
            chunkMap.put(partNumber,chunkName);
        }
        return chunkMap;
    }

    /***
     * Description: 合并分片文件成对象文件
     * @param chunkBucKetName : 分片文件所在存储桶名称
     * @param composeBucketName : 合并后的对象文件存储的存储桶名称
     * @param chunkNames : 分片文件名称集合
     * @param objectName : 合并后的对象文件名称
     * @return : boolean
     * @author : lijie
     * Update By lijie 2021/10/16 14:50
     */
    @Override
    @SneakyThrows
    public boolean composeObject(String chunkBucKetName, String composeBucketName, List<String> chunkNames,
                                 String objectName){
        if (StrUtil.isBlank(chunkBucKetName)){
            chunkBucKetName = chunkBucKet;
        }
        List<ComposeSource> sourceObjectList = new ArrayList<>(chunkNames.size());
        for (String chunk : chunkNames){
            sourceObjectList.add(
                    ComposeSource.builder()
                            .bucket(chunkBucKetName)
                            .object(chunk)
                            .build()
            );
        }
        minioClient.composeObject(
                ComposeObjectArgs.builder()
                        .bucket(ensureBucket(composeBucketName))
                        .object(objectName)
                        .sources(sourceObjectList)
                        .build()
        );
        return true;
    }

    /***
     * Description: 合并分片文件成对象文件
     * @param bucketName : 存储桶名称
     * @param chunkNames : 分片文件名称集合
     * @param objectName : 合并后的对象文件名称
     * @return : true/false
     * @author : lijie
     * Update By lijie 2021/10/16 14:51
     */
    @Override
    public boolean composeObject(String bucketName, List<String> chunkNames, String objectName){
        return composeObject(chunkBucKet,bucketName,chunkNames,objectName);
    }

    /***
     * Description: 获取chuck的bucketName
     * @param bucketName : 传入的bucketName
     * @return : java.lang.String
     * @author : lijie
     * Update By lijie 2021/10/21 10:39
     */
    @Override
    public String getChuckBucketName(String bucketName){
        if (StrUtil.isNotBlank(bucketName)){
            return bucketName;
        }
        return chunkBucKet;
    }

    /***
     * Description: 获得文件对象的大小
     * @param bucketName : bucket名称
     * @param objectName : 对象名称
     * @return : java.lang.Long
     * @author : lijie
     * Update By lijie 2021/10/22 18:42
     */
    @Override
    @SneakyThrows
    public Long getObjectSize(String bucketName, String objectName){
        StatObjectResponse statObject = minioClient
                .statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());

        return statObject.size();
    }
    /***
     * Description: 批量删除
     * @param deleteFileMap : {bucketName:[fileName1,fileName2...]}
     * @author : lijie
     * Update By lijie 2021/12/9 14:33
     */
    @SneakyThrows
    @Override
    public void batchDelete(Map<String, Set<String>> deleteFileMap) {
        if (MapUtil.isEmpty(deleteFileMap)){
            return;
        }
        Set<Map.Entry<String, Set<String>>> entries = deleteFileMap.entrySet();
        for (Map.Entry<String, Set<String>> entry : entries) {
            String k = entry.getKey();
            Set<String> set = entry.getValue();
            if (CollUtil.isEmpty(set) || StrUtil.isBlank(k)){
                continue;
            }
            List<DeleteObject> objects = new LinkedList<>();
            set.forEach(fileName->objects.add(new DeleteObject(fileName)));
            Iterable<Result<DeleteError>> results =
                    minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(k).objects(objects).build());
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                log.error("Error in deleting object " + error.objectName() + "; " + error.message());
            }
        }
    }

    /***
     * Description: 将分钟数转换为秒数
     * @param expiry : 过期时间(分钟数)
     * @return : int
     * @author : lijie
     * Update By lijie 2021/10/16 14:51
     */
    private static int expiryHandle(Integer expiry){
        expiry = expiry * 60;
        if (expiry > 604800){
            return 604800;
        }
        return expiry;
    }


}
