/*
 * @Author: Kane
 * @Date: 2023-01-22 23:11:26
 * @LastEditors: Kane
 * @LastEditTime: 2023-10-23 17:01:29
 * @FilePath: /desktop_archievement_backend/src/main/java/com/cpic/xim/web/controllers/fileupload/FileUpload.java
 * @Description: 用于接受上传文件的Controller。
 * 
 * Copyright (c) ${2022} 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.Vector;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@SuppressWarnings( "unused" )
@Controller
@RequestMapping( path = "/file" )
public class FileUpload
{
    /**
     * 接收上传文件，并保存到临时目录：
     * 1、临时目录下再用sessionID作为子目录保存文件。
     * 2、保存时不更改文件名，会覆盖同名文件。
     * 3、MultipartFile参数形参名称必须和请求form中file标签的name属性一致，否则值为null。
     * 4、返回值为接收结果和文件保存绝对路径。
     * @param taskName 任务名称字符串
     * @param files MultipartFile结构的文件对象
     * @param request HttpServletRequest对象实例
     * @return 返回一个FileUploadResult对象，包含上传结果。
     */
    @RequestMapping( path = "/file-upload.do" )
    @ResponseBody
    public FileUploadResult getUploadFile( @RequestParam( "task-name" ) String taskName,
            @RequestParam( "files" ) MultipartFile file, HttpServletRequest request )
    {
        // session id用来创建临时目录，避免重复
        String sessionID = request.getSession().getId();
        FileUploadResult result = new FileUploadResult();
        Vector<String> fileNames = new Vector<String>();

        result.setSuccess( true );
        result.setMessage( "上传成功!" );

        String filePath = request.getServletContext().getRealPath( "/temp/upload/" + sessionID );
        File dir = new File( filePath );

        if ( !dir.mkdirs() )
        {
            
        }

        // 检查文件长度，如果为0则跳过
        if ( file.isEmpty() )
        {
            result.setSuccess( false );
            result.setMessage( "不允许上传空文件。" );
        }
        else
        {
            // 保存文件到临时目录
            Long milliSecond =
                    LocalDateTime.now().toInstant( ZoneOffset.of( "+8" ) ).toEpochMilli();
            String fileName = String.valueOf( milliSecond ) + file.getOriginalFilename();
            // String fileName = file.getOriginalFilename();
            File destFile = new File( filePath, fileName );

            try
            {
                file.transferTo( destFile );
                // 把上传文件的绝对路径保存，返回给前端
                fileNames.add( destFile.getAbsolutePath() );

                result.setSuccess( true );
                result.setMessage( "上传成功" );
                result.setFileList( fileNames );
            }
            catch ( IOException error )
            {
                result.setSuccess( false );
                result.setMessage( "上传失败，原因：" + error.getMessage() );
            }
        }

        return result;
    }
}
