package cn.reghao.tnb.content.app.config.shard;

import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;

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

/**
 * @author reghao
 * @date 2022-03-15 18:46:37
 */
//@Configuration
public class ShardingDataSourceConfig {
    private final String database = "reghao_oss_rdb";

    //@Bean
    public DataSource getShardingDataSource() throws SQLException {
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.getTableRuleConfigs().add(getTableRuleConfiguration());
        //shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("qq", "qq_mobile_$->{qq % 4}"));
        shardingRuleConfig.setDefaultTableShardingStrategyConfig(
                new StandardShardingStrategyConfiguration("qq", new ModuloShardingTableAlgorithm()));
        return ShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, new Properties());
    }

    private TableRuleConfiguration getTableRuleConfiguration() {
        String logicalTalbe = "qq_mobile";
        String actualDataNodes = database + ".qq_mobile_$->{0..3}";
        return new TableRuleConfiguration(logicalTalbe, actualDataNodes);
    }

    private Map<String, DataSource> createDataSourceMap() {
        Map<String, DataSource> result = new HashMap<>();
        result.put(database, DataSourceUtil.createDataSource(database));
        return result;
    }
}
