package com.jeeplus.common.ossutil;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.baidubce.services.bos.model.PutObjectResponse;
import com.jeeplus.common.config.Global;

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

public class OssClient {
    private final  String accessKey= Global.getConfig("accessKeyId");
    private final  String secretKey= Global.getConfig("accessKeySecret");
    private final  String endpoint= Global.getConfig("endpoint");
    private final  String bucketName= Global.getConfig("bucketName");
    private final  String url = Global.getConfig("aliyunUrl");
    private OSSClient ossClient;

    public OssClient(){
        ossClient = new OSSClient(endpoint, accessKey, secretKey);
    }

    public String  uploadFileToOss(File file,
                                String objectKey) {
        ossClient.putObject(bucketName,objectKey,file);
        return url+objectKey;
    }

    public String  uploadFileToOss(InputStream inputStream,
                                   String objectKey) {
        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectKey, inputStream);
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return url+objectKey;
    }

    public InputStream getObject(String objectKey)
            throws IOException {

        // 获取Object，返回结果为BosObject对象
        OSSObject object = ossClient.getObject(bucketName, objectKey);
        // 获取Object的输入流
        InputStream inputStream = object.getObjectContent();
        return inputStream;
    }

    public void deleteObject(String objectKey){
        ossClient.deleteObject(bucketName,objectKey);
    }


}
