package cc.smtweb.system.bpm.web.sys.base.job;

import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.jdbc.ISimpleWorker;
import cc.smtweb.framework.core.systask.SingleRequestHelper;
import cc.smtweb.framework.core.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * Created by Akmm at 2022-09-14 09:51
 * 定时任务的基类
 */
@Slf4j
public abstract class BaseJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobEntity job = (JobEntity) jobExecutionContext.getJobDetail().getJobDataMap().get("job");

        final String id = this.getClass().getName();
        SingleRequestHelper.singleRequest(SwConsts.REDIS_KEY_BASE_JOB, id, job.getName() + "任务执行中，本次忽略.........", () -> {
            JobLog jlog = startLog(job);
            try {
                String info = work();
                endLog(jlog, true, info);
            } catch (Exception e) {
                endLog(jlog, false, e.getMessage());
                log.error(job.getName() + ":::执行失败", e);
            }

        });
    }

    //任务执行信息，可返回执行结果
    protected abstract String work();

    //存任务日志-开始
    private JobLog startLog(JobEntity job) {
        JobLog jlog = new JobLog();
        jlog.setId(DbEngine.getInstance().nextId());
        jlog.setSjId(job.getId());
        jlog.setBeginTime(DateUtil.nowDateTimeLong());
        DbEngine.getInstance().doTransSingle(() -> DbEngine.getInstance().findDao(JobLog.class).insertEntity(jlog));
        return jlog;
    }

    //存任务日志-结束
    private void endLog(JobLog jlog, boolean sucess, String info) {
        jlog.setEndTime(DateUtil.nowDateTimeLong());
        jlog.setSuccess(sucess);
        jlog.setInfo(info);
        DbEngine.getInstance().doTransSingle(() -> DbEngine.getInstance().findDao(JobLog.class).updateEntity(jlog));
    }
}
