package cn.com.ctop.common.module.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by JQ.bi on 2020.6.19
 */
@Configuration
@PropertySource("classpath:config.properties")
public class JQCOSUtils {

    private static Logger logger = LoggerFactory.getLogger(JQCOSUtils.class);

    //腾讯云API的密钥Access Key ID
    private static String accessKeyId;

    //腾讯云API的密钥Access Key Secret
    private static String accessKeySecret;

    //腾讯云API的内或外网域名
    private static String endpoint;

    //腾讯云API的bucket名称
    private static String bucketName;

    //腾讯云API的文件夹名称
    private static String folder;

    /**
     * 永久密钥参数初始化
     */
    @Value("${qcloud.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        JQCOSUtils.accessKeyId = accessKeyId;
    }

    @Value("${qcloud.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        JQCOSUtils.accessKeySecret = accessKeySecret;
    }

    @Value("${qcloud.cos.endpoint}")
    public void setEndpoint(String endpoint) {
        JQCOSUtils.endpoint = endpoint;
    }

    @Value("${qcloud.cos.bucketName}")
    public void setBucketName(String bucketName) {
        JQCOSUtils.bucketName = bucketName;
    }

    @Value("${qcloud.cos.folder}")
    public void setFolder(String folder) {
        JQCOSUtils.folder = folder;
    }

    /**
     * 创建COSClient实例
     */
    public static COSClient getCosClient() {
        //初始化用户身份信息（secretId, secretKey）
        COSCredentials cred = new BasicCOSCredentials(accessKeyId, accessKeySecret);
        //设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        Region region = new Region("ap-chongqing");
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cred, clientConfig);
    }

    /**
     * 创建桶
     */
    public static String createBucket(String bucketName) {

        COSClient cosClient = JQCOSUtils.getCosClient();
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        //设置 bucket 的权限为 Private(私有读写), 其他可选有公有读私有写, 公有读写
        createBucketRequest.setCannedAcl(CannedAccessControlList.PublicReadWrite);
        try {
            Bucket bucketResult = cosClient.createBucket(createBucketRequest);
            return bucketResult.getName();
        } catch (CosClientException serverException) {
            logger.error(serverException.getMessage());
        }
        return bucketName;
    }

    /**
     * 删除桶
     */
    public static void deleteBucket(String bucketName) {

        COSClient cosClient = JQCOSUtils.getCosClient();
        cosClient.deleteBucket(bucketName);
    }

    /**
     *  上传对象 文件上传
     */
    public static String uploadObject(File file){

        String resultStr="";
        COSClient cosClient= JQCOSUtils.getCosClient();
        String fileName=file.getName();
        try {
            PutObjectResult putObjectResult = cosClient.putObject(new PutObjectRequest(bucketName, folder+fileName, file));
            resultStr=putObjectResult.getETag();
        }catch (CosClientException serverException){
            logger.error(serverException.getMessage());
        }
        return resultStr;
    }

    /**
     *  上传对象 流上传
     */
    public static String uploadObject(InputStream inputStream, String fileName){

        String resultStr="";
        COSClient cosClient= JQCOSUtils.getCosClient();
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            PutObjectResult putObjectResult = cosClient.putObject(new PutObjectRequest(bucketName, folder+fileName, inputStream,metadata));
            resultStr=putObjectResult.getETag();
        }catch (CosClientException | IOException serverException){
            logger.error(serverException.getMessage());
        }
        return resultStr;
    }
    /**
     *  删除对象
     */
    public static void deleteObject(String dir,String fileName){

        COSClient cosClient= JQCOSUtils.getCosClient();
        try{
            cosClient.deleteObject(bucketName, dir+fileName);
        }catch (CosClientException serverException){
            logger.error(serverException.getMessage());
        }

    }
}
