package com.bonus.system.file.controller;

import com.bonus.common.core.utils.DateTimeHelper;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.system.file.util.IDUtils;
import com.bonus.system.file.util.SystemUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @className:FileUploadController
 * @author:cwchen
 * @date:2025-02-19-13:36
 * @version:1.0
 * @description:文件上传
 */
@RestController
@RequestMapping("/fileUpload/")
@Slf4j
public class FileUploadController {

    @ApiOperation(value = "单文件上传")
    @PostMapping("singleUploadFile")
    public AjaxResult singleUploadFile(@RequestParam(value = "file") MultipartFile file){
        try {
            String fileName = file.getOriginalFilename();
            String suffix= IDUtils.getSuffix(fileName);
            String path="/" + DateTimeHelper.getNowYmd()+"/"+ IDUtils.createID()+suffix;
            String newPath= SystemUtils.getUploadPath()+path;
            File uploadFile = new File(newPath);
            //生成文件夹
            if (!uploadFile.getParentFile().exists()) {
                uploadFile.getParentFile().mkdirs();
            }
            // 存入临时文件
            file.transferTo(uploadFile);
            Map<String, String> map = new HashMap<>();
            map.put("filePath",path);
            map.put("fileName",fileName);
            return AjaxResult.success("上传成功",map);
        }catch (Exception e){
            log.error(e.toString(),e);
            return AjaxResult.error("文件上传异常");
        }
    }
}
