package com.ruoyi.project.monitor.controller;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.monitor.domain.SysLog;
import com.ruoyi.project.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 操作日志记录
 *
 * @author Wang Zi Wen
 * @email wangggziwen@163.com
 * @date 2023/04/25 15:47:42
 */
@RestController
@RequestMapping("/monitor/log")
public class SysLogController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ISysConfigService configService;
    /**
     * 查询操作日志列表
     *
     * @return 操作日志列表
     */
    @GetMapping("/list")
    public AjaxResult list()
    {
        // 获取log.path的值
        String filePath = null;

        filePath = configService.selectConfigByKey("log.path");
        if (StringUtils.isEmpty(filePath)) {
            filePath = "/u03/logs";
        }
        logger.info(filePath);
        File file = new File(filePath);//父级文件夹
        String[] fileNameList = file.list();//文件名列表
        File[] fileList = file.listFiles();
        // 使用Comparator对文件列表按照修改日期进行排序
        Arrays.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File file1, File file2) {
                long lastModified1 = file1.lastModified();
                long lastModified2 = file2.lastModified();
                return Long.compare(lastModified2, lastModified1);
            }
        });
        // 获取前200条文件（如果文件列表超过200条）
        int limit = Math.min(fileList.length, 200);
        File[] topFiles = Arrays.copyOf(fileList, limit);

        List<SysLog> logList = new ArrayList<>();//日志信息列表
        for (File f : topFiles) {
            SysLog sysLog = new SysLog();
            sysLog.setFileName(f.getName());//文件名
            sysLog.setFileUrl(f.getAbsolutePath());//绝对路径
            logList.add(sysLog);
        }
        return AjaxResult.success(logList);
    }

    /**
     * 下载操作日志
     *
     * @param fileName 文件名称
     * @param fileUrl 文件路径
     */
    @GetMapping("/download")
    public void logFileDownload(String fileName, String fileUrl, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(fileUrl, response.getOutputStream());
        }
        catch (Exception e)
        {
            logger.error("下载文件失败", e);
        }
    }

}
