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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description 分片算法manager
 * @Author: ph
 * @Date: 2020/3/2 08:58
 */
@Component
public class ShardingAlgorithmManager {

    @Value("${new.sharding.db.size}")
    private Integer dbSize;

    @Value("${new.sharding.tb.size}")
    private Integer tbSize;

    public boolean compareIndex(Long oldUserId, Long newUserId) {
        if (Objects.equals(oldUserId, newUserId)) {
            return true;
        }
        if (!compareDbIndex(oldUserId, newUserId)) {
            return false;
        }
        int tbIndex0 = RoutingAlgorithm.routeTb(oldUserId, dbSize, tbSize);
        int tbIndex1 = RoutingAlgorithm.routeTb(newUserId, dbSize, tbSize);
        return tbIndex0 == tbIndex1;
//        int hashCode = oldUserId.toString().hashCode();
//        if (hashCode < 0) {
//            hashCode = -hashCode;
//        }
//        long db = hashCode % dbSize + 1;
//        long tb = hashCode / tbSize % tbSize;
//
//        int hashCodeNew = newUserId.toString().hashCode();
//        if (hashCodeNew < 0) {
//            hashCodeNew = -hashCodeNew;
//        }
//        long dbNew = hashCodeNew % dbSize + 1;
//        long tbNew = hashCodeNew / tbSize % tbSize;
//        return db == dbNew && tb == tbNew;
    }

    private boolean compareDbIndex(Long oldUserId, Long newUserId) {
        int dbIndex0 = RoutingAlgorithm.routeDb(oldUserId, dbSize);
        int dbIndex1 = RoutingAlgorithm.routeDb(newUserId, dbSize);
        return dbIndex0 == dbIndex1;
    }

    public static void main(String[] args) {
        int dbIndex0 = RoutingAlgorithm.routeDb(7766L, 2);
        int tbIndex0 = RoutingAlgorithm.routeTb(7766L, 2, 2);
        int dbIndex1 = RoutingAlgorithm.routeDb(6688, 2);
        int tbIndex1 = RoutingAlgorithm.routeTb(6688, 2, 2);
        System.out.println(dbIndex0);
        System.out.println(tbIndex0);

        System.out.println(dbIndex1);
        System.out.println(tbIndex1);
    }
}
