package com.pictc.config;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.pictc.jdbc.JdbcContextUtils;
import com.pictc.utils.StringUtils;

@Configuration
public class JdbcConfig {
	
    @Value("${spring.datasource.dynamic.datasource.master.username:itc_dne}")
    private String globalUsername;
    
    @Value("${spring.datasource.dynamic.datasource.master.password:itc_dne}")
    private String globalPassword;
    
    @Value("${spring.datasource.dynamic.datasource.master.driver-class-name:com.kingbase8.Driver}")
    private String globalDriver;
	
	@Bean
	public JdbcContextUtils jdbcContextUtils() throws SQLException {
		JdbcContextUtils contextUtils = new JdbcContextUtils();
		contextUtils.setLogSource(logDataSource());
		return contextUtils;
	}
	
	@Bean
	public DataLogDbConfig logDataDbConfig() {
		return new DataLogDbConfig();
	}
	
	/**
     * 额外的日志数据源配置
     */
    public DataSource logDataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        DataLogDbConfig dbConfig = logDataDbConfig();
        // 日志数据库连接信息
        dataSource.setUrl(dbConfig.getUrl());
        dataSource.setUsername(StringUtils.opt(dbConfig.getUsername(),globalUsername));
        dataSource.setPassword(StringUtils.opt(dbConfig.getPassword(),globalPassword));
        dataSource.setDriverClassName(StringUtils.opt(dbConfig.getDriverClassName(),globalDriver));
        
        // 日志库连接池参数（可独立配置）
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(3);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(20000);
        dataSource.setTimeBetweenEvictionRunsMillis(45000);
        dataSource.setMinEvictableIdleTimeMillis(1200000);
        
        // 连接验证
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestWhileIdle(true);
        
        return dataSource;
    }

	
	

}
