package com.ruoyi.system.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.ruoyi.common.config.OssProperties;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.IOssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 */
@Service
public class OssServiceImpl implements IOssService {
    private static Logger logger = LoggerFactory.getLogger(OssServiceImpl.class);

    @Autowired
    private OSS ossClient;// 注入阿里云oss文件服务器客户端
    @Autowired
    private OssProperties ossProperties;// 注入阿里云OSS基本配置类

    /**
     * 文件上传
     *
     * @param uploadFile
     * @param: uploadFile
     * @return: string
     */
    @Override
    public String upload(MultipartFile uploadFile, String filePath) {
        InputStream inputStream = null;
        try {
            inputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return upload(inputStream, uploadFile.getOriginalFilename(), filePath);
    }

    /**
     * 文件上传
     *
     * @param uploadFile
     * @param filePath
     * @param: uploadFile File
     * @return: string
     */
    @Override
    public String upload(File uploadFile, String filePath) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return upload(inputStream, uploadFile.getName(), filePath);
    }

    private String putFileToOss(String filePath, String bucketName, String originalFilename, InputStream inputStream) {
        try {

            ossClient.putObject(bucketName, filePath + originalFilename, inputStream);
            return "https://"+ossProperties.getBucket() +"." + ossProperties.getEndpoint() + "/"+ filePath + originalFilename;
        }catch (OSSException oe) {
            logger.error(oe.getMessage(), oe);
            return "Error Message: OSSException: " + oe.getErrorMessage();
        } catch (ClientException ce) {
            logger.error(ce.getMessage(), ce);
            return "Error Message: ClientException" + ce.getMessage();
        }
    }

    @Override
    public String upload(InputStream inputStream, String fileName, String filePath) {
        String bucketName = ossProperties.getBucket();

        // 获取文件原名称
//        String originalFilename = IdUtils.fastSimpleUUID() + fileName;
        String originalFilename = IdUtils.fastSimpleUUID()+ fileName.substring(fileName.lastIndexOf("."));

        return putFileToOss(filePath, bucketName, originalFilename, inputStream);
    }

    @Override
    public String uploadFileByUrl(String url, String fileName ,String filePath){
        InputStream inputStream = null;
        try {
            inputStream = new URL(url).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return upload(inputStream,fileName,filePath);
    }

    @Override
    public AssumeRoleResponse getUploadToken() {
        //构建一个阿里云客户端，用于发起请求。
        //构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "LTAI5t8w2RqtGB43m2ccQLw9", "63THVMLns07b1cLXWjnj8RY5FlaiSk");
        IAcsClient client = new DefaultAcsClient(profile);

        //构造请求，设置参数。关于参数含义和设置方法，请参见API参考。
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn("acs:ram::1772789427166655:role/ramossupload");
        request.setRoleSessionName("RamOssUpload");

        //发起请求，并得到响应。
        try {
            AssumeRoleResponse response = client.getAcsResponse(request);
            return response;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
//        if(null==ossClient){
//            ossClient = initOss();
//        }
//        if(null==ossProperties){
//            ossProperties = initOssProperties();
//        }

        String url="http://i.diyigaokao.com/images/201202/201202161100413470.jpg";

        String resUrl= new OssServiceImpl().uploadFileByUrl(url,"pku.jpg","mingxue/universityLog/");
        System.out.println(resUrl);
    }

    private static OssProperties initOssProperties(){
        String endpoint= "oss-cn-beijing.aliyuncs.com";
        String accessKeyId= "LTAI5tShe4frXAuHPGMnEjjY";
        String accessKeySecret= "onbNqpaAfdcKU1fygjd2dQqJWPgpN2";
        String bucket= "mingxuejingbang";
        OssProperties ossProperties = new OssProperties();
        ossProperties.setEndpoint(endpoint);
        ossProperties.setAccessKeyId(accessKeyId);
        ossProperties.setAccessKeySecret(accessKeySecret);
        ossProperties.setBucket(bucket);

        return ossProperties;
    }

    private static OSS initOss(){
        String endpoint= "oss-cn-beijing.aliyuncs.com";
        String accessKeyId= "LTAI5tShe4frXAuHPGMnEjjY";
        String accessKeySecret= "onbNqpaAfdcKU1fygjd2dQqJWPgpN2";


        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

}
