package cn.gov.customs.wxjy.ibmmq.controller;

import cn.gov.customs.wxjy.ibmmq.service.IFileHandlerService;
import lombok.AllArgsConstructor;
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.io.IOException;
import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("/api/file")
@AllArgsConstructor
public class FileTransferController {

    private IFileHandlerService fileHandlerService;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, String savePath) {
        try {
            // 保存临时文件
            // File tempFile = File.createTempFile("upload-", file.getOriginalFilename());
            File tempFile = new File("d:/home/" + file.getOriginalFilename());
            file.transferTo(tempFile);

            // 发送文件
            String fileId = fileHandlerService.sendFile(tempFile.getAbsolutePath(), savePath);

            // 删除临时文件
            tempFile.delete();

            return "文件上传并发送成功，FileID: " + fileId;
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "文件上传失败: " + e.getMessage();
        }
    }
}
