package com.seamew.lottery.domain.support.ids.policy;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import com.seamew.lottery.common.Constants;
import com.seamew.lottery.domain.support.ids.IIdGenerator;
import com.seamew.lottery.domain.support.ids.annotation.IdMode;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Author: seamew
 * @Title: SnowFlake
 * @CreateTime: 2023年02月16日 10:08:00
 * @Description: 15位雪花算法推荐
 * @Version: 1.0
 */
@Component
@IdMode(idMode = Constants.Ids.SnowFlake)
public class SnowFlake implements IIdGenerator {

    private Snowflake snowflake;

    @PostConstruct
    public void init() {
        // 0 ~ 31 位，可以采用配置的方式使用
        long workerId;
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        } catch (Exception e) {
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
        workerId = workerId >> 16 & 31;
        long dataCenterId = 1L;
        snowflake = IdUtil.getSnowflake(workerId, dataCenterId);
    }

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

}
