package cn.wisenergy.common.config.multipleDatasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.github.pagehelper.PageInterceptor;
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.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @description:
 * @author: nh
 * @create: 2021-04-20 10:25
 **/
@Configuration
@MapperScan(basePackages = "cn.wisenergy.oaMapper", sqlSessionFactoryRef = "oaSqlSessionFactory")
public class OaDataSourceConfig {

    @Bean("oaDataSource")
    @ConfigurationProperties("spring.datasource.druid.one")
    public DataSource dataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("oaSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("oaDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath:/oaMapper/*Mapper.xml"));
        //分页插件
        Interceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        //数据库
        properties.setProperty("helperDialect", "mysql");
        //是否将参数offset作为PageNum使用
        properties.setProperty("offsetAsPageNum", "true");
        //是否进行count查询
        properties.setProperty("rowBoundsWithCount", "true");
        //是否分页合理化
        properties.setProperty("reasonable", "false");
        interceptor.setProperties(properties);
        bean.setPlugins(new Interceptor[] {interceptor});
        return bean.getObject();
    }

    @Bean("oaSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionFactory(@Qualifier("oaSqlSessionFactory")SqlSessionFactory sqlSessionFactory ){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("oaDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
