package com.foreverwin.mesnac.quartz.configuration;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foreverwin.mesnac.quartz.model.SystemJob;
import com.foreverwin.mesnac.quartz.model.SystemJobLog;
import com.foreverwin.mesnac.quartz.constant.Constants;
import com.foreverwin.mesnac.quartz.service.SystemJobLogService;
import com.foreverwin.mesnac.quartz.service.SystemJobService;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.listeners.JobListenerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;

/**
 * @author Ervin Chen
 * @date 2020/10/22 16:15
 */
public class SystemJobListener extends JobListenerSupport {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    SystemJobService systemJobService;

    @Autowired
    SystemJobLogService systemJobLogService;

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

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {

    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        long runTime = context.getJobRunTime();
        JobDetail jobDetail = context.getJobDetail();
        String jobName = jobDetail.getKey().getName();
        String jobGroup = jobDetail.getKey().getGroup();
        Map jobDataMap = jobDetail.getJobDataMap().getWrappedMap();

        if(jobException != null){
            logger.error("任务:{},任务组:{},任务参数:{},运行时间:{},运行结果:{},失败信息:{}", jobDetail.getDescription(), jobGroup, Convert.toStr(jobDataMap), runTime, "FAIL", ExceptionUtil.stacktraceToString(jobException));
        }else{
            logger.info("任务:{},任务组:{},任务参数:{},运行时间:{},运行结果:{}", jobDetail.getDescription(), jobGroup, Convert.toStr(jobDataMap), runTime, "OK");
        }

        QueryWrapper<SystemJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemJob.NAME, jobName).eq(SystemJob.JOB_GROUP, jobGroup);
        SystemJob systemJob = systemJobService.getOne(queryWrapper, false);
        if(systemJob != null){
            SystemJobLog jobLog = new SystemJobLog();
            jobLog.setHandle(String.format(Constants.SYSTEM_JOB_LOG_BO, systemJob.getHandle(), System.currentTimeMillis()));
            jobLog.setJobBo(systemJob.getHandle());
            jobLog.setName(systemJob.getName());
            jobLog.setDescription(systemJob.getDescription());
            jobLog.setJobGroup(systemJob.getJobGroup());
            jobLog.setJobClass(systemJob.getJobClass());
            jobLog.setJobParam(Convert.toStr(jobDataMap));
            jobLog.setRunTime(runTime);
            jobLog.setStartDateTime(LocalDateTime.ofInstant(context.getFireTime().toInstant(), ZoneId.systemDefault()));
            jobLog.setEndDateTime(jobLog.getStartDateTime().plusSeconds(runTime/1000));
            if(jobException != null){
                jobLog.setStatus(Constants.FAIL);
                jobLog.setError(ExceptionUtil.stacktraceToString(jobException));
                logger.error("任务:{},任务组:{},任务参数:{},运行时间:{},运行结果:{},失败信息:{}", jobDetail.getDescription(), jobGroup, Convert.toStr(jobDataMap), runTime, "FAIL", ExceptionUtil.stacktraceToString(jobException));
            }else{
                jobLog.setStatus(Constants.OK);
                logger.info("任务:{},任务组:{},任务参数:{},运行时间:{},运行结果:{}", jobDetail.getDescription(), jobGroup, Convert.toStr(jobDataMap), runTime, "OK");
            }
            systemJobLogService.save(jobLog);
        }
    }
}
