package com.bonus.hn.bearing.capacity.backstage.manager.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.core.io.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * 包名称：com.bonus.hn.bearing.capacity.backstage.manager.controller
 * 类名称：Download
 * 类描述：
 * 创建人：@author xxxxxx
 * 创建时间：2023年11月16日 09:35
 */
@RestController
@RequestMapping("/download")
public class DownloadController {
    private static final String DESTINATION_DIRECTORY = "C://files/proProcess/";
    @GetMapping("/download")
    @ApiOperation(value = "工程进度管理-更新项目进度")
    public ResponseEntity<Resource> downloadFile(@RequestParam("filePath") String filePath) throws IOException {
        File sourceFile = new File(filePath);
        File destinationDirectory = new File(DESTINATION_DIRECTORY);

        // Create the destination directory if it doesn't exist
        if (!destinationDirectory.exists()) {
            destinationDirectory.mkdirs();
        }
        // Copy the source file to the destination directory
        Path destinationPath = new File(destinationDirectory, sourceFile.getName()).toPath();
        Files.copy(sourceFile.toPath(), destinationPath, StandardCopyOption.REPLACE_EXISTING);

        Resource resource = new FileSystemResource(destinationPath.toFile());

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + sourceFile.getName());

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(sourceFile.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    /**
     * 根据文件名获取对应的MIME类型
     * @param fileName 文件名
     * @return 文件类型
     */
    private String getContentType(String fileName) {
        if (fileName.endsWith(".rar")) {
            return "application/x-rar-compressed";
        } else if (fileName.endsWith(".zip")) {
            return "application/zip";
        } else if (fileName.endsWith(".doc")) {
            return "application/msword";
        } else if (fileName.endsWith(".docx")) {
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        } else if (fileName.endsWith(".pdf")) {
            return "application/pdf";
        } else {
            return "application/octet-stream";
        }
    }
}
