package com.dxhy.core.job.utils;

import java.util.Date;
import java.util.concurrent.Future;

import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSON;
import com.dxhy.common.utils.SpringContextUtils;
import com.dxhy.core.job.entity.ScheduleJobEntity;
import com.dxhy.core.job.entity.ScheduleJobLogEntity;
import com.dxhy.core.job.service.ScheduleJobLogService;

import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务
 *
 * @author user
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {
    private static ThreadPoolTaskScheduler taskExecutor;
    static {
        init();
    }

    /**
     * 启动初始化启动所有job
     *
     */
    private static void init() {
        taskExecutor = new ThreadPoolTaskScheduler();
        taskExecutor.setPoolSize(10);
        taskExecutor.setThreadNamePrefix("taskExecutor-");
        taskExecutor.initialize();
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(300);
    }

    @Override
    protected void executeInternal(@NotNull JobExecutionContext context) {

        ScheduleJobEntity scheduleJob;
        try {
            scheduleJob = (ScheduleJobEntity)context.getMergedJobDataMap().get(ScheduleJobEntity.JOB_PARAM_KEY);
        } catch (Exception e1) {
            String jsonJob = context.getMergedJobDataMap().getString(ScheduleJobEntity.JOB_PARAM_KEY);
            log.debug("josnJob   --  " + jsonJob);
            scheduleJob = JSON.parseObject(jsonJob, ScheduleJobEntity.class);
        }
        // 获取spring bean
        ScheduleJobLogService scheduleJobLogService =
            (ScheduleJobLogService)SpringContextUtils.getBean("scheduleJobLogService");

        // 数据库保存执行记录
        ScheduleJobLogEntity jobLogEntity = new ScheduleJobLogEntity();
        jobLogEntity.setJobId(scheduleJob.getJobId());
        jobLogEntity.setBeanName(scheduleJob.getBeanName());
        jobLogEntity.setMethodName(scheduleJob.getMethodName());
        jobLogEntity.setParams(scheduleJob.getParams());
        jobLogEntity.setCreateTime(new Date());

        // 任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            // 执行任务
            log.info("任务准备执行，任务ID：" + scheduleJob.getJobId());
            ScheduleRunnable task =
                new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams());
            Future<?> future = taskExecutor.submit(task);

            future.get();

            // 任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            jobLogEntity.setTimes((int)times);
            // 任务状态 0：成功 1：失败
            jobLogEntity.setStatus(0);

            log.info("任务执行完毕，任务ID：" + scheduleJob.getJobId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);

            // 任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            jobLogEntity.setTimes((int)times);

            // 任务状态 0：成功 1：失败
            jobLogEntity.setStatus(1);
            jobLogEntity.setError(StringUtils.substring(e.toString(), 0, 2000));
        } finally {
            scheduleJobLogService.save(jobLogEntity);
        }
    }
}
