package com.younike.common.utils.oss.service.impl;


import com.younike.common.bean.VideoUploadResult;
import com.younike.common.utils.date.DatePattern;
import com.younike.common.utils.date.DateUtils;
import com.younike.common.utils.oss.AliyunOSSUtil;
import com.younike.common.utils.oss.service.IStorageService;
import lombok.extern.log4j.Log4j2;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * OSS存储服务
 *
 * @author chenpengfei
 */
@Service
@Log4j2
public class StorageServiceImpl implements IStorageService {

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Value("${oss.filepath}")
    private String filePath;

    @Value("${oss.filehost}")
    String fileHost;

    @Override
    public String store(MultipartFile file) {

        log.info("文件上传");
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        try {
            if (file != null) {
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    commpressPicCycle(file,newFile,0.6);

                    // 根据不同文件文件类型-不同日期生成不同文件夹
                    Date date = new Date();
                    String datePath = DateUtils.formatDateByStyle(date, DatePattern.CN_DATE_BASIC_STYLE4.getDatePattern());

                    String timeStamp = String.valueOf(System.currentTimeMillis());
                    filename = timeStamp + filename.substring(filename.lastIndexOf("."), filename.length());

                    String path;
                    if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png")) {
                        // images
                        path = filePath + "images/" + datePath + "/" + filename;
                    } else if (filename.endsWith(".mp4")) {
                        // video
                        path = filePath + "images/" + datePath + "/" + filename;
                    } else {
                        path = filePath + "other/" + datePath + "/" + filename;
                    }
                    // 上传到OSS
                    String uploadUrl = aliyunOSSUtil.upLoad(newFile, path);
                    newFile.delete();
                    if (uploadUrl != null) {
                        return uploadUrl;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

        }

        return null;
    }

    public static void commpressPicCycle(MultipartFile oldFile , File newFile,double quality) throws IOException {
        FileOutputStream os = new FileOutputStream(newFile);
        //判断大小,如果小于2M,不压缩,如果大于等于2M,压缩
        if(oldFile.getSize() <= 2097152){
            Thumbnails.of(oldFile.getInputStream())
                    .scale(1f) //图片大小（长宽）压缩比例 从0-1，1表示原图
                    .outputQuality(1) //图片质量压缩比例 从0-1，越接近1质量越好
                    .toOutputStream(os);
            return;
        }
        Thumbnails.of(oldFile.getInputStream())
                .scale(quality) //图片大小（长宽）压缩比例 从0-1，1表示原图
                .outputQuality(0.6f) //图片质量压缩比例 从0-1，越接近1质量越好
                .toOutputStream(os);
        long fileSize = newFile.length()/1024+1;
        if(fileSize <= 2097152){
            return;
        }
        quality -= 0.05;
        if(quality <= 0){
            return;
        }
        commpressPicCycle(oldFile,newFile,quality);
    }

    @Override
    public VideoUploadResult storeVideo(MultipartFile file) {
        log.info("视频上传");
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        try {
            if (file != null) {
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);

                    // 根据不同文件文件类型-不同日期生成不同文件夹
                    Date date = new Date();
                    String datePath = DateUtils.formatDateByStyle(date, DatePattern.CN_DATE_BASIC_STYLE4.getDatePattern());

                    String timeStamp = String.valueOf(System.currentTimeMillis());
                    filename = timeStamp + filename.substring(filename.lastIndexOf("."), filename.length());

                    String path;
                    if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png")) {
                        // images
                        path = filePath + "images/" + datePath + "/" + filename;
                    } else if (filename.endsWith(".mp4")) {
                        // video
                        path = filePath + "video/" + datePath + "/" + filename;
                    } else {
                        path = filePath + "other/" + datePath + "/" + filename;
                    }
                    // 上传到OSS
                    VideoUploadResult upload = aliyunOSSUtil.videoUpload(newFile, path);
                    if (upload != null) {
                        upload.setVideoUrl(fileHost + upload.getVideoUrl());
                        upload.setSignedUrl(fileHost + upload.getSignedUrl());
                    }
                    newFile.delete();
                    if (upload != null) {
                        return upload;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

        }

        return null;
    }

    @Override
    public String uploadExcel(File file) {
        log.info("excel--上传");

        try {
            if (file != null) {
                String datePath = DateUtils.formatDateByStyle(new Date(), DatePattern.CN_DATE_BASIC_STYLE4.getDatePattern());
                String path = filePath + "excel/" + datePath + "/" + file.getName();

                // 上传到OSS
                String uploadUrl = aliyunOSSUtil.upLoad(file, path);

                file.delete();
                if (uploadUrl != null) {
                    return uploadUrl;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

        }

        return null;
    }
    /**
     * 2022-2-9 Another 上传 filename 是 blob 的文件
     * @param file filename 是 blob 的文件
     * @return 文件路径
     */
    @Override
    public String storeBlob(MultipartFile file) {
        log.info("filename 是 blob 的文件上传");
        if (file == null) {
            return "上传文件为空";
        }

        String filename = file.getOriginalFilename();
        if (!"blob".equals(filename)) {
            return "调用方法出错，请更换调用方法";
        }
        try {
            File newFile = new File("a"+filename);
            FileOutputStream os = new FileOutputStream(newFile);
            commpressPicCycle(file,newFile,0.6);

            // 根据不同文件文件类型-不同日期生成不同文件夹
            Date date = new Date();
            String datePath = DateUtils.formatDateByStyle(date, DatePattern.CN_DATE_BASIC_STYLE4.getDatePattern());

            String timeStamp = String.valueOf(System.currentTimeMillis());
            String path = filePath + "other/" + datePath + "/" + filename + "/" + timeStamp;
            // 上传到OSS
            String uploadUrl = aliyunOSSUtil.upLoad(newFile, path);
            newFile.delete();
            if (uploadUrl != null) {
                return uploadUrl;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }
}
