package com.huashe.park.common;

import java.time.Instant;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;

public class EnhancedIDGenerator {
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(EnhancedIDGenerator.class);

    // 基础参数配置（可通过构造函数注入）
    private static final long EPOCH = Instant.parse("2025-01-01T00:00:00Z").toEpochMilli();

    private static final int TIMESTAMP_BITS = 35; // 支持到2060年

    private static final int SEQUENCE_BITS = 12; // 4096/ms

    private static final int MACHINE_BITS = 4; // 支持16台机器

    private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1;

    // 分布式机器ID（0~15）
    private final long machineId;

    private final AtomicLong lastTimestamp = new AtomicLong(-1L);

    private final AtomicLong sequence = new AtomicLong(0);

    public EnhancedIDGenerator(int machineId) {
        if (machineId < 0 || machineId >= (1 << MACHINE_BITS)) {
            throw new IllegalArgumentException("机器ID范围 0~15");
        }
        this.machineId = machineId;
    }

    public String generate() {
        long currentTimestamp;
        long lastStamp;
        long currentSequence;

        do {
            currentTimestamp = System.currentTimeMillis() - EPOCH;
            lastStamp = lastTimestamp.get();

            // 处理时间回拨（最大容忍100ms）
            if (currentTimestamp < lastStamp) {
                handleClockDrift(lastStamp - currentTimestamp);
                currentTimestamp = System.currentTimeMillis() - EPOCH;
            }

            // 序列号重置条件
            if (currentTimestamp != lastStamp) {
                sequence.set(0);
            }

            currentSequence = sequence.getAndIncrement();
            if (currentSequence > MAX_SEQUENCE) {
                Thread.yield(); // 让出CPU等待下一毫秒
                currentTimestamp = System.currentTimeMillis() - EPOCH;
                sequence.set(0);
                currentSequence = 0;
            }

        }
        while (!lastTimestamp.compareAndSet(lastStamp, currentTimestamp));

        // 组合数值：35位时间戳 + 4位机器ID + 12位序列号 = 51位
        long combined = (currentTimestamp << (MACHINE_BITS + SEQUENCE_BITS)) | (machineId << SEQUENCE_BITS)
            | currentSequence;

        return encodeBase36(combined);
    }

    // 改进型Base36编码（消除前导零）
    private String encodeBase36(long number) {
        char[] buffer = new char[8];
        for (int i = 7; i >= 0; i--) {
            int digit = (int) (number % 36);
            buffer[i] = (digit < 10) ? (char) ('0' + digit) : (char) ('a' + digit - 10);
            number /= 36;
        }
        return new String(buffer);
    }

    // 时间回拨容错机制
    private void handleClockDrift(long driftMillis) {
        if (driftMillis > 100) {
            throw new IllegalStateException("检测到超过100ms的时间回拨");
        }
        try {
            Thread.sleep(driftMillis);
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        // 分布式测试示例
        EnhancedIDGenerator node1 = new EnhancedIDGenerator(1);
        EnhancedIDGenerator node2 = new EnhancedIDGenerator(2);

        System.out.println("节点1 ID: " + node1.generate()); // 示例：02H3D9MF
        System.out.println("节点2 ID: " + node2.generate()); // 示例：12K8F7LZ
        ThreadPoolExecutor threadPoolTaskExecutor = new ThreadPoolExecutor(10, 10, 100, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100));
        for (int i = 0; i < 100; i++) {
            threadPoolTaskExecutor.execute(() -> {
                log.info(node1.generate());
            });
        }
    }
}
