package com.sqx.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class StandardShardingStrategyConf implements PreciseShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        Object valueObj = shardingValue.getValue();
        long value = 0;
        if (valueObj instanceof String) {
            // 如果是字符串类型，尝试解析为Long
            value = Long.parseLong((String) valueObj);

        } else if (valueObj instanceof Long) {
            // 如果是字符串类型，尝试解析为Long
            value = (long) valueObj;

        }
        // 根据ID对5取模来确定表名
        long tableIndex = value % 5;
        for (String tableName : availableTargetNames) {
            if (tableName.endsWith(String.valueOf(tableIndex))) {
                return tableName;
            }
        }
        throw new IllegalArgumentException();
    }
}