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.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;

/**
 * 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({DataSourcesProperties.class})
@MapperScan(basePackages = {"cn.freemud.manager.dao","com.freemud.sdk.api.assortment.orderdistributor.mapper","com.freemud.api.assortment.datamanager.manager",
        "com.freemud.api.assortment.datamanager.queue.dao","com.freemud.api.assortment.datamanager.rbac.dao","com.freemud.api.assortment.datamanager.queue.entity"}
        , sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourcesConfig {

    /**
     * 配置数据源
     *
     * @return
     */
    @Bean("dataSource")
    @Primary
    public DataSource dataSource(DataSourcesProperties dataSourcesProperties) {
        return DataSourceBuildUtil.init(dataSourcesProperties);
    }

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

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

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

}
