package com.zm.order.tool.server.sharding;

import com.zm.order.tool.server.component.ThreadContext;
import com.zm.order.tool.server.constants.CommonConstants;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @Description 通用数字分库算法
 * @Author: ph
 * @Date: 2020/3/20 13:39
 */
public class CommonNumberPreciseDataBaseAlgorithm implements PreciseShardingAlgorithm {

    @Override
    public String doSharding(Collection collection, PreciseShardingValue preciseShardingValue) {
        Long value = Long.valueOf(String.valueOf(preciseShardingValue.getValue()));
        if (value < 0) {
            value = 0 - value;
        }
        Long mod = value % collection.size();
        ThreadContext.setDbSize(collection.size());
        for (Object each : collection) {
            String dsName = String.valueOf(each);
            if (dsName.endsWith(CommonConstants.SHARDING_SPLIT + mod)) {
                return dsName;
            }
        }
        throw new UnsupportedOperationException();
    }
}
