package admin.config;

import admin.asept.DynamicDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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 javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lj
 * @date 2024/11/19 13:24
 */
@Configuration
@EnableAutoConfiguration
public class DataSourceConfig{

    @Bean(value = "master")
//    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master")
    public DataSource createDataSourceYdp(){
        System.out.println("zhjt数据源");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(value="slaver")
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.slaver")
    public DataSource createDataSourceQy(){
        System.out.println("qy数据源");
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 动态数据源引入
     *
     * @param masterDataSource
     * @return
     */
    @Bean
    @Primary
    public DynamicDataSource dataSource(@Qualifier("master") DataSource ydpDataSource,
                                        @Qualifier("slaver") DataSource qyDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(3);
        targetDataSources.put("master", ydpDataSource);
        targetDataSources.put("slaver", qyDataSource);


        //配置包级别的数据源
        Map<String, String> packageDataSource = new HashMap<>();
        //默认包使用的数据源
        packageDataSource.put("admin.modules","master");

        DynamicDataSource dynamicDataSource = new DynamicDataSource(ydpDataSource, targetDataSources);
        dynamicDataSource.setPackageDatasource(packageDataSource);
        dynamicDataSource.afterPropertiesSet();
        return dynamicDataSource;
    }
}
