/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package easydo.technology.quartz.utils;

import easydo.technology.quartz.domain.SysQuartzJob;
import easydo.technology.quartz.domain.QuartzLog;
import easydo.technology.quartz.mapper.QuartzLogMapper;
import easydo.technology.quartz.thread.ThreadPoolExecutorUtil;
import easydo.technology.utils.RedisUtils;
import easydo.technology.utils.SpringContextHolder;
import easydo.technology.utils.StringUtil;
import easydo.technology.utils.ThrowableUtil;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.UUID;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 参考人人开源，https://gitee.com/renrenio/renren-security
 * @author /
 * @date 2019-01-07
 */
@Async
@SuppressWarnings({"unchecked","all"})
public class ExecutionJob extends QuartzJobBean {

    /** 该处仅供参考 */
    private final static ThreadPoolExecutor EXECUTOR = ThreadPoolExecutorUtil.getPoll();

    @Override
    public void executeInternal(JobExecutionContext context) {
        SysQuartzJob quartzJob = (SysQuartzJob) context.getMergedJobDataMap().get(SysQuartzJob.JOB_KEY);
        // 获取spring bean
        QuartzLogMapper quartzLogRepository = SpringContextHolder.getBean(QuartzLogMapper.class);
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        
        String uuid = quartzJob.getUuid();

        QuartzLog log = new QuartzLog();
        log.setId(UUID.randomUUID().toString());
        log.setJobName(quartzJob.getJobName());
        log.setBeanName(quartzJob.getBeanName());
        log.setMethodName(quartzJob.getMethodName());
        log.setParams(quartzJob.getParams());
        long startTime = System.currentTimeMillis();
        log.setCronExpression(quartzJob.getCronExpression());
        try {
            QuartzRunnable task = new QuartzRunnable(quartzJob.getBeanName(), quartzJob.getMethodName(),
                    quartzJob.getParams());
            Future<?> future = EXECUTOR.submit(task);
            future.get();
            long times = System.currentTimeMillis() - startTime;
            log.setTime(times);
            if(StringUtil.isNotEmpty(uuid)) {
                redisUtils.set(uuid, true);
            }
            // 任务状态
            log.setIsSuccess(true);
        } catch (Exception e) {
            if(StringUtil.isNotEmpty(uuid)) {
                redisUtils.set(uuid, false);
            }
            long times = System.currentTimeMillis() - startTime;
            log.setTime(times);
            // 任务状态 0：成功 1：失败
            log.setIsSuccess(false);
            log.setExceptionDetail(ThrowableUtil.getStackTrace(e));
        } finally {
            quartzLogRepository.insert(log);
        }
    }
}
