package com.ruoyi.cron.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.cron.TaskLog;
import com.ruoyi.cron.annotation.Cron;
import com.ruoyi.cron.annotation.CronComponent;
import com.ruoyi.cron.annotation.CronParam;
import com.ruoyi.cron.document.CronTaskLog;
import com.ruoyi.cron.runner.CronBeanPostProcessor;
import lombok.RequiredArgsConstructor;

import java.time.LocalDate;
import java.util.Date;

import static com.ruoyi.common.utils.MongoUtil.*;

@CronComponent
@RequiredArgsConstructor
public class CronTaskLogCleanTask {

  private final TaskLog log;
  private final CronBeanPostProcessor cronBeanPostProcessor;

  @Cron("日志清理任务")
  public void clear(@CronParam("几天前") Integer day, @CronParam("清理的组(null全部)") Integer groupId, @CronParam("清理的任务(null全部)") String taskId) {
    log.log("开始执行日志清理...");
    Date date = DateUtils.toDate(LocalDate.now().plusDays(-day));
    log.log("清理时间(之前)：" + DateUtil.formatDateTime(date));
    log.log("清理的组编号：" + ((groupId == null) ? "全部" : groupId));
    log.log("清理的任务：" + ((taskId == null) ? "全部" : cronBeanPostProcessor.getList().stream().filter(a -> a.getId().equals(taskId)).findFirst().get().getName()));
    long count = doRemove(CronTaskLog.class, conditions().put("startTime$lt", date).query()).getDeletedCount();
    log.log("日志清理完成，清理数量：" + count);
  }

}
