package cn.gov.customs.demo.config;

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

import com.github.pagehelper.page.PageAutoDialect;
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.dao"},
    annotationClass = Mapper.class,
    sqlSessionFactoryRef = "demoSqlSessionFactory",
    sqlSessionTemplateRef = "demoSqlTemplate")
@EnableTransactionManagement
public class DemoDataSourceConfig {

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

  @Bean(name = "demoSqlSessionFactory")
  public SqlSessionFactory demoSqlSessionFactory() 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/demo/**/*.xml"));
    bean.setTypeAliasesPackage("cn.gov.customs.demo");
    return bean.getObject();
  }

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

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

}
