package com.cool.store.service.impl;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
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.enums.ErrorCodeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.response.ResponseResult;
import com.cool.store.service.OSSService;
import com.cool.store.utils.poi.DateUtils;
import com.cool.store.vo.oss.OssUploadConfigVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @Author suzhuhong
 * @Date 2024/3/28 14:29
 * @Version 1.0
 */
@Service
@Slf4j
public class OSSServiceImpl implements OSSService {

    @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;

    @Override
    public OssUploadConfigVO 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);
            String time = DateUtil.format(new Date(), "yyMM") + "/";
            OssUploadConfigVO result = new OssUploadConfigVO(accessKeyId, encodedPolicy, signature, dir + time, host, String.valueOf(expireEndTime / 1000), cdnUrl);
            return result;
        }catch (Exception e){
            log.info("exception", e);
            throw new ServiceException(ErrorCodeEnum.GET_INFO_ERROR);
        }finally {
            if(Objects.nonNull(client)){
                client.shutdown();
            }
        }
    }
}
