package com.example.repurchase.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import java.sql.Connection;
import java.sql.SQLException;


@Configuration
@Primary
@PropertySource("classpath:/properties/sqlServer.properties")
public class SqlServerDruid {

    public static DruidDataSource dataSource;

    @Value("${sqlServer.driver}")
    private String driver;
    @Value("${sqlServer.url}")
    private String url;
    @Value("${sqlServer.username}")
    private String username;
    @Value("${sqlServer.password}")
    private String password;
    @Value("${sqlServer.urlMaster}")
    private String urlMaster;
    @Value("${sqlServer.usernameMaster}")
    private String usernameMaster;
    @Value("${sqlServer.passwordMaster}")
    private String passwordMaster;
    @Value("${sqlServer.initialSize}")
    private int initialSize;
    @Value("${sqlServer.maxActive}")
    private int maxActive;
    @Value("${sqlServer.minIdle}")
    private int minIdle;
    @Value("${sqlServer.maxWait}")
    private int maxWait;


    @Bean(autowire = Autowire.BY_NAME, value = "sqlServerConnection")
    public Connection sqlServerConnection() throws SQLException {
        dataSource = new DruidDataSource();
        //四个基本属性
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        //其他属性
        //初始大小
        dataSource.setInitialSize(initialSize);
        //最大大小
        dataSource.setMaxActive(maxActive);
        //最小大小
        dataSource.setMinIdle(minIdle);
        //检查时间
        dataSource.setMaxWait(maxWait);
        return dataSource.getConnection();
    }

    @Bean(autowire = Autowire.BY_NAME, value = "sqlServerConnectionMaster")
    public Connection sqlServerConnectionMaster() throws SQLException {
        dataSource = new DruidDataSource();
        //四个基本属性
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(urlMaster);
        dataSource.setUsername(usernameMaster);
        dataSource.setPassword(passwordMaster);
        //其他属性
        //初始大小
        dataSource.setInitialSize(initialSize);
        //最大大小
        dataSource.setMaxActive(maxActive);
        //最小大小
        dataSource.setMinIdle(minIdle);
        //检查时间
        dataSource.setMaxWait(maxWait);
        return dataSource.getConnection();
    }
}
