package cn.hanghui.outapi.platform.common.utils;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.common.utils
 * @class FileUtils
 * @date 2023/10/8 上午10:41
 * @description
 */
@Slf4j
public class FileUtils {

    public static String android_apk_base_path = "file/upload/android";

    public static String pic_base_path = "file/upload/pic";

    public static String pic_photo_path = "file/upload/photo";


    public static String getDirectory(String basePath) {
        return basePath.concat("/").concat(DateUtil.format(new Date(), "yyyyMMdd"));
    }

    public static String saveByCopy(String filePath, MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        return saveByCopy(filename, filePath, file.getInputStream());
    }

    public static String saveByCopy2(String filePath, MultipartFile file) throws IOException {
        String filename = getRandomFileName(file.getOriginalFilename());
        return saveByCopy(filename, filePath, file.getInputStream());
    }

    public static String saveByCopy(String filename, String filePath, InputStream inputStream) throws IOException {
        Path directory = Paths.get(filePath);
        if (!Files.exists(directory)) {
            Files.createDirectories(directory);
        }
        //如果存在文件就先删除
        Files.deleteIfExists(directory.resolve(filename));
        Files.copy(inputStream, directory.resolve(filename));
        return filePath.concat("/").concat(filename);
    }

    public static String getRandomFileName(String fileName) {
        log.info(fileName);
        String suffix = "";
        if (StringUtils.isNotEmpty(fileName)) {
            if (fileName.contains(".")) {
                String[] arr = fileName.split("\\.");
                if (arr.length > 1)
                    suffix = arr[arr.length - 1];
            }
        }
        if (StringUtils.isNotEmpty(suffix)) {
            return SnowflakeIdWorker.getSnowId() + "." + suffix;
        }
        return SnowflakeIdWorker.getSnowId() + ".tmp";
    }



}
