package com.liang.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;


@RestController
@RequestMapping("/fileDownload")
public class FileDownloadController {

    /**
     * 任务书模块附件的模板下载，不太好放入ProProjectController于是单独放在了这里
     *
     * @return
     * @throws IOException
     */
//    @GetMapping("/download")
//    public ResponseEntity<Resource> downloadFile() throws IOException {
//        ClassPathResource resource = new ClassPathResource("upload/202308/模版表.docx");
//
//        return ResponseEntity.ok()
//                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
//                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
//                .body(resource);
//    }
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile() throws IOException {
        ClassPathResource resource = new ClassPathResource("upload/202308/模版表.docx");

        InputStream inputStream = resource.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }

        byte[] fileContent = outputStream.toByteArray();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "模板表.docx"); // 设置下载文件名

        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }
}
