package com.njcn.common.utils;

import cn.hutool.core.text.StrPool;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2023年04月19日 16:02
 */
public class FileUtil {

    /***
     * 随机生成文件名
     * @author hongawen
     * @date 2023/4/19 16:02
     * @param originalFileName 原文件名
     * @return String
     */
    public static String generateFileName(String originalFileName) {
        String suffix;
        if (originalFileName.contains(StrPool.DOT)) {
            suffix = originalFileName.substring(originalFileName.lastIndexOf(StrPool.DOT));
        } else {
            suffix = StrPool.DOT + originalFileName;
        }
        return UUID.randomUUID().toString().replace("-", "").toUpperCase() + suffix;
    }

    /**
     * MultipartFile 转 String
     *
     * @param multipartFile 原字符串
     * @return 成功标记
     */
    public static String multipartFileToString(MultipartFile multipartFile) {
        StringBuilder txtResult = new StringBuilder();
        try (
                InputStreamReader isr = new InputStreamReader(multipartFile.getInputStream(), StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr)
        ) {
            String lineTxt;
            while ((lineTxt = br.readLine()) != null) {
                txtResult.append(lineTxt);
            }
            return txtResult.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }


}
