package com.dhcc.finance.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.dhcc.finance.ibatis.SQLCostStatisticsInterceptor;
import com.mysql.cj.jdbc.MysqlDataSource;
/**
 * @ClassName: MyBatisConfigPms 
 * @Description: TODO(mysql配置类)
 * @author lipeng 
 * @date 2019年10月12日 下午11:08:07
 * @see
 */
@Configuration
@MapperScan(basePackages = "com.dhcc.finance.main.dao", sqlSessionTemplateRef = "pmsSqlSessionTemplate")
public class MyBatisConfigPms {
    private static final String MAPPER_LOCATION = "classpath:mapper/mysql/*.xml";
	// 配置数据源
	@Primary
	@Bean(name = "pmsDataSource")
	public DataSource pmsDataSource(DBConfigMysql dBConfigMysql) throws SQLException {
		MysqlDataSource mysqlXaDataSource = new MysqlDataSource();
		mysqlXaDataSource.setUrl(dBConfigMysql.getUrl());
		mysqlXaDataSource.setPassword(dBConfigMysql.getPassword());
		mysqlXaDataSource.setUser(dBConfigMysql.getUsername());
		return mysqlXaDataSource;
	}
	@Primary
	@Bean(name = "pmsSqlSessionFactory")
	public SqlSessionFactory pmsSqlSessionFactory(@Qualifier("pmsDataSource") DataSource dataSource, MybatisProperties mybatisProperties,SQLCostStatisticsInterceptor sqlCostStatisticsInterceptor)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); // 创建session工厂
		bean.setDataSource(dataSource); // 设置数据源 
		bean.setConfiguration(mybatisProperties.getConfiguration());
		bean.setPlugins(new Interceptor[] {sqlCostStatisticsInterceptor});
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      bean.setMapperLocations(resolver.getResources(MyBatisConfigPms.MAPPER_LOCATION));  // 指定mapper.xml文件的位置

		
		return bean.getObject();  //返回FactoryBean创建的Bean实例
	}
	
	@Primary
	@Bean(name = "pmsSqlSessionTemplate")
	public SqlSessionTemplate pmsSqlSessionTemplate(
			@Qualifier("pmsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}