/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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.heyu.api.schedule;


import com.heyu.api.data.constants.ApiConstants;
import com.heyu.api.data.entity.calca.ScheduleJobEntity;
import com.heyu.api.data.entity.calca.ScheduleJobLogEntity;
import com.heyu.api.data.utils.SpringContextUtils;
import com.heyu.api.data.utils.StringUtils;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.*;


/**
 * 定时任务
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.2.0 2016-11-28
 */
public class ScheduleJob extends QuartzJobBean {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final ThreadPoolExecutor TASK_EXECUTOR = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1,
            Runtime.getRuntime().availableProcessors() + 1, 10, TimeUnit.MINUTES,
            new ArrayBlockingQueue<>(1000),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.CallerRunsPolicy());


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap map = context.getMergedJobDataMap();
        Object obj = map.get(ApiConstants.JOB_PARAM_KEY);
        ScheduleJobEntity scheduleJob;
        if (obj instanceof ScheduleJobEntity) {
            scheduleJob = (ScheduleJobEntity) obj;
        } else {
            scheduleJob = new ScheduleJobEntity();
            BeanUtils.copyProperties(obj, scheduleJob);
        }
        //任务开始时间
        long startTime = System.currentTimeMillis();

        if (!SpringContextUtils.hasBean(scheduleJob.getBeanName())) {
            logger.info("任务准备执行，beanName 是：" + scheduleJob.getBeanName() + " ，但是容器中不存在 ，不执行");
            return;
        }


        //数据库保存执行记录
        ScheduleJobLogEntity log = new ScheduleJobLogEntity();
        log.setJobId(scheduleJob.getJobId());
        log.setBeanName(scheduleJob.getBeanName());
        log.setMethodName(scheduleJob.getMethodName());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(new Date());
        log.setStatus(0);
        log.setTimes(1);
        try {
            //执行任务
            logger.info("任务准备执行，任务ID：" + scheduleJob.getJobId());
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams());
            Future<?> future = TASK_EXECUTOR.submit(task);
            future.get();
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times);
            //任务状态    0：成功    1：失败
            log.setStatus(1);

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

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

            //任务状态    0：执行中    -1：失败
            log.setStatus(-1);
            log.setError(StringUtils.substring(e.toString(), 0, 2000));
        }
    }
}
