package com.yifu.cloud.plus.v1.job.util;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.yifu.cloud.plus.v1.job.entity.SysScheduleJob;
import com.yifu.cloud.plus.v1.job.entity.SysScheduleJobLog;
import com.yifu.cloud.plus.v1.job.service.SysScheduleJobLogService;
import com.yifu.cloud.plus.v1.yifu.common.core.util.SpringContextHolder;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.scheduling.quartz.QuartzJobBean;

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


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


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        SysScheduleJob scheduleJob = (SysScheduleJob) context.getMergedJobDataMap()
                .get(SysScheduleJob.JOB_PARAM_KEY);

        //获取spring bean
        SysScheduleJobLogService scheduleJobLogService = (SysScheduleJobLogService) SpringContextHolder.getBean("sysScheduleJobLogService");

        //数据库保存执行记录
        SysScheduleJobLog log = new SysScheduleJobLog();
        log.setJobId(scheduleJob.getJobId());
        log.setBeanName(scheduleJob.getBeanName());
        log.setMethodName(scheduleJob.getMethodName());
        log.setParams(scheduleJob.getParams());
        log.setCreatetime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN));
        log.setRemark(scheduleJob.getRemark());

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

        try {
//			MDC.put("logname");
            MDC.put("logName", getLogName(scheduleJob.getMethodName()));
            //执行任务
            logger.info("任务准备执行，任务ID：" + scheduleJob.getJobId());
            //任务状态    0：成功    1：失败  2 执行中
            log.setStatus(String.valueOf(2));
            scheduleJobLogService.saveOrUpdate(log);

            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(),
                    scheduleJob.getMethodName(), scheduleJob.getParams());
            Future<?> future = service.submit(task);

            future.get();

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

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

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

            //任务状态    0：成功    1：失败  2 执行中
            log.setStatus(String.valueOf(1));
            log.setError(e.toString());
        } finally {
            MDC.remove("logName");
            scheduleJobLogService.saveOrUpdate(log);
        }
    }

    private String getLogName(String path) {
        return String.format("%s%s_%s", "Schedule", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN), path);
    }
}
