package com.pingpang.config;

import java.sql.SQLException;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
@Primary //在同样的DataSource中，首先使用被标注的DataSource
@EnableAutoConfiguration
@Component
public class DruidDataSourceConfig extends DataSourceProperties{

	private Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class);

	 @Value("${spring.datasource.druid.url}")
	    private String dbUrl;

	    @Value("${spring.datasource.druid.username}")
	    private String username;

	    @Value("${spring.datasource.druid.password}")
	    private String password;

	    @Value("${spring.datasource.druid.driverClassName}")
	    private String driverClassName;

	    @Value("${spring.datasource.druid.initial-size}")
	    private int initialSize;

	    @Value("${spring.datasource.druid.max-active}")
	    private int maxActive;

	    @Value("${spring.datasource.druid.min-idle}")
	    private int minIdle;

	    @Value("${spring.datasource.druid.max-wait}")
	    private int maxWait;

	    @Value("${spring.datasource.druid.pool-prepared-statements}")
	    private boolean poolPreparedStatements;

	    @Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}")
	    private int maxPoolPreparedStatementPerConnectionSize;

	    @Value("${spring.datasource.druid.time-between-eviction-runs-millis}")
	    private int timeBetweenEvictionRunsMillis;

	    @Value("${spring.datasource.druid.min-evictable-idle-time-millis}")
	    private int minEvictableIdleTimeMillis;

	    @Value("${spring.datasource.druid.max-evictable-idle-time-millis}")
	    private int maxEvictableIdleTimeMillis;

	    @Value("${spring.datasource.druid.validation-query}")
	    private String validationQuery;

	    @Value("${spring.datasource.druid.test-while-idle}")
	    private boolean testWhileIdle;

	    @Value("${spring.datasource.druid.test-on-borrow}")
	    private boolean testOnBorrow;

	    @Value("${spring.datasource.druid.test-on-return}")
	    private boolean testOnReturn;

	    @Value("${spring.datasource.druid.filters}")
	    private String filters;

	    @Value("{spring.datasource.druid.connection-properties}")
	    private String connectionProperties;

	    /**
	     * Druid 连接池配置
	     */
	    @Bean     //声明其为Bean实例
	    public DruidDataSource dataSource() {
	        DruidDataSource datasource = new DruidDataSource();
	        datasource.setUrl(dbUrl);
	        datasource.setUsername(username);
	        datasource.setPassword(password);
	        datasource.setDriverClassName(driverClassName);
	        datasource.setInitialSize(initialSize);
	        datasource.setMinIdle(minIdle);
	        datasource.setMaxActive(maxActive);
	        datasource.setMaxWait(maxWait);
	        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
	        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
	        datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
	        datasource.setValidationQuery(validationQuery);
	        datasource.setTestWhileIdle(testWhileIdle);
	        datasource.setTestOnBorrow(testOnBorrow);
	        datasource.setTestOnReturn(testOnReturn);
	        datasource.setPoolPreparedStatements(poolPreparedStatements);
	        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
	        try {
	            datasource.setFilters(filters);
	        } catch (Exception e) {
	            logger.error("druid configuration initialization filter", e);
	        }
	        datasource.setConnectionProperties(connectionProperties);
	        return datasource;
	    }
	    
    /**
     * JDBC操作配置
     */
    @Bean(name = "dataOneTemplate")
    public JdbcTemplate jdbcTemplate (@Autowired DruidDataSource dataSource){
        return new JdbcTemplate(dataSource) ;
    }    
    
    @Bean
    public ServletRegistrationBean statViewServle(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        // IP白名单
        servletRegistrationBean.addInitParameter("allow","139.159.144.33,192.168.0.28,192.168.1.218,127.0.0.1");
        // IP黑名单(共同存在时，deny优先于allow)
        servletRegistrationBean.addInitParameter("deny","192.168.1.100");
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername","druid");
        servletRegistrationBean.addInitParameter("loginPassword","1");
        //是否能够重置数据
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean statFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //添加过滤规则
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的格式
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
