package com.jeeplus.test.oss.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

@Slf4j
@Service
public class OSSClientService {

    @Value("${config.accessory.aliyun.bucketName}")
    private String bucketName;

    @Value("${config.accessory.aliyun.endpoint}")
    private String endpoint;

    @Value("${config.accessory.aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${config.accessory.aliyun.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream inStream, String fileDir, String fileName) {
        //初始化OSSClient
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        long start = System.currentTimeMillis();
        //上传文件
        PutObjectResult putResult = ossClient.putObject(bucketName, fileDir + fileName, inStream);
        String ret = putResult.getETag();

        try {
            if (inStream != null) {
                inStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        log.info("上传文件到云服务器成功，文件名：{}，耗时：{}ms",fileName,end-start);
        return ret;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     * 文件下载
     * @param key
     * @param fileName
     */
    public byte[] downBytesByStream(String key, String fileName){
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        byte[] bytes = null;
        BufferedInputStream in = null;
        ByteArrayOutputStream outputStream = null;
        log.info("开始从云服务器加载文件，文件名：{}",fileName);
        try {
            // 创建OSSClient实例
            long start = System.currentTimeMillis();
            OSSObject ossObject = ossClient.getObject(bucketName, key);
            in = new BufferedInputStream(ossObject.getObjectContent());
            outputStream = new ByteArrayOutputStream();
            byte[] car=new byte[1024];
            int L=0;
            while((L=in.read(car))!=-1){
                outputStream.write(car, 0,L);
            }
            bytes = outputStream.toByteArray();
            long end = System.currentTimeMillis();
            log.info("从云服务器加载文件成功，文件名：{}，耗时：{}ms",fileName,end-start);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  bytes;
    }

    public String datePath(){
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        String month = String.valueOf(date.get(Calendar.MONTH)+1);
        String day = String.valueOf(date.get(Calendar.DAY_OF_MONTH));
        String path = "/"+year+"/"+month+"/"+day;
        return path;
    }
}
