package com.multictrl.modules.job.utils;

import com.multictrl.common.constant.Constant;
import com.multictrl.common.exception.ExceptionUtils;
import com.multictrl.common.utils.SpringContextUtils;
import com.multictrl.modules.job.entity.ScheduleJobEntity;
import com.multictrl.modules.job.entity.ScheduleJobLogEntity;
import com.multictrl.modules.job.service.ScheduleJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;


/**
 * 定时任务
 *
 * @author Sdy
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap().
				get(ScheduleUtils.JOB_PARAM_KEY);

        //数据库保存执行记录
        ScheduleJobLogEntity logEntity = new ScheduleJobLogEntity();
		logEntity.setJobId(scheduleJob.getId());
		logEntity.setBeanName(scheduleJob.getBeanName());
		logEntity.setParams(scheduleJob.getParams());
		logEntity.setCreateDate(new Date());

        //任务开始时间
        long startTime = System.currentTimeMillis();
        
        try {
			//执行任务
			log.info("任务准备执行，任务ID：{}", scheduleJob.getId());
			Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
			Method method = target.getClass().getDeclaredMethod("run", String.class);
			method.invoke(target, scheduleJob.getParams());

			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			logEntity.setTimes((int)times);
			//任务状态
			logEntity.setStatus(Constant.SUCCESS);

			log.info("任务执行完毕，任务ID：{}  总共耗时：{} 毫秒", scheduleJob.getId(), times);
		} catch (Exception e) {
			log.error("任务执行失败，任务ID：{}", scheduleJob.getId(), e);
			
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			logEntity.setTimes((int)times);
			
			//任务状态
			logEntity.setStatus(Constant.FAIL);
			logEntity.setError(ExceptionUtils.getErrorStackTrace(e));
		}finally {
			//获取spring bean
			ScheduleJobLogService scheduleJobLogService = SpringContextUtils.getBean(ScheduleJobLogService.class);
			scheduleJobLogService.insert(logEntity);
		}
    }
}