package com.ruoyi.schedule.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.enums.DictEnum;
import com.ruoyi.schedule.domain.SysJobLog;
import com.ruoyi.schedule.service.ISysJobLogService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.scheduling.annotation.Scheduled;
import org.noear.solon.scheduling.scheduled.Job;
import org.noear.solon.scheduling.scheduled.JobHandler;
import org.noear.solon.scheduling.scheduled.JobInterceptor;

/**
 * 定时任务拦截器
 * @author ruoyi
 */
@Component
public class GlobalJobInterceptor implements JobInterceptor {

    @Inject
    ISysJobLogService sysJobLogService;

    @Override
    public void doIntercept(Job job, JobHandler jobHandler) throws Throwable {
        handleIntercept(job, jobHandler);
    }

    /**
     * 定时任务调度记录
     * @param job
     * @param jobHandler
     * @throws Throwable
     */
    private void handleIntercept(Job job, JobHandler jobHandler) throws Throwable {
        long start = System.currentTimeMillis();
        Scheduled scheduled = job.getScheduled();
        SysJobLog sysJobLog = new SysJobLog();
        sysJobLog.setJobName(job.getName());
//        sysJobLog.setJobSimpleName();
//        sysJobLog.setJobGroup();
        sysJobLog.setCronExpression(StrUtil.isNotEmpty(scheduled.cron()) ? scheduled.cron() : String.valueOf(scheduled.fixedRate()));
        sysJobLog.setStatus(DictEnum.COMMON_SUCCESS_FAIL.SUCCESS.getValue());
//        sysJobLog.setJobMessage();
        try {
            jobHandler.handle(job.getContext());
        } catch (Throwable e) {
            sysJobLog.setStatus(DictEnum.COMMON_SUCCESS_FAIL.FAIL.getValue());
            sysJobLog.setExceptionInfo(e.getMessage());
            throw e;
        } finally {
            long times = System.currentTimeMillis() - start;
            sysJobLog.setCostTime(times);
            sysJobLogService.save(sysJobLog);
        }
    }

}
