package com.sunyard.config;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

/**
 * @author liulu
 * @since 2024/10/28
 */
@Configuration
@MapperScan({"com.sunyard.ssp.**.mapper","com.sunyard.chsm.**.mapper"})
public class MyBatisConfig {

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 如果配置多个插件, 切记分页最后添加
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.DM));
        return interceptor;
    }

    @Bean
    public DatabaseIdProvider databaseIdProvider() {
        VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider(){
            @Override
            public String getDatabaseId(DataSource dataSource) {
                String databaseId = super.getDatabaseId(dataSource);
                if (StrUtil.isBlank(databaseId)){
                    throw new NullPointerException("多数据库标识为空，请检查数据库连接情况");
                }
                return databaseId;
            }
        };
        Properties properties = new Properties();
        properties.put("Oracle","oracle");
        properties.put("MySQL","mysql");
        properties.put("DM","dm");
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }

}
