package com.ruoyi.file.utils;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.file.object.UploadResult;
import com.ruoyi.file.object.UploadTask;

import java.io.File;

/**
 * 文件上传工具类
 *
 * @author ruoyi
 */
public class FileUploadFunc
{
    /**
     * 默认大小 50M
     */
    private static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 图片压缩红线 kb
     */
    private static final long DES_FILE_SIZE = 1024;

    /**
     * 默认的文件名最大长度 100
     */
    private static final int DEFAULT_FILE_NAME_LENGTH = 100;

    private static final String THUMBNAIL_DIRECTORY = "thumbnail"; // 存放目录名称
    private static final int THUMBNAIL_SIZE = 128; // px // 大小
    private static final boolean THUMBNAIL_CROP = true; // 是否裁剪中间正方形区域
    private static final float THUMBNAIL_QUALITY = 0.8f; // 质量

    private static final boolean COMPRESS_IMAGE = true;

    public static File GetFile(String filePath)
    {
        File desc = new File(filePath);

        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    private static void AssertUploadTask(UploadTask task)
    {
        try
        {
            // 文件名长度
            if (task.getFile().getOriginalFilename().length() > DEFAULT_FILE_NAME_LENGTH) {
                throw new FileNameLengthLimitExceededException(DEFAULT_FILE_NAME_LENGTH);
            }
            // 校验类型、大小
            FileUploadUtils.assertAllowed(task.getFile(), MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static UploadResult Upload(UploadTask task)
    {
        AssertUploadTask(task);

        String extension = task.OriginFileExtension();
        byte[] bytes = task.UploadBytes();
        byte[] writeBytes = bytes;
        boolean needThumbnail = MimeTypeUtils.isImageExtension(extension);

        task.setThumbnailFolderName(THUMBNAIL_DIRECTORY);

        // 大于1M的图片文件进行压缩
        if (needThumbnail)
        {
            if(COMPRESS_IMAGE)
            {
                writeBytes = ImageUtils.compressPicForScale(bytes, DES_FILE_SIZE);
            }

            boolean isAngle = false;
            if(isAngle) // 旋转保存
            {
                //根据图片角度自动识别翻转
                //int angle = ImageUtils.getAngle(ImageUtils.getExif(file.getInputStream()));
                // 旋转可能是自动识别手机效果的，此处不是原生，所以写死
                int angle = 3;
                writeBytes = ImageUtils.rotateImage(writeBytes, extension, angle);
            }
        }

        UploadResult result = task.GenerateResult();
        result.setState(1);

        // 存储
        File desc = GetFile(result.getFilePath());
        FileUtil.writeBytes(writeBytes, desc);
        result.setFileSize(writeBytes.length);

        // 缩略图
        if(needThumbnail)
        {
            File thumbFile = GetFile(result.getThumbnailFilePath());
            if(!ImageUtils.generateThumbnail(bytes, thumbFile, THUMBNAIL_SIZE, THUMBNAIL_CROP, THUMBNAIL_QUALITY))
            {
                result.setThumbnailFilePath(result.getThumbnailFilePath())
                        .setThumbnailFileUrl(result.getThumbnailFileUrl())
                        .setThumbnailFileSize(result.getFileSize())
                        ;
            }
            else
                result.setThumbnailFileSize(thumbFile.length());
        }

        result.Finish(true);

        return result;
    }

}
