package cn.schedule.core;

import cn.component.context.SpringContextKit;
import cn.constant.SqlConst;
import cn.constant.ScheduleConst;
import cn.pojo.entity.TSysJob;
import cn.pojo.entity.TSysJobLog;
import cn.service.IJobLogService;
import cn.util.core.CloneKit;
import cn.util.core.ExceptKit;
import cn.util.core.IsKit;
import cn.util.string.StringKit;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;

/**
 * 抽象quartz调用
 */
public abstract class AbstractQuartzJob implements Job 
{
     /**线程本地变量*/
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException 
    {
        TSysJob sysJob = new TSysJob();
        CloneKit.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConst.TASK_PROPERTIES));
        try {
            before(context, sysJob);
            if (sysJob != null) {
                doExecute(context, sysJob);
            }
            after(context, sysJob, null);
        } catch (Exception e) {
            after(context, sysJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param sysJob  系统计划任务
     */
    protected void before(JobExecutionContext context, TSysJob sysJob) {
        threadLocal.set(new Date());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param sysJob  系统计划任务
     */
    protected void after(JobExecutionContext context, TSysJob sysJob, Exception e) 
    {
        Date startTime = threadLocal.get();
        threadLocal.remove();
        final TSysJobLog sysJobLog = new TSysJobLog();
        sysJobLog.setJobName(sysJob.getJobName());
        sysJobLog.setJobGroup(sysJob.getJobGroup());
        sysJobLog.setInvokeTarget(sysJob.getInvokeTarget());
        sysJobLog.setStartTime(startTime);
        sysJobLog.setStopTime(new Date());
        long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
        sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (IsKit.isNotNull(e) ) {
            sysJobLog.setStatus(SqlConst.FAIL);
            String errorMsg = StringKit.substring(ExceptKit.getExceptionMessage(e), 0, 2000);
            sysJobLog.setExceptionInfo(errorMsg);
        } else {
            sysJobLog.setStatus(SqlConst.SUCCESS);
        }
        //写入数据库当中
        SpringContextKit.getBean(IJobLogService.class).addJobLog(sysJobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob  系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, TSysJob sysJob) throws Exception;
}

