package com.yida.data.job.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.entity.job.Job;
import com.yida.data.job.service.IJobService;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.cron.pattern.CronPattern;
import cn.hutool.cron.pattern.CronPatternUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@RequiredArgsConstructor
public class JobTask {
    private final IJobService jobService;

    /**
     * 清理过期的用户定时任务
     */
    public void cleanExpiredUserJob() {
        List<Job> list = jobService.list(Wrappers.<Job>lambdaQuery()
                .eq(Job::getType, 1));
        List<String> delJobs = new ArrayList<>();
        for (Job job : list) {
            Date date = CronPatternUtil.nextDateAfter(new CronPattern(job.getCronExpression()), new Date(), true);
            log.info("clean job,date:{}", date);
            if (date == null) {
                delJobs.add(job.getJobId().toString());
            }
        }
        if (CollUtil.isNotEmpty(delJobs)) {
            jobService.deleteJobs(delJobs.toArray(new String[0]));
        }
    }
}
