package com.tofly.xrtygis.config;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.tofly.mybatisplus.config.MapWrapperFactory;
import com.tofly.mybatisplus.config.MybatisKeyGenerator;
import com.tofly.mybatisplus.config.MybatisPlusConfigurer;
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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;

@Configuration
@MapperScan(basePackages = {"com.tofly.*.callCenterMapper"}, sqlSessionTemplateRef  = "secondSqlSessionTemplate")
public class DruidConfigSecond {
    @Autowired
    private MybatisPlusConfigurer mybatisPlusConfigurer;
    @Autowired
    private MybatisKeyGenerator mybatisKeyGenerator;
    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:callCenterMapper/*.xml"));
        bean.setPlugins(mybatisPlusConfigurer.paginationInterceptor());
        bean.setObjectWrapperFactory(new MapWrapperFactory());
        //设置全局配置
        GlobalConfig config = mybatisPlusConfigurer.globalConfig();
        config.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerator(mybatisKeyGenerator));
        bean.setGlobalConfig(config);
        return bean.getObject();
    }

    @Bean(name = "secondTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("secondDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "secondSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
