package com.hzs.common.core.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.hzs.common.core.config.OssConfig;
import com.hzs.common.core.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * OSS 使用工具
 */
@Slf4j
public class OssUtil {

    /**
     * 简单上传 - 文件上传
     *
     * @param file     上传的文件
     * @param path     文件上传路径（不传入默认按年月日创建）
     * @param fileName 文件名称
     */
    public static String uploadMultipartFile(final MultipartFile file, final String path, final String fileName) {
        // 最终名称
        String objectName = OssConfig.getPrefixDirectory() + "/";
        // 存储路径
        if (StringUtils.isNotEmpty(path)) {
            objectName += path;
        } else {
            objectName += DateUtils.parseDateToStr(DateUtils.YAMMER);
        }
        objectName += "/";
        // 文件名称
        if (StringUtils.isNotEmpty(fileName)) {
            objectName += fileName;
        } else {
            objectName += UUID.fastUUID() + "." + UploadUtils.getFileExtension(file);
        }

        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = OssUtil.createClient();
            ossClient.putObject(OssConfig.getBucketName(), objectName, file.getInputStream());
        } catch (OSSException | ClientException e) {
            log.error("OssUtil.uploadMultipartFile oss error: ", e);
            return null;
        } catch (Exception e) {
            log.error("OssUtil.uploadMultipartFile error: ", e);
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return objectName;
    }

    /**
     * 简单上传 - 文件流上传
     *
     * @param inputStream 上传的文件流
     * @param ext         文件对应扩展名
     * @param path        文件上传路径（不传入默认按年月日创建）
     * @return
     */
    public static String uploadFileForStream(final InputStream inputStream, final String ext, final String path, final String fileName) {
        // 最终名称
        String objectName = OssConfig.getPrefixDirectory() + "/";
        // 存储路径
        if (StringUtils.isNotEmpty(path)) {
            objectName += path;
        } else {
            objectName += DateUtils.parseDateToStr(DateUtils.YAMMER);
        }
        objectName += "/";
        // 文件名称
        if (StringUtils.isNotEmpty(fileName)) {
            objectName += fileName;
        } else {
            objectName += UUID.fastUUID() + "." + ext;
        }

        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = OssUtil.createClient();
            ossClient.putObject(OssConfig.getBucketName(), objectName, inputStream);
        } catch (OSSException | ClientException e) {
            log.error("OssUtil.uploadFileForStream oss error: ", e);
            return null;
        } catch (Exception e) {
            log.error("OssUtil.uploadFileForStream error: ", e);
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return objectName;
    }

    /**
     * 简单上传 - 文件上传
     *
     * @param file     上传的文件
     * @param path     文件上传路径（不传入默认按年月日创建）
     * @param fileName 文件名称
     */
    public static String uploadFile(final File file, final String path, final String fileName) {
        // 最终名称
        String objectName = OssConfig.getPrefixDirectory() + "/";
        // 存储路径
        if (StringUtils.isNotEmpty(path)) {
            objectName += path;
        } else {
            objectName += DateUtils.parseDateToStr(DateUtils.YAMMER);
        }
        objectName += "/";
        // 文件名称
        if (StringUtils.isNotEmpty(fileName)) {
            objectName += fileName;
        } else {
            objectName += UUID.fastUUID() + "." + UploadUtils.getFileExtension(file);
        }

        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = OssUtil.createClient();
            ossClient.putObject(OssConfig.getBucketName(), objectName, file);
        } catch (OSSException | ClientException e) {
            log.error("OssUtil.uploadFile oss error: ", e);
            return null;
        } catch (Exception e) {
            log.error("OssUtil.uploadFile error: ", e);
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return objectName;
    }

    /**
     * 删除oss文件
     *
     * @param filePath 文件全路径
     * @return
     */
    public static boolean deleteFile(String filePath) {
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = OssUtil.createClient();
            ossClient.deleteObject(OssConfig.getBucketName(), filePath.replaceAll(OssConfig.getFilePath(), ""));
        } catch (OSSException | ClientException e) {
            log.error("OssUtil.deleteFile oss error: ", e);
            return false;
        } catch (Exception e) {
            log.error("OssUtil.deleteFile error: ", e);
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return true;
    }

    /**
     * 创建ossClient
     *
     * @return
     */
    private static OSS createClient() {
        String accessKeyId = OssConfig.getAccessKeyId();
        String accessKeySecret = OssConfig.getAccessKeySecret();
        String endpoint = OssConfig.getEndpoint();
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

}
