package cn.datax.service.workflow.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.zaxxer.hikari.HikariDataSource;
import lombok.AllArgsConstructor;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@AllArgsConstructor
public class ProcessEngineConfig {

    private final DataSource dataSource;

//    @Bean
//    @Primary
//    @ConfigurationProperties("spring.datasource.primary")
//    public DataSourceProperties primaryDataSourceProperties() {
//        return new DataSourceProperties();
//    }
//
//    @Bean
//    @Primary
//    @ConfigurationProperties("spring.datasource.primary.configuration")
//    public HikariDataSource firstDataSource() {
//        return primaryDataSourceProperties().initializeDataSourceBuilder()
//                .type(HikariDataSource.class).build();
//    }
//
//    @Bean
//    @ConfigurationProperties("spring.datasource.flowable")
//    public DataSourceProperties flowableDataSourceProperties() {
//        return new DataSourceProperties();
//    }
//
//    @Bean
//    @ConfigurationProperties("spring.datasource.flowable.configuration")
//    public HikariDataSource flowableDataSource() {
//        return flowableDataSourceProperties().initializeDataSourceBuilder()
//                .type(HikariDataSource.class).build();
//    }

    /**
     * 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;
    }
}
