package com.xjrsoft.common.factory;

import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.xjrsoft.config.OSSConfig;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云存储
 *
 * @author tzx
 */
public class AliyunCloudStorageService extends CloudStorageService {
    private OSSClient client;

    public AliyunCloudStorageService(OSSConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        client = new OSSClient(config.getEndpoint(), config.getAccessKey(),
                config.getSecretKey());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(config.getBucketName(), path, inputStream);
        } catch (Exception e){
            client.putObject(config.getBucketName(), path, inputStream);
            throw new RuntimeException("上传文件失败，请检查配置信息", e);
        }
        return   "https://" + config.getBucketName() + StringPool.DOT + config.getEndpoint() + StringPool.SLASH + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getPrefix(), suffix));
    }

    @Override
    public boolean delete(String objectName) {
        try {
            String[] split = objectName.split(config.getBucketName() + StringPool.DOT + config.getEndpoint() + StringPool.SLASH);
            client.deleteObject(config.getBucketName(),split[1]);
        } catch (Exception e){
            throw new RuntimeException("删除文件失败，请检查配置信息", e);
        }
        return true;
    }
}
