package com.zfire.jiasm.syncdata.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.util.Date;


@Slf4j
@Service
public class OSSUtil {

    @Value("${ali.access.key.id}")
    private String ACCESS_KEY_ID;
    @Value("${ali.access.key.secert}")
    private String ACCESS_KEY_SECERT;
    @Value("${ali.oss.bucket.name}")
    private String OSS_BUCKET_NAME;
    @Value("${ali.oss.endpoint.ww}")
    private String OSS_ENDPOINT_WW;
    @Value("${ali.oss.endpoint}")
    private String OSS_ENDPOINT;
    @Value("${ali.oss.type.pic}")
    private String OSS_TYPE_PIC;

    public  boolean uploadFile(String ossObjectKey, File file){
        OSS client = new OSSClientBuilder().build(OSS_ENDPOINT_WW, ACCESS_KEY_ID, ACCESS_KEY_SECERT);
        PutObjectResult putObjectResult = client.putObject(new PutObjectRequest(OSS_BUCKET_NAME, ossObjectKey, file));
        log.info("putObjectResult" + putObjectResult);
        return true;
    }

    public  String getUrl(String key){
        OSS client = new OSSClientBuilder().build(OSS_ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECERT);
        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest ;
        generatePresignedUrlRequest =new GeneratePresignedUrlRequest(OSS_BUCKET_NAME, key);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }

    public  String getUrlWw(String key){
        // OSS clientWw = new OSSClientBuilder().build("https://"+OSS_ENDPOINT_WW,ACCESS_KEY_ID,ACCESS_KEY_SECERT);
        OSS clientWw = new OSSClientBuilder().build(OSS_ENDPOINT_WW,ACCESS_KEY_ID,ACCESS_KEY_SECERT);
        // 设置URL过期时间为1小时
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        GeneratePresignedUrlRequest generatePresignedUrlRequest ;
        generatePresignedUrlRequest =new GeneratePresignedUrlRequest(OSS_BUCKET_NAME, key);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = clientWw.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }

}
