package com.bcxin.autodownloadupload.controller;


import cn.hutool.core.io.FileUtil;
import com.bcxin.autodownloadupload.common.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.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.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@RestController
@RequestMapping("/download/log")
public class DownloadLogController {

    /**
     * description: 下载日志
     * author: linchunpeng
     * date:  2023-06-07 13:14
     */
    @GetMapping("/{logPath}")
    public void downloadLogByPath(@PathVariable("logPath") String logPath, HttpServletResponse response) throws IOException {
        boolean isNullFile = false;
        if (StringUtils.isBlank(logPath)) {
            isNullFile = true;
        }
        logPath = logPath.replace("*", File.separator);
        if (!FileUtil.exist(logPath)) {
            isNullFile = true;
        }
        if (isNullFile) {
            response.setContentType("text/html; charset=UTF-8"); //转码
            PrintWriter out = response.getWriter();
            out.flush();
            out.println("<script defer='defer' type='text/javascript'>");
            out.println("alert('无log文件下载');");
            out.println("</script>");
            return;
        }
        FileUtils.responseWithFile(logPath, response);
    }

}
