package com.mortals.flowable.common.config;

import com.mortals.flowable.listener.ProcessInstanceCompleteListener;
import com.mortals.flowable.listener.ProcessInstanceStartListener;
import com.mortals.flowable.listener.TaskCreateListener;
import lombok.extern.apachecommons.CommonsLog;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.impl.event.logger.handler.ProcessInstanceStartedEventHandler;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 全局监听配置 ContextRefreshedEvent在类被初始化之后触发
 */
@Configuration
@CommonsLog
public class FlowableGlobListenerConfig implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private SpringProcessEngineConfiguration configuration;
    @Autowired
    private ProcessInstanceCompleteListener processInstanceCompleteListener;
    @Autowired
    private ProcessInstanceStartListener processInstanceStartListener;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskCreateListener taskCreateListener;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        FlowableEventDispatcher dispatcher = configuration.getEventDispatcher();
        // 任务创建全局监听-待办消息发送
        runtimeService.addEventListener(taskCreateListener, FlowableEngineEventType.TASK_CREATED);
        //任务完成全局监听
        // dispatcher.addEventListener(activityCompleteListener, FlowableEngineEventType.TASK_CREATED);


        runtimeService.addEventListener(processInstanceStartListener, FlowableEngineEventType.PROCESS_STARTED);
        runtimeService.addEventListener(processInstanceCompleteListener, FlowableEngineEventType.PROCESS_COMPLETED);

        log.info("全局监听配置");
    }
}
