package cn.com.poc.common.utils;

import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author Roger Wu
 */
public class FileUtils {

    /**
     * 格式化文件大小
     */
    public static String formatFileSize(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return String.format("%.2f KB", bytes / 1024.0);
        } else if (bytes < 1024 * 1024 * 1024) {
            return String.format("%.2f MB", bytes / (1024.0 * 1024));
        } else {
            return String.format("%.2f GB", bytes / (1024.0 * 1024 * 1024));
        }
    }

    public static File multipartFileToFile(MultipartFile multiFile) {

        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 随机文件名
        fileName = fileName + RandomCodeUtils.generateString(8) + DateUtils.formatDate(new Date(), DateUtils.DATESTYLE);
        try {
            File file = File.createTempFile(fileName, prefix);
            org.apache.commons.io.FileUtils.writeByteArrayToFile(file, multiFile.getBytes());
            return file;
        } catch (IOException e) {
            throw new RuntimeException("multipart file convert to file error：" + e.getMessage());
        }
    }

    /**
     * 将字节流转换成文件
     *
     * @param data
     * @throws Exception
     */
    public static File createTempFile(byte[] data, String fileSuffix) throws IOException {
        if (data != null) {
            File file = File.createTempFile(UUID.randomUUID().toString(), fileSuffix);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data, 0, data.length);
            fos.flush();
            fos.close();
            return file;
        }
        return null;
    }
}
