package org.matrix.fs.controller;

import javafx.scene.control.Alert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * FileSysController.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2022/3/17 at 2:49 PM
 * Suffering is the most powerful teacher of life.
 */
@Slf4j
@RestController
@RequestMapping
public class FileSysController {

    @GetMapping("/report/{fileName}")
    public ResponseEntity downloadAlertWeb(HttpServletRequest request,
                                           @PathVariable String fileName) {
        //1.拼接 - > url
        String fileUrl = "file:" + System.getProperty("user.dir") + "/htmls/" +fileName;
        try {
            UrlResource resource = new UrlResource(fileUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    "inline;filename=\"" + fileName + "\"");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            String contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
            return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength())
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(new InputStreamResource(resource.getInputStream()));
        } catch (IOException e) {
            log.info("[文件模块] 没有读取到文件名 = {},文件地址 = {} 的文件",fileName,fileUrl);
            HttpHeaders falseHeaders = new HttpHeaders();
            falseHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate");
            falseHeaders.add("Content-Disposition", "inline;filename=\"" + "404.jpg" + "\"");
            falseHeaders.add("Pragma", "no-cache");
            falseHeaders.add("Expires", "0");
            return ResponseEntity.ok().headers(falseHeaders).contentType(MediaType.parseMediaType("image/jpeg"))
                    .body("没有找到该资源");
        }
    }
}
