package com.bcxin.Infrastructures.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 雪花算法工具类
 */
@Component
public class SnowFlakeUtil {

    private static long machineId;
    private static long dataCenterId;

    @Value("${snowFlake.machineId:0}")
    public void setMachineId(long machineId) {
        SnowFlakeUtil.machineId = machineId;
    }

    @Value("${snowFlake.dataCenterId:0}")
    public void setDataCenterId(long dataCenterId) {
        SnowFlakeUtil.dataCenterId = dataCenterId;
    }

    /**
     * 初始化构造，无参构造有参函数，默认节点都是0
     */
    public SnowFlakeUtil() {
        this(0L, 0L);
    }

    public SnowFlakeUtil(long machineId, long dataCenterId) {
        this.machineId = machineId;
        this.dataCenterId = dataCenterId;
    }

    /**
     * 成员类，SnowFlakeUtil的实例对象的保存域
     */
    private static class IdGenHolder {
        private static final SnowFlakeUtil instance = new SnowFlakeUtil();
    }

    /**
     * 外部调用获取SnowFlakeUtil的实例对象，确保不可变
     */
    public static SnowFlakeUtil get() {
        return IdGenHolder.instance;
    }

    private Snowflake snowflake = IdUtil.createSnowflake(machineId, dataCenterId);

    public synchronized long id(){
        return snowflake.nextId();
    }

    public static Long getId() {
        return SnowFlakeUtil.get().id();
    }
}
