package com.gyee.frame.common.conf;


import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.gyee.frame.common.dataSources.DataSourceType;
import com.gyee.frame.common.dataSources.DynamicDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Mybatis多数据源配置
 * 参考文章：https://www.cnblogs.com/geekdc/p/10963476.html
 * @ClassName: MybatisConfig
 * @author gyee
 * @date 2019-12-06 21:11
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.gyee.frame.mapper")
public class MybatisConfig {
	
	@Bean(name = "master")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource()
    {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "slave")
    @ConfigurationProperties("spring.datasource.druid.slave")
//    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource()
    {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "ticket")
    @ConfigurationProperties("spring.datasource.druid.ticket")
//    @ConditionalOnProperty(prefix = "spring.datasource.druid.ticket", name = "enabled", havingValue = "true")
    public DataSource ticketDataSource()
    {
        return DruidDataSourceBuilder.create().build();
    }

    @Autowired
    PaginationInterceptor paginationInterceptor;

    @Bean
    @Primary
    public DataSource dataSource(@Qualifier("master") DataSource masterDataSource,
                                         @Qualifier("slave") DataSource slaveDataSource,
                                         @Qualifier("ticket") DataSource ticketDataSource)
    {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
    	targetDataSources.put(DataSourceType.SLAVE.name(),slaveDataSource);
        targetDataSources.put(DataSourceType.TICKET.name(),ticketDataSource);
        return new DynamicDataSource(masterDataSource(), targetDataSources);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean ();
        factoryBean.setDataSource(dataSource(masterDataSource(), slaveDataSource(), ticketDataSource()));
        // 设置mapper.xml的位置路径
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/*/*.xml");
        // 设置model路径
        factoryBean.setTypeAliasesPackage("com.gyee.frame.model.*");
        factoryBean.setMapperLocations(resources);
        // 设置 MyBatis-Plus 分页插件
        Interceptor[] plugins = {paginationInterceptor};
        factoryBean.setPlugins(plugins);
        return factoryBean.getObject();
    }
    
    /**
     * 配置@Transactional注解事务
     * @param dataSource
     * @return
     * @author gyee
     * @Date 2019年12月7日 上午11:31:33
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 分页插件
     */
    @Bean(name = "paginationInterceptor")
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

}
