package com.cf.imes.module.executor.util;

/**
 * @projectName: cf_imes_back
 * @author: 晨丰科技
 * @date: 2024/3/5 10:55
 * 生产单id创建
 */
public class IdGenerator {
    private static final long START_TIMESTAMP = 1613203200000L; // 设置起始时间戳为2021-02-13 00:00:00
    private static final long WORKER_ID_BITS = 5L;
    private static final long DATABASE_ID_BITS = 5L;
    private static final long SEQUENCE_BITS = 12L;

    private static final long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS);
    private static final long MAX_DATABASE_ID = -1L ^ (-1L << DATABASE_ID_BITS);

    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final long DATABASE_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATABASE_ID_BITS;

    private long workerId;
    private long databaseId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public IdGenerator(long workerId, long databaseId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID must be between 0 and " + MAX_WORKER_ID);
        }
        if (databaseId > MAX_DATABASE_ID || databaseId < 0) {
            throw new IllegalArgumentException("Database ID must be between 0 and " + MAX_DATABASE_ID);
        }
        this.workerId = workerId;
        this.databaseId = databaseId;
    }

    public synchronized long generateId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate ID for " + (lastTimestamp - timestamp) + " milliseconds");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & ((1 << SEQUENCE_BITS) - 1);
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | (databaseId << DATABASE_ID_SHIFT)
                | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

}
