package com.hwrj.cloud.portal.util;



import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;

/**
 * @zdd
 */
public class GeneratorIdUtils {
    private long workerId;
    private long datacenterId = 0L;
    private long sequence = 0L;
    private long workerIdBits = 8L;
    private long sequenceBits = 12L;
    private long workerIdShift;
    private long datacenterIdShift;
    private long sequenceMask;
    private long lastTimestamp;

    public GeneratorIdUtils() {
        this.workerIdShift = this.sequenceBits;
        this.datacenterIdShift = this.sequenceBits + this.workerIdBits;
        this.sequenceMask = ~(-1L << (int)this.sequenceBits);
        this.lastTimestamp = -1L;
        this.workerId = (long)(255 & this.getLastIP());
    }

    public synchronized String nextId() {
        long timestamp = this.currentTime();
        if (timestamp < this.lastTimestamp) {
            throw new RuntimeException(String.format("时钟向后移动。拒绝在%d毫秒内生成id", this.lastTimestamp - timestamp));
        } else {
            if (this.lastTimestamp == timestamp) {
                this.sequence = this.sequence + 1L & this.sequenceMask;
                if (this.sequence == 0L) {
                    timestamp = this.nextMillis(this.lastTimestamp);
                }
            } else {
                this.sequence = 0L;
            }

            this.lastTimestamp = timestamp;
            long suffix = this.datacenterId << (int)this.datacenterIdShift | this.workerId << (int)this.workerIdShift | this.sequence;
            SimpleDateFormat timePe = new SimpleDateFormat("yyyyMMddHHMMssSSS");
            String datePrefix = timePe.format(timestamp);
            String s = datePrefix + suffix;
            return s;
        }
    }

    protected long nextMillis(long lastTimestamp) {
        long timestamp;
        for(timestamp = this.currentTime(); timestamp <= lastTimestamp; timestamp = this.currentTime()) {
        }

        return timestamp;
    }

    protected long currentTime() {
        return System.currentTimeMillis();
    }

    private byte getLastIP() {
        byte lastip = 0;

        try {
            InetAddress ip = InetAddress.getLocalHost();
            byte[] ipByte = ip.getAddress();
            lastip = ipByte[ipByte.length - 1];
        } catch (UnknownHostException var4) {
            var4.printStackTrace();
        }

        return lastip;
    }
}
