package cn.reghao.tnb.sb.multi.mybatis.ds;

import cn.reghao.tnb.sb.multi.mybatis.PageListInterceptor;
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.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author reghao
 * @date 2021-06-10 22:46:29
 */
@Configuration
@MapperScan(basePackages = "cn.reghao.tnb.sb.multi.mybatis.mapper.three",
        sqlSessionFactoryRef = "thirdSqlSessionFactory")
public class DataSourceThird {
    @Bean(name = "thirdDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.third")
    public DataSource thirdDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "thirdSqlSessionFactory")
    public SqlSessionFactory thirdSqlSessionFactory(@Qualifier("thirdDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setPlugins(new Interceptor[]{pageListInterceptorThird()});

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setDefaultFetchSize(100);
        configuration.setDefaultStatementTimeout(30);
        factoryBean.setConfiguration(configuration);

        // TODO 不使用 xml 文件，使用 @Select 等注解
        String location = "classpath*:mapper/three/*.xml";
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(location));
        return factoryBean.getObject();
    }

    private PageListInterceptor pageListInterceptorThird() {
        return new PageListInterceptor();
    }

    @Bean("thirdSqlSessionTemplate")
    public SqlSessionTemplate thirdSqlSessionTemplate(
            @Qualifier("thirdSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
}
