package com.ssyf.plugs.mysql.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.ssyf.common.core.constants.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
* 数据库配置
* @author huwei
* @date 2022/7/6 11:00
*/
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "spring.datasource.base" ,name = "jdbcUrl")
@MapperScan(basePackages = BaseDatasourceConfig.MAPPER_PATH, sqlSessionFactoryRef = "baseSqlSessionFactory")
public class BaseDatasourceConfig {

    /**
     * mapper所在路径
     */
    public static final String MAPPER_PATH = SystemConstants.PROJECT_BASE_PACKAGE + ".**.mapper";
    /**
     * xml所在路径
     */
    public static final String XML_PATH = "classpath*:".concat(SystemConstants.PROJECT_BASE_PACKAGE.replace(".","/")).concat("/**/*.xml");

    @Primary
    @Bean(name = "base")
    @ConfigurationProperties(prefix = "spring.datasource.base")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "baseSqlSessionFactory")
    public SqlSessionFactory datasource1SqlSessionFactory(@Qualifier("base") DataSource datasource)
            throws Exception {
        log.info("mybaits mapper扫描路径：".concat(MAPPER_PATH));
        log.info("mybaits xml扫描路径：".concat(XML_PATH));
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(datasource);
        // 设置mybatis的xml所在位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(XML_PATH));
        bean.setPlugins(paginationInterceptor());
        return bean.getObject();
    }

    /**
     * 分页插件
     * paginationInterceptor.setLimit(你的最大单页限制数量，默认 50 条，小于 0 如 -1 不受限制);
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLimit(50);
        return paginationInterceptor;
    }
}