package com.cool.store.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.cool.store.response.ResponseResult;
import com.cool.store.vo.oss.OssUploadConfigVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Date;
import java.util.Objects;

/**
 * @author zhangchenbiao
 * @FileName: OssClientController
 * @Description:
 * @date 2023-06-01 11:25
 */
@RestController
@RequestMapping({"/oss"})
@Slf4j
public class OssClientController {

    @Value("${oss.accessKeyId:null}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret:null}")
    private String accessKeySecret;
    @Value("${oss.endpoint:null}")
    private String endpoint;
    @Value("${oss.bucket:null}")
    private String bucket;
    @Value("${cdn.url:null}")
    private String cdnUrl;
    @Value("${oss.file.dir:null}")
    private String dir;

    @GetMapping("/getUploadFileConfig")
    public ResponseResult getUploadFileConfig(){
        // host的格式为 bucketname.endpoint
        String host = "https://" + bucket + "." + endpoint;

        OSS client = null;
        try {
            client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            long expireTime = 300;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String signature = client.calculatePostSignature(postPolicy);
            OssUploadConfigVO result = new OssUploadConfigVO(accessKeyId, encodedPolicy, signature, dir, host, String.valueOf(expireEndTime / 1000), cdnUrl);
            return ResponseResult.success(result);
        }catch (Exception e){
            log.info("exception", e);
        }finally {
            if(Objects.nonNull(client)){
                client.shutdown();
            }
        }
        return ResponseResult.success();
    }
}
