package com.reptileclient.jlifeapp.config.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.reptileclient.jlifeapp.dao.jz", sqlSessionTemplateRef = "nurseSqlSessionTemplate")
public class MyBatisConfigNurse {
    @Autowired
    private DataSourceConfig dataSourceConfig;

    static final String MAPPER_LOCATION = "classpath:mybatis/mapper/jz/*.xml";

    /**
     * 创建数据源
     */
    @Bean(name = "nurseDS")
    @Primary
    public DataSource getNurseDataSource() {
        DataSource build = DataSourceBuilder.create()
                .driverClassName(dataSourceConfig.getDriverClassName())
                .url(dataSourceConfig.getDbUrl_jz())
                .username(dataSourceConfig.getUsername_jz())
                .password(dataSourceConfig.getPassword_jz())
                .build();
        return build;
    }


    /**
     * 创建SessionFactory
     */
    @Bean(name = "nurseSqlSessionFactory")
    @Primary
    public SqlSessionFactory nurseSqlSessionFactory(@Qualifier("nurseDS") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置mapper配置文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return bean.getObject();
    }

    /**
     * 创建事务管理器
     */
    @Bean("nurseTransactionManger")
    @Primary
    public DataSourceTransactionManager nurseTransactionManger(@Qualifier("nurseDS") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 创建SqlSessionTemplate
     */
    @Bean(name = "nurseSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate nurseSqlSessionTemplate(@Qualifier("nurseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
