package com.slodon.b2b2c.upload;

import com.slodon.b2b2c.core.config.DomainUrlUtil;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.upload.base.Upload;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.multipart.MultipartFile;

/**
 * minio上传文件
 */
@Slf4j
public class MinioUpload extends Upload {

    public MinioUpload(StringRedisTemplate stringRedisTemplate) {
        super(stringRedisTemplate);
    }

    /**
     * 上传文件
     *
     * @param file     要上传的文件
     * @param fileName 文件名，必须以'/'开头，如 /images/seller/goods/0Kwf1FTdCzZo5J7Siph.png
     */
    @Override
    public String upload(MultipartFile file, String fileName) {
        //获取配置
        String minioUrl = stringRedisTemplate.opsForValue().get("minio_url");//minio地址
        int port = Integer.parseInt(stringRedisTemplate.opsForValue().get("minio_port"));//minio端口
        String minioS3Region = stringRedisTemplate.opsForValue().get("minio_s3_region");//兼容S3时需要设置
        String accessKey = stringRedisTemplate.opsForValue().get("minio_access_key");
        String secretKey = stringRedisTemplate.opsForValue().get("minio_secret_key");
        String bucketName = stringRedisTemplate.opsForValue().get("minio_bucket_name");//存储桶名称

        //从fileName中获取bucketName和objectName
//        String reg = "/(\\S*?)(/\\S*)";
//        String folderName = fileName.replaceFirst(reg, "$1");
//        //String objectName = fileName.replaceFirst(reg, "$2");

        try {
            // 1. 配置 MinIO/S3 客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioUrl, port, true)
                    // 替换为您的MinIO服务器地址
                    .credentials(accessKey, secretKey) // 您的访问密钥和秘密密钥
                    .region(minioS3Region) // 设置区域
                    .build();
            //查询桶是否已存在，不存在则创建桶
            // 2. 检查桶是否存在，不存在则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build());

            if (!found) {
                log.info("Bucket does not exist, creating new bucket:{}", bucketName);
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .region(minioS3Region)
                        .build());
            }

            //上传文件
            log.info("Uploading file to bucket...");
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            log.info("File uploaded successfully");
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new MallException("上传文件失败");
        }
        return DomainUrlUtil.SLD_IMAGE_RESOURCES + fileName;
    }
}
