package cn.com.qmth.examcloud.tool.utils.oss;

import cn.com.qmth.examcloud.tool.utils.FileHelper;
import cn.com.qmth.examcloud.tool.utils.StatusException;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class OssHelper {

    private final static Logger log = LoggerFactory.getLogger(OssHelper.class);

    private OssConfig config;

    public OssHelper(OssConfig config) {
        this.config = config;
    }

    public OssFileInfo writeFile(String filePath, File file) {
        filePath = fixOssFilePath(filePath);
        OSS client = getClient(config);
        try {
            client.putObject(config.getBucket(), filePath, file);
        } catch (Exception e) {
            log.error("文件上传失败！filePath:{} err:{}", filePath, e.getMessage());
            throw new StatusException("文件上传失败！");
        } finally {
            try {
                client.shutdown();
            } catch (Exception e) {
                // ignore
            }
        }

        filePath = OssConfig.SEPARATOR + filePath;
        OssFileInfo result = new OssFileInfo();
        result.setFileName(FileHelper.getFileName(filePath));
        result.setFilePath(filePath);
        result.setFileUrl(config.getUrlPrefix() + filePath);
        return result;
    }

    private OSS getClient(OssConfig config) {
        try {
            ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
            configuration.setMaxErrorRetry(1);

            OSS client = new OSSClientBuilder().build(config.getEndpoint(),
                    config.getAccessKeyId(), config.getAccessKeySecret(), configuration);
            // client.setBucketTransferAcceleration(config.getBucket(), true);
            return client;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new StatusException("OSS客户端初始化失败！");
        }
    }

    private String fixOssFilePath(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            throw new StatusException("文件存储路径不能为空！");
        }

        // OSS存储路径不允许以 / 开头，需要去掉 /
        if (filePath.startsWith("/")) {
            return filePath.substring(1);
        }
        return filePath;
    }

}
