package com.mortals.flowable.common.config;

import com.mortals.flowable.listener.global.GlobalProcistEndListener;
import com.mortals.flowable.listener.global.GlobalProcistStartListener;
import com.mortals.flowable.listener.global.GlobalTaskCreateListener;
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.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 GlobalProcistEndListener globalProcistEndListener;
    @Autowired
    private GlobalProcistStartListener globalProcistStartListener;
    @Autowired
    private GlobalTaskCreateListener globalTaskCreateListener;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        log.info("全局监听配置初始化");

        FlowableEventDispatcher dispatcher = configuration.getEventDispatcher();
        //添加流程实例创建全局监听
        dispatcher.addEventListener(globalProcistStartListener, FlowableEngineEventType.PROCESS_STARTED);
        //添加流程实例结束全局监听
        dispatcher.addEventListener(globalProcistEndListener, FlowableEngineEventType.PROCESS_COMPLETED);
        dispatcher.addEventListener(globalTaskCreateListener, FlowableEngineEventType.TASK_CREATED);
    }



//
//    @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("全局监听配置");
//    }
}
