/**
 * 
 */
package com.huatek.busi.service.impl.job;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSON;
import com.huatek.busi.entity.ScheduleJob;
import com.huatek.busi.entity.ScheduleJobLog;
import com.huatek.busi.service.job.ScheduleJobLogService;
import com.huatek.torch.util.uuid.Uuid;

/**
  * @ClassName: CustomJobBean
  * @FullClassPath: com.huatek.busi.service.impl.job.CustomJobBean
  * @Description: TODO
  * @author: Arno
  * @date: Jul 3, 2019 3:05:56 PM
  * @version: 1.0
  */

public class CustomJobBean extends QuartzJobBean {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private ExecutorService service = Executors.newSingleThreadExecutor(); 
	
	

	/* (non-Javadoc)
	 * @see org.springframework.scheduling.quartz.QuartzJobBean#executeInternal(org.quartz.JobExecutionContext)
	 */
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		//JobKey jobKey = context.getTrigger().getJobKey();
		String jsonJob = context.getMergedJobDataMap().getString(JobConstant.JOB_PARAM_KEY);
		ScheduleJob scheduleJob =  JSON.parseObject(jsonJob, ScheduleJob.class);

		//获取spring bean
	    ScheduleJobLogService scheduleJobLogService = SpringContextUtils.getBean(ScheduleJobLogService.class);
	    
		logger.info("任务准备执行，任务ID：" + scheduleJob.getId());
		 //数据库保存执行记录
        ScheduleJobLog log = new ScheduleJobLog();
        log.setId(Uuid.getUUID());
        log.setJobId(scheduleJob.getId());
        log.setBeanName(scheduleJob.getBeanName());
        log.setMethodName(scheduleJob.getMethodName());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(LocalDateTime.now());
        
        //任务开始时间
        long startTime = System.currentTimeMillis();
		try {
			ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), 
					scheduleJob.getMethodName(), scheduleJob.getParams());
			Future<?> future = service.submit(task);        
			future.get();
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes((int)times);
			//任务状态    0：成功    1：失败
			log.setStatus(0);
			logger.info("任务执行完毕，任务ID：" + scheduleJob.getId() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			logger.error("任务执行失败，任务ID：" + scheduleJob.getId(), e);
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes((int)times);
			//任务状态    0：成功    1：失败
			log.setStatus(1);
			log.setError(e.getMessage());
		}finally {
			scheduleJobLogService.insertLog(log);
		}
	}

}
