package com.kingdee.shr.custom.sendfile;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GetElectronFile {


    public static void handlePdfFile(String dir, String fileName, HttpServletResponse response, boolean isDownload) throws IOException {
        String home = System.getProperty("EAS_HOME"); // 获取 EAS 根目录
        String fileDir = home + "/server/deploy/easweb.ear/shr_web.war/tmp/electronicAttachment/" + dir;
        fileName = URLEncoder.encode(fileName, "UTF-8");
        File pdfFile = new File(fileDir, fileName);

        // 检查文件是否存在
        if (!pdfFile.exists() || !pdfFile.isFile()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件未找到或已失效");
            return;
        }

        // 设置响应类型和头部信息
        response.setContentType("application/pdf");
        String contentDisposition = isDownload ? "attachment" : "inline";
        response.setHeader("Content-Disposition", contentDisposition + "; filename=\"" + pdfFile.getName() + "\"");
        response.setContentLength((int) pdfFile.length());

        // 读取文件并写入响应流
        try (FileInputStream fileInputStream = new FileInputStream(pdfFile);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件无法读取或发送");
        }
    }


    public ResponseEntity<Resource> viewPdf(String dir, String fileName) throws IOException {
        String home = System.getProperty("EAS_HOME"); // 获取 EAS 根目录
        String fileDir = home + "/server/deploy/easweb.ear/shr_web.war/tmp/electronicAttachment/" + dir;
        fileName = URLEncoder.encode(fileName, "UTF-8");
        Path filePath = Paths.get(fileDir, fileName);
        // 检查文件是否存在
        if (!Files.exists(filePath)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        // 检查文件是否可读
        if (!Files.isReadable(filePath)) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        // 读取文件内容到字节数组中
        byte[] fileContent = Files.readAllBytes(filePath);

        // 创建ByteArrayResource来包装字节数组
        Resource resource = new ByteArrayResource(fileContent);
        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "application/pdf");
        // 创建并返回ResponseEntity
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
    }



    public ResponseEntity<Resource> downloadFile(String dir, String fileName) throws IOException {
        String home = System.getProperty("EAS_HOME"); // 获取 EAS 根目录
        String fileDir = home + "/server/deploy/easweb.ear/shr_web.war/tmp/electronicAttachment/" + dir;
        fileName = URLEncoder.encode(fileName, "UTF-8");
        Path filePath = Paths.get(fileDir, fileName);
        // 检查文件是否存在和可读
        if (!Files.exists(filePath) || !Files.isReadable(filePath)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        // 获取文件的内容类型
        String contentType = Files.probeContentType(filePath);
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
        // 创建资源对象
        Resource resource = new FileSystemResource(filePath.toFile());
        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, contentType);
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");

        // 创建并返回ResponseEntity
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
}


