package com.kym.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.kym.common.config.OssConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;


/**
 * 私有写
 * https://oss.console.aliyun.com/bucket/oss-cn-shenzhen/kym-static/overview
 * aliyun 对象存储工具类
 */
public class OssUtil {
    private static Logger logger = LoggerFactory.getLogger(OssUtil.class);
    private static String bucket;

    private OssUtil() {
    }

    private static OSS getClient() {
        OssConfig ossConfig = SpringUtil.getBean(OssConfig.class);
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossConfig.getEndpoint();
        String keyId = ossConfig.getKeyId();
        String keySecret = ossConfig.getKeySecret();
        bucket = ossConfig.getBucket();
        // 创建OSSClient实例。
        return new OSSClientBuilder().build(endpoint, keyId, keySecret);
    }

    /**
     * 文件上传
     *
     * @param fileId 文件在应用系统中的唯一ID
     * @param file   文件
     */
    public static PutObjectResult upload(String fileId, File file) {
        OSS oss = getClient();

        try {
            PutObjectRequest request = new PutObjectRequest(bucket, fileId, file);
            return oss.putObject(request);
        } catch (Exception ce) {
            logger.error("upload>>>" + ce.getMessage(), ce);
        } finally {
            if (oss != null) {
                oss.shutdown();
            }
        }
        return null;
    }


    public static void download(String fileId, File destFile) {
        OSS oss = getClient();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            OSSObject ossObject = oss.getObject(bucket, fileId);
            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            inputStream = ossObject.getObjectContent();
            outputStream = Files.newOutputStream(destFile.toPath());
            IoUtil.copy(inputStream, outputStream);
        } catch (Exception ce) {
            logger.error("download >>>" + ce.getMessage(), ce);
        } finally {
            if (oss != null) {
                oss.shutdown();
            }
            IoUtil.close(outputStream);
            IoUtil.close(inputStream);
        }
    }


    public static void delete(String fileId) {
        OSS oss = getClient();
        try {
            // 删除文件。
            oss.deleteObject(bucket, fileId);
        } catch (Exception ce) {
            logger.error("delete >>>" + ce.getMessage(), ce);
        } finally {
            if (oss != null) {
                oss.shutdown();
            }
        }
    }

}
