package com.ywt.mg.domain.models;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.ywt.mg.core.utils.Checker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;

/**
 * @author daiyihua
 * @create 2018-07-27 上午10:26
 * @desc OSS直传参数设置
 **/
@Component
public class OssSettring {

    private static Logger logger = LoggerFactory.getLogger(OssSettring.class);

    // Endpoint外网访问域名
    public static final String endpoint = "oss-cn-shenzhen.aliyuncs.com";

    // 用户请求的accessid
    public static final String accessKeyId = "LTAI6J2CnMZpFOMA"; // 6MKOqxGiGU4AUk44

    public static final String accessKeySecret = "S5imKc18OwO82527mZtSoUqr3De06f";    //ufu7nS8kS59awNihtjSonMETLI0KLy

    public static final String fileBucketName = "ywt-files";

    public String uploadFile(String localPath, String saveFileName){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 接收返回的url
        String url = "";
        try {
            File file = new File(localPath);
            if (Checker.isNone(file)) {
                return "文件不存在";
            }

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(fileBucketName, saveFileName, file);
            // 上传文件
            ossClient.putObject(putObjectRequest);
            // 获取文件url
            // url过期时间
            Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7);
            url = ossClient.generatePresignedUrl(fileBucketName, saveFileName, date).toString();
            return url;
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message:" + oe.getErrorMessage());
            logger.info("Error Code:" + oe.getErrorCode());
            logger.info("Request ID:" + oe.getRequestId());
            logger.info("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "";
    }

}
