package com.fdkankan.ucenter.config;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.fdkankan.fyun.face.FYunFileServiceInterface;
import com.fdkankan.ucenter.common.constants.NacosProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import java.net.URL;

@Configuration
@RefreshScope
public class FyunConfig {

    @Value("${fyun.type}")
    public String type;
    @Value("${fyun.key}")
    public String key;
    @Value("${fyun.secret}")
    public String secret;
    @Value("${fyun.bucket}")
    public String bucket;
    @Value("${fyun.endPoint}")
    public String endPoint;
    @Value("${fyun.host}")
    public String host;

    @Autowired
    FYunFileServiceInterface fYunFileServiceInterface;

    public OSSClient build(){
        return new OSSClient(endPoint.replace("-internal",""),key,secret);
    }

    public URL getPresignedUrl( String url) {
        if(!"oss".equals(type)){
            return fYunFileServiceInterface.getPresignedUrl(url);
        }
        java.util.Date expiration = new java.util.Date();
        long expTimeMillis = expiration.getTime();
        expTimeMillis += 1000 * 60 * 60 * 8;
        expiration.setTime(expTimeMillis);
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket, url);
        generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
        generatePresignedUrlRequest.setExpiration(expiration);
        OSSClient build = this.build();
        URL url1 = build.generatePresignedUrl(generatePresignedUrlRequest);
        build.shutdown();
        return url1;
    }
}
