//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.testor.biz.sys.file.util;

import com.testor.biz.file.model.domain.SysFile;
import com.testor.biz.file.model.dto.FileDTO;
import com.testor.biz.file.service.SysFileService;
import com.testor.biz.sys.file.config.ObjectItem;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.ListObjectsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveBucketArgs;
import io.minio.RemoveObjectsArgs;
import io.minio.Result;
import io.minio.SetBucketPolicyArgs;
import io.minio.StatObjectArgs;
import io.minio.BucketExistsArgs.Builder;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;

@Component
@Slf4j
public class MinioUtilS {
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucket}")
    private String bucketName;
    @Value("${minio.endpoint}")
    private String address;
    @Value("${apisix.minioroute.url}")
    private String apisixUrl;

    public MinioUtilS() {
    }

    public void existBucket(String name) {
        try {
            boolean exists = this.minioClient.bucketExists((BucketExistsArgs)((Builder)BucketExistsArgs.builder().bucket(name)).build());
            if (!exists) {
                this.minioClient.makeBucket((MakeBucketArgs)((io.minio.MakeBucketArgs.Builder)MakeBucketArgs.builder().bucket(name)).build());
                String config = "{\n\t\"Version\": \"2012-10-17\",\n\t\"Statement\": [{\n\t\t\"Effect\": \"Allow\",\n\t\t\"Principal\": {\n\t\t\t\"AWS\": [\"*\"]\n\t\t},\n\t\t\"Action\": [\"s3:GetBucketLocation\", \"s3:ListBucket\", \"s3:ListBucketMultipartUploads\"],\n\t\t\"Resource\": [\"arn:aws:s3:::zlmy\"]\n\t}, {\n\t\t\"Effect\": \"Allow\",\n\t\t\"Principal\": {\n\t\t\t\"AWS\": [\"*\"]\n\t\t},\n\t\t\"Action\": [\"s3:AbortMultipartUpload\", \"s3:DeleteObject\", \"s3:GetObject\", \"s3:ListMultipartUploadParts\", \"s3:PutObject\"],\n\t\t\"Resource\": [\"arn:aws:s3:::zlmy/*\"]\n\t}]\n}";
                this.minioClient.setBucketPolicy((SetBucketPolicyArgs)((io.minio.SetBucketPolicyArgs.Builder)SetBucketPolicyArgs.builder().bucket(this.bucketName)).config(config).build());
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }

    }

    public Boolean makeBucket(String bucketName) {
        try {
            this.minioClient.makeBucket((MakeBucketArgs)((io.minio.MakeBucketArgs.Builder)MakeBucketArgs.builder().bucket(bucketName)).build());
        } catch (Exception var3) {
            var3.printStackTrace();
            return false;
        }

        return true;
    }

    public Boolean removeBucket(String bucketName) {
        try {
            this.minioClient.removeBucket((RemoveBucketArgs)((io.minio.RemoveBucketArgs.Builder)RemoveBucketArgs.builder().bucket(bucketName)).build());
        } catch (Exception var3) {
            var3.printStackTrace();
            return false;
        }

        return true;
    }

    public List<FileDTO> upload(MultipartFile[] multipartFile) throws Exception {
        List<FileDTO> names = new ArrayList(multipartFile.length);
        MultipartFile[] var3 = multipartFile;
        int var4 = multipartFile.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            MultipartFile file = var3[var5];
            SysFile sysFile = new SysFile();
            FileDTO fileDTO = new FileDTO();
            String fileName = file.getOriginalFilename();
            sysFile.setFileName(fileName);
            fileDTO.setFileName(fileName);
            String fileId = IdHelper.getId32bitTime();
            double size = (double)file.getSize();
            int beginIndex = fileName.lastIndexOf(".");
            String ext = StringHelper.substring(fileName, beginIndex, fileName.length());
            fileName = fileName.replaceAll(" ", "");
            fileName = fileName.replaceAll("-", "");
            fileName = fileName.replaceAll("_", "");
            String[] split = fileName.split("\\.");
            if (split.length > 1) {
                fileName = split[0] + "_" + System.currentTimeMillis() + ext;
            } else {
                fileName = fileName + System.currentTimeMillis();
            }

            InputStream in = null;

            try {
                this.existBucket(this.bucketName);
                in = file.getInputStream();
                this.minioClient.putObject(((PutObjectArgs.builder().bucket(this.bucketName)).object(fileName)).stream(in, in.available(), -1L).contentType(file.getContentType()).build());
                String loginName = ContextUtils.getLoginUser().getUserId();
                if (loginName != null) {
                    sysFile.setCreateBy(loginName);
                    sysFile.setUpdateBy(loginName);
                    sysFile.setFileId(fileId);
                    sysFile.setFileExt(ext);
                    sysFile.setFileDowName(fileName);
                    sysFile.setFileSize(BigDecimal.valueOf(size));
                    String filePath = "";
                    if (this.apisixUrl != null && this.apisixUrl != "") {
                        filePath = this.apisixUrl + "/" + this.bucketName + "/" + fileName;
                        sysFile.setFilePath(filePath);
                    } else {
                        filePath = this.address + "/" + this.bucketName + "/" + fileName;
                        sysFile.setFilePath(filePath);
                    }

                    this.sysFileService.save(sysFile);
                    fileDTO.setFileId(fileId);
                    fileDTO.setFilePath(filePath);
                    fileDTO.setFileDowName(fileName);
                    names.add(fileDTO);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("上传文件失败:"+e.getMessage());
                throw new BusinessException("上传失败");
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException var25) {
                        var25.printStackTrace();
                    }
                }

            }
        }

        return names;
    }

    public ResponseEntity<byte[]> download(String fileName) {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;

        try {
            in = this.minioClient.getObject((GetObjectArgs)((io.minio.GetObjectArgs.Builder)((io.minio.GetObjectArgs.Builder)GetObjectArgs.builder().bucket(this.bucketName)).object(fileName)).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(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException var21) {
                var21.printStackTrace();
            }

            headers.setContentLength((long)bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity(bytes, headers, HttpStatus.OK);
        } catch (Exception var22) {
            var22.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException var19) {
                        var19.printStackTrace();
                    }
                }

                if (out != null) {
                    out.close();
                }
            } catch (IOException var20) {
                var20.printStackTrace();
            }

        }

        return responseEntity;
    }

    public InputStream downloadForIn(String fileName) {
        try {
            return this.minioClient.getObject((GetObjectArgs)((io.minio.GetObjectArgs.Builder)((io.minio.GetObjectArgs.Builder)GetObjectArgs.builder().bucket(this.bucketName)).object(fileName)).build());
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
    }

    public List<ObjectItem> listObjects(String bucketName) {
        Iterable<Result<Item>> results = this.minioClient.listObjects((ListObjectsArgs)((io.minio.ListObjectsArgs.Builder)ListObjectsArgs.builder().bucket(bucketName)).build());
        ArrayList objectItems = new ArrayList();

        try {
            Iterator var4 = results.iterator();

            while(var4.hasNext()) {
                Result<Item> result = (Result)var4.next();
                Item item = (Item)result.get();
                ObjectItem objectItem = new ObjectItem();
                objectItem.setObjectName(item.objectName());
                objectItem.setSize(item.size());
                objectItems.add(objectItem);
            }

            return objectItems;
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }
    }

    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = (List)objects.stream().map((e) -> {
            return new DeleteObject(e);
        }).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = this.minioClient.removeObjects((RemoveObjectsArgs)((io.minio.RemoveObjectsArgs.Builder)RemoveObjectsArgs.builder().bucket(bucketName)).objects(dos).build());
        return results;
    }

    public boolean isObjectExist(String fileName) {
        boolean exist = true;

        try {
            this.minioClient.statObject((StatObjectArgs)((io.minio.StatObjectArgs.Builder)((io.minio.StatObjectArgs.Builder)StatObjectArgs.builder().bucket(this.bucketName)).object(fileName)).build());
        } catch (Exception var4) {
            exist = false;
        }

        return exist;
    }
}
