package org.jeecg.modules.quartz.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.joblog.entity.CsPtJobLog;
import org.jeecg.modules.joblog.service.ICsPtJobLogService;
import org.jeecg.modules.quartz.entity.QuartzJob;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: niugeng
 * @create: 2024-03-12 16:46
 **/
@Slf4j
@Component
public class SysJobListener implements JobListener {
    @Override
    public String getName() {
        return "sysJobListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException e) {
        try {
            final JobDetail jobDetail = context.getJobDetail();
            final Class<? extends Job> jobClass = jobDetail.getJobClass();

            final IQuartzJobService quartzJobService = SpringContextUtils.getBean(IQuartzJobService.class);
            final QuartzJob quartzJob = quartzJobService.lambdaQuery().eq(QuartzJob::getJobClassName, jobClass.getName()).one();
            if (quartzJob ==null){
                return;
            }
            final long jobRunTime = context.getJobRunTime();
            final Date fireTime = context.getFireTime();

            String status ;
            String message = "" ;
            // 作业执行完成
            if (e != null) {
                status = "1";
                message = StrUtil.sub(e.getMessage(),0,2000);
            } else {
                status = "0";
            }

            final ICsPtJobLogService logService = SpringContextUtils.getBean(ICsPtJobLogService.class);
            final CsPtJobLog csPtJobLog = new CsPtJobLog();
            csPtJobLog.setJobId(quartzJob.getId());
            csPtJobLog.setJobName(quartzJob.getDescription());
            csPtJobLog.setQqsj(fireTime);
            csPtJobLog.setFhsj(DateUtil.date());
            csPtJobLog.setHs(jobRunTime);
            csPtJobLog.setStatus(status);
            csPtJobLog.setMessage(message);

            logService.save(csPtJobLog);
        } catch (Exception ignored) {

        }

    }
}
