package cn.gov.customs.demo.government.config;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.ibatis.annotations.Mapper;
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.mybatis.spring.boot.autoconfigure.SpringBootVFS;
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 org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * DateSourceConfig content
 *
 * @author chuxianming
 * @date 2024-05-24 10:18:12
 */
@Configuration
@MapperScan(
    basePackages = {"cn.gov.customs.demo.government.dao"},
    annotationClass = Mapper.class,
    sqlSessionFactoryRef = "governmentSqlSessionFactory",
    sqlSessionTemplateRef = "governmentSqlTemplate")
@EnableTransactionManagement
public class GovernmentDataSourceConfig {

  @Resource
  private MybatisProperties properties;
  @Resource
  @Qualifier("GOVERNMENTDataSource")
  private DataSource dataSource;

  @Bean(name = "governmentSqlSessionFactory")
  public SqlSessionFactory governmentSqlSessionFactory() throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setConfiguration(this.properties.getConfiguration());
    bean.setVfs(SpringBootVFS.class);
    bean.setDataSource(dataSource);
    bean.setMapperLocations(
        new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/government/*.xml"));
    bean.setTypeAliasesPackage("cn.gov.customs.demo.government");
    return bean.getObject();
  }

  @Bean(name = "governmentSqlTemplate")
  public SqlSessionTemplate governmentSqlTemplate(
      @Qualifier("governmentSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }

  @Bean(name="governmentTransactionManager")
  public PlatformTransactionManager governmentTransactionManager() {
    return new DataSourceTransactionManager(this.dataSource);
  }
}
