package com.ruoyi.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constants.HttpConstant;
import com.ruoyi.common.web.exception.ServiceException;
import org.noear.solon.Utils;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.UploadedFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件 工具类
 * @author ruoyi
 */
public class FileUtil extends cn.hutool.core.io.FileUtil {

    /**
     * 上传
     * @param file
     * @param maxSize
     * @param fileType
     * @return
     */
    public static String upload(UploadedFile file, long maxSize, List<String> fileType, String savePath, String requestPrefix) {
        try {
            checkFile(file, maxSize, fileType);
            String fileName = StrUtil.isEmpty(file.getExtension()) ? Utils.guid() : Utils.guid() + "." + file.getExtension();
            String key = File.separator + DateUtil.today() + File.separator + fileName;
            File saveFile = new File(savePath + key);
            if (!saveFile.exists()) {
                if (!saveFile.getParentFile().exists()) {
                    saveFile.getParentFile().mkdirs();
                }
            }
            file.transferTo(saveFile);
            return requestPrefix + key;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 下载
     * @param byteArrayOutputStream
     * @return
     */
    public static void download(ByteArrayOutputStream byteArrayOutputStream) {
        Context ctx = ContextUtil.getContext();
        ctx.contentType(HttpConstant.CONTENT_TYPE_FORM);
        try {
            byteArrayOutputStream.writeTo(ctx.outputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 校验文件
     * @param file
     * @param maxSize
     * @param fileType
     * @throws IOException
     */
    private static void checkFile(UploadedFile file, long maxSize, List<String> fileType) throws IOException {
        if(file == null || file.isEmpty()) {
            throw new ServiceException("文件为空");
        }
        if(maxSize != -1 && file.getContentSize() > maxSize * 1024 * 1024) {
            throw new ServiceException("请上传 " + maxSize + "M 以内的文件");
        }
        if(!fileType.contains(file.getExtension())) {
            throw new ServiceException("不支持此类文件上传");
        }
    }

}
