package com.mortals.flowable.common.config;

import com.google.common.collect.Maps;
import com.mortals.flowable.listener.ProcessEndListener;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author: zxfei
 * @date: 2021/8/10 0:30
 * @description:
 **/
//@Configuration
public class FlowableListenerConfig {

    // flowable监听级别参照 {@link FlowableEngineEventType} org.flowable.common.engine.api.delegate.event
    /**
     * 任务节点前置监听
     */
    private static final String FLOWABLE_TASK_NODE_REAR_LISTENER = "TASK_COMPLETED";
    private static final String FLOWABLE_TASK_NODE_BEFORE_LISTENER = "TASK_COMPLETED";

    // 自己建立监听类实现FlowableEventListener接口
    /**
     * 任务节点前置监听
     */
    private final ProcessEndListener taskBeforeListener;


    @Autowired
    public FlowableListenerConfig(ProcessEndListener taskBeforeListener) {
        this.taskBeforeListener = taskBeforeListener;
    }

    /**
     * 将自定义监听器纳入flowable监听
     *
     * @param
     * @return org.flowable.spring.boot.EngineConfigurationConfigurer<org.flowable.spring.SpringProcessEngineConfiguration>
     * @author: Lu Yang
     * @date: 2019/5/4 21:05
     */
    @Bean
    public EngineConfigurationConfigurer<SpringProcessEngineConfiguration> globalListenerConfigurer() {
        return engineConfiguration -> {
            engineConfiguration.setTypedEventListeners(this.customFlowableListeners());
        };
    }


    private Map<String, List<FlowableEventListener>> customFlowableListeners() {
        Map<String, List<FlowableEventListener>> listenerMap = Maps.newHashMap();
        listenerMap.put(FLOWABLE_TASK_NODE_BEFORE_LISTENER, new ArrayList<>(Collections.singletonList(getTaskBeforeListener())));
        return listenerMap;
    }

    public ProcessEndListener getTaskBeforeListener() {
        return taskBeforeListener;
    }
}
