package com.wzj.soopin.order.utils;

public class SnowflakeIdGenerator {
    // 起始时间戳（可以设置项目上线时间等固定时间，单位毫秒）
    private static final long START_TIMESTAMP = 1609459200000L; // 2021-01-01 00:00:00
    // 机器ID所占位数
    private static final long WORKER_ID_BITS = 5L;
    // 数据中心ID所占位数
    private static final long DATA_CENTER_ID_BITS = 5L;
    // 序列号所占位数
    private static final long SEQUENCE_BITS = 12L;
    // 最大的机器ID，2的WORKER_ID_BITS次方减1
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    // 最大的数据中心ID，2的DATA_CENTER_ID_BITS次方减1
    private static final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
    // 序列号最大值，2的SEQUENCE_BITS次方减1
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
    // 时间戳左移（WORKER_ID_BITS + DATA_CENTER_ID_BITS + SEQUENCE_BITS）位
    private static final long TIMESTAMP_LEFT_SHIFT = WORKER_ID_BITS + DATA_CENTER_ID_BITS + SEQUENCE_BITS;
    // 机器ID左移（DATA_CENTER_ID_BITS + SEQUENCE_BITS）位
    private static final long WORKER_ID_SHIFT = DATA_CENTER_ID_BITS + SEQUENCE_BITS;
    // 数据中心ID左移SEQUENCE_BITS位
    private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS;
    // 当前机器ID
    private long workerId;
    // 当前数据中心ID
    private long dataCenterId;
    // 序列号
    private long sequence = 0L;
    // 上次生成ID的时间戳
    private long lastTimestamp = -1L;
    /**
     * 构造函数
     * @param workerId 机器ID（取值范围0 - MAX_WORKER_ID）
     * @param dataCenterId 数据中心ID（取值范围0 - MAX_DATA_CENTER_ID ）
     */
    public SnowflakeIdGenerator(long workerId, long dataCenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("Worker ID can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("Data center ID can't be greater than %d or less than 0", MAX_DATA_CENTER_ID));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }
    /**
     * 生成唯一ID
     * @return 生成的唯一ID
     */
    public synchronized long nextId() {
        long timestamp = timeGen();
        // 若当前时间小于上一次生成ID的时间戳，说明系统时钟回退过，抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        // 同一毫秒内生成，则序列号递增
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            // 序列号溢出，等待到下一毫秒
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 不同毫秒生成，序列号重置为0
            sequence = 0L;
        }
        // 记录上一次生成ID的时间戳
        lastTimestamp = timestamp;
        // 生成唯一ID
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT) |
                (workerId << WORKER_ID_SHIFT) |
                (dataCenterId << DATA_CENTER_ID_SHIFT) |
                sequence;
    }
    /**
     * 获取当前时间戳（单位：毫秒）
     * @return 当前时间戳
     */
    private long timeGen() {
        return System.currentTimeMillis();
    }
    /**
     * 等待直到下一个毫秒
     * @param lastTimestamp 上一次生成ID的时间戳
     * @return 下一个毫秒的时间戳
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }
}
