package cn.freemud.core.db;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: CouponDataSourcesConfig
 * @Package com.freemud.data.source.config
 * @Description:
 * @author: chaopeng.lv
 * @date: 2018/5/16 17:08
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties({Db2DataSourcesProperties.class})
@MapperScan(basePackages = {"cn.freemud.manager.db2.dao"}
        , sqlSessionFactoryRef = "db2SqlSessionFactory")
public class Db2DataSourcesConfig {

    /**
     * 配置数据源
     *
     * @return
     */
    @Bean("db2DataSource")
    public DataSource dataSource(Db2DataSourcesProperties db2DataSourcesProperties) {
        return DataSourceBuildUtil.init(db2DataSourcesProperties);
    }

    // 创建session工厂
    @Bean("db2SqlSessionFactory")
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db2/*.xml"));
        return sessionFactoryBean.getObject();
    }

    // 创建事务管理（按需添加）
    @Bean("db2DataSourceTransactionManager")
    public DataSourceTransactionManager db2DataSourceTransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    // 会话管理
    @Bean("db2SqlSessionTemplate")
    public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
