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 CommonNumberPreciseTableAlgorithm implements PreciseShardingAlgorithm {

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