package cn.reghao.bnt.web.devops.aliyun.service;

import cn.reghao.bnt.web.devops.aliyun.model.po.AliyunAccount;
import cn.reghao.bnt.web.devops.aliyun.model.vo.StsToken;
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.sts20150401.models.AssumeRoleResponseBody;
import com.aliyun.tea.TeaException;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author reghao
 * @date 2024-08-30 14:31:24
 */
@Service
public class AliyunService {
    private AliyunOss aliyunOss;
    private com.aliyun.sts20150401.Client stsClient;
    private String bucket;
    private String region;
    private String roleArn;
    private String ossDomain;
    private String myDomain;

    // TODO 使用 AliyunService 前需要先调用 AliyunService#init 初始化
    public void init(AliyunOss aliyunOss, AliyunAccount aliyunAccount) throws Exception {
        this.aliyunOss = aliyunOss;
        String stsEndpoint = aliyunAccount.getEndpoint();
        String accessKeyId = aliyunAccount.getAccessKeyId();
        String accessKeySecret = aliyunAccount.getAccessKeySecret();
        this.bucket = aliyunAccount.getBucketName();
        this.region = aliyunAccount.getRegion();
        this.roleArn = aliyunAccount.getRoleArn();
        this.ossDomain = String.format("%s.%s.aliyuncs.com", bucket, region);
        this.myDomain = System.getenv("MY_DOMAIN");

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = stsEndpoint;
        this.stsClient = new com.aliyun.sts20150401.Client(config);
    }

    public StsToken getStsToken() {
        com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest();
        assumeRoleRequest.setRoleArn(roleArn);
        assumeRoleRequest.setRoleSessionName("role_session_test");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            AssumeRoleResponse roleResponse = stsClient.assumeRoleWithOptions(assumeRoleRequest, runtime);
            AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials credentials = roleResponse.getBody().getCredentials();
            String accessKeyId = credentials.getAccessKeyId();
            String accessKeySecret = credentials.getAccessKeySecret();
            String expiration = credentials.getExpiration();
            String securityToken = credentials.getSecurityToken();

            String ossUrl = String.format("http://%s.%s.aliyuncs.com/", bucket, region);
            String objectId = UUID.randomUUID().toString().replace("-", "");
            return new StsToken(bucket, region, ossUrl, objectId, accessKeyId, accessKeySecret, expiration, securityToken);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;
    }

    public String getSignedUrl(String objectName) {
        String signedUrl = aliyunOss.getSignedUrl(objectName);
        if (signedUrl != null) {
            return signedUrl.replace(ossDomain, myDomain);
        }

        return null;
    }
}
