package com.huigou.bpm.engine.job;

import com.huigou.bpm.engine.application.TimeoutBizTaskHandler;
import com.huigou.bpm.engine.domain.model.BizTask;
import com.huigou.bpm.engine.repository.BizTaskRepository;
import com.huigou.cache.SystemCache;
import com.huigou.util.ApplicationContextWrapper;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;

/**
 * @author yonghuan
 */
@DisallowConcurrentExecution
public class BizTaskTimeoutCheckJob extends QuartzJobBean {

    private final static Logger LOG = LoggerFactory.getLogger(BizTaskTimeoutCheckJob.class);

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        Boolean enabledCheck = SystemCache.getParameter("bpm.bizTask.timeoutCheck.enabled", Boolean.class);
        if (Boolean.FALSE.equals(enabledCheck)) {
            return;
        }
        Collection<TimeoutBizTaskHandler> handlers = ApplicationContextWrapper.getBeans(TimeoutBizTaskHandler.class);
        if (CollectionUtils.isEmpty(handlers) && LOG.isErrorEnabled()) {
            LOG.debug("未设置业务节点超时任务handler，将不扫描业务节点超时任务！");
            return;
        }
        BizTaskRepository taskRepository = ApplicationContextWrapper.getBean(BizTaskRepository.class);
        long totals = taskRepository.countTimeoutCheckTask();
        if (LOG.isInfoEnabled()) {
            LOG.info("检查到 {} 条超时业务节点任务", totals);
        }
        if (totals > 0) {
            List<BizTask> tasks = taskRepository.findTimeoutCheckTasks();
            handlers.forEach(handler -> handler.handle(tasks));
            tasks.forEach(task -> {
                task.setTimeoutCheck(false);
                taskRepository.save(task);
            });
        }

    }
}
