package com.platform.oss;

import com.aliyun.oss.OSSClient;
import com.platform.utils.RRException;
import com.platform.utils.ResourceUtil;
import com.platform.utils.SheelUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云存储
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-03-26 16:22
 */
@Slf4j
public class AliyunCloudStorageService extends CloudStorageService {
    private OSSClient client;

    public AliyunCloudStorageService(CloudStorageConfig config) {
        this.config = config;

        //初始化
        init();
    }

    private void init() {
        client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
                config.getAliyunAccessKeySecret());
    }

    @Override
    public String upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);

        long size = file.getSize();
        if(size > 500000L){
            //在这里将图片压缩
            String localFile = ResourceUtil.getConfigByName("file-backup-path") + "scal_" + fileName;
            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.5f).toFile(localFile);
            File scaleFile = new File(localFile);
            if(null == scaleFile){
                log.error("压缩照片[{}]失败" , fileName);
                return "";
            }
            return upload(new FileInputStream(scaleFile), getPath(config.getAliyunPrefix()) + "." + prefix);
        }else{
            log.info("照片大小小于500kb，不压缩");
            return upload(file.getInputStream() , getPath(config.getAliyunPrefix()) + "." + prefix);
        }

    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(config.getAliyunBucketName(), path, inputStream);
        } catch (Exception e) {
            throw new RRException("上传文件失败，请检查配置信息", e);
        }

        return config.getAliyunDomain() + "/" + path;
    }
}
