package com.cool.store.oss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
@Slf4j
public class OSSServer {

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

    /**
     * 服务端上传文件的方法
     * ObjectName 为文件存放位置 + 名字，不可包含 bucket
     */
    public String uploadFileServer(InputStream inputStream, String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象
            objectName = dir + objectName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, objectName, inputStream);
            // 创建PutObject请求。
            ossClient.putObject(putObjectRequest);
            return cdnUrl + "/" + objectName;
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.error("Error Message:" + ce.getMessage());
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
        finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    /**
     * 服务端下载文件到内存流
     * @param objectName 自定义路径 + 文件名
     */
    public ByteArrayOutputStream downloadFileServer(String objectName) throws IOException {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucket, dir + objectName);

            // 读取文件内容转为 ByteArrayInputStream
            InputStream objectInputstream = ossObject.getObjectContent();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = objectInputstream.read(buffer)) != -1 ) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();

            // ossObject对象使用完毕后必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            ossObject.close();

        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.error("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            outputStream.close();
        }
        return outputStream;
    }

}
