package cn.datax.service.workflow.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.AllArgsConstructor;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@AllArgsConstructor
public class ProcessEngineConfig {

    private final DataSource dataSource;

    /**
     * ProcessEngine 配置，注入DataSourceTransactionManager和DataSource
     * @return
     */
    @Bean
    public SpringProcessEngineConfiguration springProcessEngineConfiguration() {
        SpringProcessEngineConfiguration springProcessEngineConfiguration = new SpringProcessEngineConfiguration();
        // 手动从多数据源中获取 quartz数据源
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        DataSource flowable = ds.getDataSource("flowable");
        springProcessEngineConfiguration.setDataSource(flowable);
        springProcessEngineConfiguration.setTransactionManager(new DataSourceTransactionManager(flowable));
        // 不添加此项配置，在没创建表时，会抛出FlowableWrongDbException异常
        springProcessEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
        return springProcessEngineConfiguration;
    }
}
