package com.jsc.oscm.util;

import com.jsc.oscm.dao.LogRepository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

@Component
public class LogCleanupTask {

    @Resource
    private LogRepository logRepository;

    private static final Logger logger = Logger.getLogger(LogCleanupTask.class.getName());

    @Scheduled(cron = "0 0 0 * * *") // 每天的午夜执行
    public void cleanUpLogs() {
        LocalDateTime oneWeekAgo = LocalDateTime.now().minusWeeks(1); // 计算一周前的时间

        Date dateOneWeekAgo = Date.from(oneWeekAgo.atZone(ZoneId.systemDefault()).toInstant()); // 转换为Date类型

        // 调用 Repository 删除超过一周的日志记录
        logRepository.deleteByCreateTimeBefore(dateOneWeekAgo);
        logger.log(Level.INFO, "清理日志操作完成");
    }
}
