package com.qqchen.deploy.backend.workflow.config;

import com.qqchen.deploy.backend.workflow.event.FlowableEventDispatcher;
import jakarta.annotation.Resource;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.Map;

/**
 * Flowable配置类
 */
@Configuration
public class FlowableConfig implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration> {

    @Resource
    private FlowableEventDispatcher flowableEventDispatcher;

    @Override
    public void configure(SpringProcessEngineConfiguration engineConfiguration) {
        engineConfiguration.setActivityFontName("宋体");
        engineConfiguration.setLabelFontName("宋体");
        engineConfiguration.setAnnotationFontName("宋体");
        engineConfiguration.setDatabaseSchemaUpdate("true");

        // 配置异步执行器
        engineConfiguration.setAsyncExecutorActivate(true);
        // 设置重试次数为1，不重试
        engineConfiguration.setAsyncExecutorNumberOfRetries(1);
        // 设置失败等待时间为最小值
        engineConfiguration.setAsyncFailedJobWaitTime(1);

//        // 配置异步执行器参数
//        engineConfiguration.setAsyncExecutorDefaultAsyncJobAcquireWaitTime(1000);
//        engineConfiguration.setAsyncExecutorDefaultTimerJobAcquireWaitTime(1000);
//        engineConfiguration.setAsyncExecutorDefaultQueueSizeFullWaitTime(1000);
//        engineConfiguration.setAsyncExecutorMaxAsyncJobsDuePerAcquisition(1);
//        engineConfiguration.setAsyncExecutorMaxTimerJobsPerAcquisition(1);
//
//        // 禁用过期任务重置
//        engineConfiguration.setAsyncExecutorResetExpiredJobsInterval(0);
//
//        // 禁用定义缓存
//        engineConfiguration.setEnableProcessDefinitionInfoCache(false);

        // 添加事件监听器
        engineConfiguration.setEventListeners(Collections.singletonList(flowableEventDispatcher));
        engineConfiguration.setTypedEventListeners(
            Map.of(
                FlowableEngineEventType.PROCESS_CANCELLED.name(), Collections.singletonList(flowableEventDispatcher),
                FlowableEngineEventType.PROCESS_COMPLETED.name(), Collections.singletonList(flowableEventDispatcher),
                FlowableEngineEventType.PROCESS_COMPLETED_WITH_ERROR_END_EVENT.name(), Collections.singletonList(flowableEventDispatcher),
                FlowableEngineEventType.PROCESS_COMPLETED_WITH_TERMINATE_END_EVENT.name(), Collections.singletonList(flowableEventDispatcher)
            )
        );
    }
}
