package com.mall.thirdParty.client;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyun.oss.common.comm.SignVersion;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "aliyun.oss")
@Data
@Slf4j
public class AliOssClient {

    @Value("${aliyun.oss.endpoint}")
    String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    String accessKeyId;

    @Value("${aliyun.oss.accessKeySecrect}")
    String accessKeySecrect;

    @Value("${aliyun.oss.bucketName}")
    String bucketName;

    @Value("${aliyun.oss.region}")
    String region;

    @Bean("AliOssClient")
    public OSS aliOssClient() {
        CredentialsProvider credentialsProvider = new CredentialsProvider() {
            @Override
            public Credentials getCredentials() {
                return new DefaultCredentials(accessKeyId, accessKeySecrect);
            }

            @Override
            public void setCredentials(Credentials credentials) {
            }
        };

        try {
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            return OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();
        } catch (Exception exception) {
            log.error(exception.getMessage(), exception);
        }

        return null;
    }
}
