package com.testor.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.testor.enums.DatabaseIdEnum;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

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

@SpringBootConfiguration
public class MybatisPlusConfiguration {
    @Autowired
    private DataSource dataSource;

    @Value("${spring.datasource.dynamic.primary}")
    private String primaryDataSource;

    public MybatisPlusConfiguration() {
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        Map<String, DataSource> dataSourceMap = ((DynamicRoutingDataSource) dataSource).getCurrentDataSources();
        DruidDataSource druidDataSource = (DruidDataSource) dataSourceMap.get(primaryDataSource);
        String driverClassName = druidDataSource.getDriverClassName();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DatabaseIdEnum.getDbTypeByDriver(driverClassName)));
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    @Bean
    public DatabaseIdProvider databaseIdProvider() {
        VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        // 设置数据库厂商和databaseId别名
        for (DatabaseIdEnum databaseIdEnum : DatabaseIdEnum.values()) {
            properties.put(databaseIdEnum.getType(), databaseIdEnum.getName());
        }
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }
}
