package cn.qinys.platform.base.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * Description:
 * Auth: tanlie
 * Date: 2022-11-03 09:16
 */

@Component
public class SnowflakeIdWorker {
    Logger logger = LoggerFactory.getLogger(SnowflakeIdWorker.class);

    //起始的时间戳
    private final static long START_STAMP = 1577808000000L;

    //每一部分占用的位数
    private final static long SEQUENCE_BIT = 12; //序列号占用的位数
    private final static long WORK_ID_BIT = 10;   //机器标识占用的位数

    //每一部分的最大值
    private final static long MAX_WORK_ID = ~(-1L << WORK_ID_BIT); // 2^10 - 1 = 1023
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT); // 毫秒内序列，12位，2^12 = 4096个数字

    //每一部分向左的位移
    private final static long WORK_ID_LEFT = SEQUENCE_BIT; // 业务ID左移12位
    private final static long TIMESTAMP_LEFT = SEQUENCE_BIT + WORK_ID_BIT; //时间戳左移22位


    private long sequence = 0L; //序列号
    private long lastStamp = -1L;//上一次时间戳

    private final long snowWorkId; // 业务id

    /**
     * 无参构造
     * workId (0~1023)
     */
    public SnowflakeIdWorker() {
        Random r = new Random();
        this.snowWorkId = r.nextInt((1023) + 1);
        logger.info("work id = {}",this.snowWorkId );
    }

    /**
     * 构造函数
     *
     * @param snowWorkId 工作ID(0-31)
     */
    public SnowflakeIdWorker(long snowWorkId) {
        if (snowWorkId > MAX_WORK_ID || snowWorkId < 0) {
            throw new RuntimeException("workId must between 0 and 1023");
        }
        this.snowWorkId = snowWorkId;
    }

    /**
     * 获取下一个ID(线程安全)
     *
     * @return SnowFlakeId
     */
    public synchronized long nextId() {
        long currStamp = getNewStamp();
        if (currStamp < lastStamp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStamp == lastStamp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStamp = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }
        lastStamp = currStamp;
        return (currStamp - START_STAMP) << TIMESTAMP_LEFT //时间戳部分
                | snowWorkId <<    WORK_ID_LEFT    //数据中心部分
                | sequence;                             //序列号部分
    }

    /**
     * 获取下一个ID(线程安全)
     *
     * @return SnowFlakeId
     */
    public synchronized String nextIdStr() {
        long currStamp = getNewStamp();
        if (currStamp < lastStamp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
        if (currStamp == lastStamp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStamp = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }
        lastStamp = currStamp;
        return String.valueOf((currStamp - START_STAMP) << TIMESTAMP_LEFT //时间戳部分
                | snowWorkId <<    WORK_ID_LEFT    //数据中心部分
                | sequence);                             //序列号部分
    }


    /**
     * 阻塞到下一毫秒, 直到获得新的时间戳
     *
     * @return 当前时间戳
     */
    private long getNextMill() {
        long mill = getNewStamp();
        while (mill <= lastStamp) {
            mill = getNewStamp();
        }
        return mill;
    }

    /**
     * 返回以毫秒为单位的当前时间
     *
     * @return 当前时间(毫秒)
     */
    private long getNewStamp() {
        return System.currentTimeMillis();
    }



}
