package cn.stylefeng.workflow.instance.core.timer.listener;

import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.rule.listener.ApplicationStartedListener;
import cn.stylefeng.roses.kernel.timer.api.enums.TimerJobStatusEnum;
import cn.stylefeng.workflow.api.entity.instance.RuntimeTimer;
import cn.stylefeng.workflow.instance.core.timer.WorkflowTimerExec;
import cn.stylefeng.workflow.instance.modular.manage.pojo.request.RuntimeTimerRequest;
import cn.stylefeng.workflow.instance.modular.manage.service.RuntimeTimerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.core.Ordered;

import java.util.List;

@Slf4j
public class WorkflowTaskRunListener extends ApplicationStartedListener implements Ordered {

    @Override
    public void eventCallback(ApplicationStartedEvent event) {

        RuntimeTimerService runtimeTimerService = SpringUtil.getBean(RuntimeTimerService.class);
        WorkflowTimerExec workflowTimerExec = SpringUtil.getBean(WorkflowTimerExec.class);

        RuntimeTimerRequest sysTimersParam = new RuntimeTimerRequest();
        sysTimersParam.setTimerStatus(TimerJobStatusEnum.RUNNING.getCode());
        List<RuntimeTimer> runningTimerList = runtimeTimerService.findList(sysTimersParam);

        for (RuntimeTimer runtimeTimer : runningTimerList) {
            try {

                workflowTimerExec.startTimer(false,
                        null,
                        runtimeTimer.getTimerActionClass(),
                        runtimeTimer.getTimerName(),
                        runtimeTimer.getTimerCron(),
                        runtimeTimer.getParamRuntimeNodeJson(),
                        runtimeTimer.getParamInstanceContextJson());

            } catch (Exception exception) {

                log.error("定时器初始化遇到错误，略过该定时器！", exception);
            }
        }
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE - 200;
    }

}
