package com.yeejoin.amos.patrol.core.common.request;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.io.Serializable;

/**
 * @description:
 * @author: tw
 * @createDate: 2023/4/10
 */
public class MyIdGeneratorConfig implements IdentifierGenerator {


    /**
     * 终端ID
     */
    @Value("${generator.worker_id}")
    public  long WORKER_ID;

    /**
     * 数据中心id
     */
    @Value("${generator.datacenter_id}")
    public  long DATACENTER_ID;

    private Snowflake snowflake = IdUtil.createSnowflake(WORKER_ID, DATACENTER_ID);

    @PostConstruct
    public void init() {
        WORKER_ID = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
    }

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

    public synchronized long snowflakeId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.getSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }


    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object)
            throws HibernateException {
        return snowflakeId(WORKER_ID, DATACENTER_ID);
    }



}
