package com.brframework.commonwebbase.service;

import com.brframework.commonoss.core.AliYunOSSClient;
import com.brframework.commonoss.core.OSSMessage;
import com.brframework.commonoss.core.sts.AliYunSTSClient;
import com.brframework.commonoss.core.sts.AliYunSTSPolicyBuilder;
import com.brframework.commonoss.core.sts.AliYunSTSPolicyStatementBuilder;
import com.brframework.commonoss.core.sts.STSAuthorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * 管理后台oss
 * @author xu
 * @date 2019年8月28日16:01:07
 */
@Service
public class OSSService {

    @Autowired
    AliYunOSSClient ossClient;
    @Autowired
    AliYunSTSClient stsClient;

    /**
     * 所有bucket的写权限
     * @return
     */
    public OSSMessage adminSts(){
        String prefix = "admin-file";
        String bucket = ossClient.getDefaultBucketName();
        STSAuthorization sts = stsClient.getSTSAuthorization(AliYunSTSPolicyBuilder.builder()
                .statement(AliYunSTSPolicyStatementBuilder.builder()
                        .effect("Allow")
                        .action("oss:*")
                        .resource("acs:oss:*:*:" + bucket + "/" + prefix + "/*")
                )
        );

        return ossClient.getOSSMessage(sts, bucket, prefix);
    }


    /**
     * 只有写入权限
     * @return
     */
    public OSSMessage apiSts(){
        String prefix = "app-file";
        String bucket = ossClient.getDefaultBucketName();
        STSAuthorization sts = stsClient.getSTSAuthorization(AliYunSTSPolicyBuilder.builder()
                .statement(AliYunSTSPolicyStatementBuilder.builder()
                        .effect("Allow")
                        .action("oss:PutObject")
                        .resource("acs:oss:*:*:" + bucket + "/" + prefix + "/*")
                )
        );

        return ossClient.getOSSMessage(sts, bucket, prefix);
    }

    public void upload(String key, File file){
        ossClient.upload(key, file);
    }


    public String imageHandle(String imageUrl){
        return ossClient.genUrl(imageUrl);
    }

}
