package cn.iocoder.yudao.module.member.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.zip.GZIPOutputStream;

/**
 * @author zt
 * @description <description class purpose>
 * @since 2024/10/11
 */
@Slf4j
@Component
public class LogHandleJob implements JobHandler {

    private static final String LOG_FILE = "/usr/carteen/nohup.out";  // 原始 nohup.out 文件路径
    private static final String LOG_DIRECTORY = "/usr/carteen/log/"; // 保存压缩文件的目录


    @Override
    @TenantIgnore
    public String execute(String param) {
        // 获取昨天的日期，作为压缩文件的名字
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = dateFormat.format(calendar.getTime());
        String compressedFileName = LOG_DIRECTORY + formattedDate + ".gz";

        // 读取 nohup.out 文件并压缩
        try (FileInputStream fis = new FileInputStream(LOG_FILE);
             FileOutputStream fos = new FileOutputStream(compressedFileName);
             GZIPOutputStream gzipOS = new GZIPOutputStream(fos)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                gzipOS.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 压缩完成后，清空 nohup.out 文件（保留文件句柄）
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(LOG_FILE);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        writer.print("");
        writer.close();
        return String.format("日志压缩  %s ", true);
    }
}
