/*
 *  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 com.yfd.platform.utils;

import com.yfd.platform.config.MessageConfig;
import com.yfd.platform.config.thread.ThreadPoolExecutorUtil;
import com.yfd.platform.system.domain.Message;
import com.yfd.platform.system.domain.QuartzJob;
import com.yfd.platform.system.service.IMessageService;
import com.yfd.platform.system.service.IQuartzJobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

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

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

    @Resource
    private IMessageService messageService;

    @Resource
    private MessageConfig messageConfig;

    @Override
    public void executeInternal(JobExecutionContext context) {
        QuartzJob quartzJob =
                (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY);
        // 获取spring bean
        IQuartzJobService quartzJobService =
                SpringContextHolder.getBean(IQuartzJobService.class);
        String uuid = quartzJob.getId();
        long startTime = System.currentTimeMillis();
        String jobName = quartzJob.getJobName();
        try {
            // 执行任务
            log.info("任务开始执行，任务名称：" + jobName);
            QuartzRunnable task = new QuartzRunnable(quartzJob.getJobClass(),
                    quartzJob.getJobMethod(),
                    quartzJob.getJobParams());
            Future<?> future = EXECUTOR.submit(task);
            future.get();
            long times = System.currentTimeMillis() - startTime;

            Message message = new Message();
            message.setCreatetime(new Timestamp(System.currentTimeMillis()));
            message.setType("1");
            message.setTitle(quartzJob.getJobName());
            message.setContent(quartzJob.getDescription());
            message.setSenderName("定时器");
            message.setReceiverCodes(quartzJob.getOrderno().toString());
            message.setReceiverNames("");
            message.setStatus("1");
            message.setValidperiod(24);
            messageConfig.addMessage(message);
            // 任务状态
            log.info("任务执行完毕，任务名称：" + jobName + ", " +
                    "执行时间：" + times + "毫秒");
            log.info(
                    "--------------------------------------------------------------");
        } catch (Exception e) {
            log.error("任务执行失败，任务名称：" + jobName);
            log.error(
                    "--------------------------------------------------------------");
            quartzJob.setStatus("0");
            //更新状态
            quartzJobService.updateById(quartzJob);
        }
    }

}
