package com.sdut.labex.controller;

import com.sdut.labex.utils.ResVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@CrossOrigin
public class FileController {
    private final Path fileStorageLocation = Paths.get("/Users/springforest/Downloads/软件实训/uploads/");

    @PostMapping("/upload")
    public ResVo uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResVo.error("上传文件为空");
            }

            // 获取原始文件名的后缀
            String originalFileName = file.getOriginalFilename();
            String extension = originalFileName.substring(originalFileName.lastIndexOf("."));

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + extension;

            // 将文件保存到指定的路径
            Path filePath = this.fileStorageLocation.resolve(newFileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回新的文件名
            Map<String, Object> map = new HashMap<>();
            map.put("fileName", newFileName);
            return ResVo.ok(map);
        } catch (IOException ex) {
            ex.printStackTrace();
            return ResVo.error("文件上传失败");
        }
    }

    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        log.info(fileName);
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            System.out.println(filePath.toUri());
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                log.error("File not found " + fileName);
                return ResponseEntity.notFound().build();
            }

        } catch (MalformedURLException ex) {
            throw new RuntimeException("File not found " + fileName, ex);
        }
    }
}
