package io.hmit.common.utils;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * <h1>文件保存工具类</h1>
 *
 * @author Shen && syf0412@vip.qq.com
 * @since 2022/6/28 14:22
 */
@Slf4j
public class FileUploadUtil {

    /**
     * <h2>文件保存至目标文件夹</h2>
     * @param file 文件
     * @param folder 目标文件夹
     * @return 文件 File 对象
     * @throws IOException IO异常
     */
    public static File upload(MultipartFile file, String folder) throws IOException {
        return upload(file, folder, null, true, true);
    }

    /**
     * <h2>文件保存至目标文件夹</h2>
     * @param file 文件
     * @param folder 目标文件夹
     * @param newFileName 目标名称,需要保留后缀名(留空为原名称)
     * @param ifNeedYearMonth 是否需要添加年月目录
     * @param ifNeedTimestamp 是否需要为文件名添加时间戳
     * @return 文件 File 对象
     * @throws IOException IO异常
     */
    public static File upload(MultipartFile file, String folder, String newFileName,
                              Boolean ifNeedYearMonth, Boolean ifNeedTimestamp) throws IOException {
        if (ObjectUtils.isEmpty(folder)) return null;
        if (!folder.endsWith("/") || !folder.endsWith("\\")) folder += File.separator;
        if (ifNeedYearMonth) folder += getTodayYearMonth() + File.separator;
        File targetFolder = new File(folder);
        if (!targetFolder.exists()) {
            boolean mkdirs = targetFolder.mkdirs();
            if (!mkdirs) return null;
        }
        String targetFilePath = folder
                + (ifNeedTimestamp ? System.currentTimeMillis() + "_" : "")
                + (ObjectUtils.isEmpty(newFileName) ? file.getOriginalFilename() : newFileName);
        File targetFile = new File(targetFilePath);
        file.transferTo(targetFile);
        log.info("file saved to >>> {}", targetFilePath);
        return targetFile;
    }

    /**
     * <h2>获取月份,按月份保存文件</h2>
     * @return 年月字符串,如:202206
     */
    public static String getTodayYearMonth() {
        return DateUtil.format(new Date(), "yyyyMM");
    }

}