package org.jeecg.modules.minio.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author WangPeng
 * @date 2022/12/30 11:05
 * @description
 */
@Configuration
@Import(MinIoProperties.class)
public class MinIoConfig {

    /**
     * 创建 MinioClient
     * @param properties MinIo配置文件
     * @return MinIo客户端
     */
    @Bean
    public MinioClient minioClient(MinIoProperties properties){
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(properties.getMinioUrl())
                        .credentials(properties.getMinioName(), properties.getMinioPass())
                        .build();
        try {
            //创建文件存储桶
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build())){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
                //设置桶策略为公共的 public
                String policyJson = "{\"" +
                        "Version\":\"2012-10-17\"," +
                        "\"Statement\":[" +
                            "{\"" +
                                "Effect\":\"Allow\"," +
                                "\"Principal\":" + "{\"AWS\":[\"*\"]}," +
                                "\"Action\":[\"s3:ListBucket\"," +
                                "\"s3:ListBucketMultipartUploads\"," +
                                "\"s3:GetBucketLocation\"]," +
                                "\"Resource\":[\"arn:aws:s3:::" + properties.getBucketName() + "\"]}," +
                        "{\"" +
                            "Effect\":\"Allow\"," +
                            "\"Principal\":{\"AWS\":[\"*\"]}," +
                            "\"Action\":[\"s3:PutObject\"," +
                            "\"s3:AbortMultipartUpload\"," +
                            "\"s3:DeleteObject\"," +
                            "\"s3:GetObject\"," +
                            "\"s3:ListMultipartUploadParts\"]," +
                        "\"Resource\":[\"arn:aws:s3:::" + properties.getBucketName() + "/*\"]}]}";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(properties.getBucketName()).config(policyJson).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("MioIo 创建存储桶失败。",e);
        }
        return minioClient;
    }
}
