/**
 * @Author: Kane Wang <wangkane@qq.com>
 * @Date: 2025-10-16 09:46:42
 * @LastEditors: Kane Wang
 * @LastModified: 2025-10-16 15:16:57
 * @FilePath: src/main/java/com/cpic/xim/web/controllers/fileupload/SaveUploadFile.java
 * @Description:
 *
 *               Copyright (c) 2025 by Kane All rights reserved
 */
package com.cpic.xim.web.controllers.fileupload;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import org.springframework.web.multipart.MultipartFile;


public class SaveUploadFile
{
    public static HashMap<String, String> saveUploadFile(
            MultipartFile[] files,
            String tempFilePath
    )
      throws ProcessUploadedFileException
    {
        HashMap<String, String> savedFiles = new HashMap<>();
        // File                    dir        = new File( tempFilePath );
        String fileName = "";
        String fullPath;

        if ( !(tempFilePath.endsWith( "/" ) || tempFilePath.endsWith( "\\" )) )
        {
            fullPath = tempFilePath + "/";
        }
        else
        {
            fullPath = tempFilePath;
        }

        try
        {
            for ( MultipartFile file : files )
            {
                // 空文件跳过
                if ( file.isEmpty() )
                {
                    continue;
                }

                // 文件名前加上时间戳，避免覆盖
                Long milliSecond = LocalDateTime.now().toInstant( ZoneOffset.of( "+8" ) ).toEpochMilli();

                fileName = String.valueOf( milliSecond ) + " - " + file.getOriginalFilename();
                File destFile = new File( tempFilePath, fileName );

                file.transferTo( destFile );

                savedFiles.put( fileName, fullPath + fileName );
            }
        }
        catch ( IOException error )
        {
            throw new ProcessUploadedFileException( "临时目录" + tempFilePath + "保存文件" + fileName + "失败!" );
        }

        return savedFiles;
    }
}
