package com.qmth.themis.task.listener;

import cn.hutool.core.date.DateUtil;
import com.qmth.themis.business.constant.SpringContextHolder;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.entity.TSLog;
import com.qmth.themis.business.enums.LogEnum;
import com.qmth.themis.business.service.TSLogService;
import com.qmth.themis.business.util.JacksonUtil;
import com.qmth.themis.common.contanst.Constants;
import com.qmth.themis.task.enums.QuartzTaskEnum;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @Description: job监听
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2022/9/22
 */
public class MyJobListener implements JobListener {
    private final static Logger log = LoggerFactory.getLogger(MyJobListener.class);

    @Override
    public String getName() {
        return "myJobListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        log.info("定时任务:{}-开始执行", context.getTrigger().getJobKey());
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {

    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        QuartzTaskEnum quartzTaskEnum = QuartzTaskEnum.valueOf(context.getTrigger().getJobKey().getGroup());
        switch (quartzTaskEnum) {
            case EXAM_ACTIVITY_JOB_GROUP_NAME:
            case EXAM_STUDENT_JOB_GROUP_NAME:
            case MQ_ACTIVITY_JOB_GROUP_NAME:
//            case EXAM_AUDIO_JOB_GROUP_NAME:
                try {
                    TSLogService tsLogService = SpringContextHolder.getBean(TSLogService.class);
                    tsLogService.save(new TSLog(LogEnum.JOB, JacksonUtil.parseJson(context.getTrigger().getJobKey()),
                            Objects.nonNull(context.getPreviousFireTime()) ? DateUtil.format(context.getPreviousFireTime(), Constants.DEFAULT_DATE_PATTERN) : null,
                            Objects.nonNull(context.getNextFireTime()) ? DateUtil.format(context.getNextFireTime(), Constants.DEFAULT_DATE_PATTERN) : null,
                            -1L));
                } catch (Exception e) {
                    log.error(SystemConstant.LOG_ERROR, e);
                }
                break;
            default:
                break;
        }
        log.info("定时任务:{}-执行结束", context.getTrigger().getJobKey());
    }
}