package cn.axzo.workflow.core.engine.id;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.cfg.IdGenerator;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 基于 Nacos 的雪花算法 ID 生成器
 *
 * @author wangli
 * @since 2024/5/24 21:04
 */
@Slf4j
public class BasedNacosSnowflakeIdGenerator implements IdGenerator {

    private final NacosServiceManager nacosServiceManager;
    private final NacosDiscoveryProperties nacosDiscoveryProperties;
    private static final long MAX_SEQUENCE = 99_999_999L;
    private static final AtomicLong sequence = new AtomicLong(0);
    private static volatile String lastTimestamp = "";
    private static int nodeId;

    public BasedNacosSnowflakeIdGenerator(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties) {
        this.nacosServiceManager = nacosServiceManager;
        this.nacosDiscoveryProperties = nacosDiscoveryProperties;
        init();
    }

    /**
     * 获取当前服务所有节点 + 增加服务监听
     *
     * @throws NacosException
     */
    @SneakyThrows
    private void init() {
        NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
        namingService.subscribe(nacosDiscoveryProperties.getService(), new EventListener() {
            @Override
            public void onEvent(Event event) {
                if (-1 == nacosDiscoveryProperties.getPort()) {
                    return;
                }
                nodeId = calcNodeId(((NamingEvent) event).getInstances());
            }
        });
    }

    /**
     * 用ip+port计算服务列表的索引
     *
     * @param instanceList
     * @return
     */
    private int calcNodeId(List<Instance> instanceList) {
        List<Long> ipPosrList = instanceList.stream()
                .map(x -> dealIpPort(x.getIp(), x.getPort()))
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());
        return ipPosrList.indexOf(dealIpPort(nacosDiscoveryProperties.getIp(), nacosDiscoveryProperties.getPort())) + 1;
    }

    /**
     * ip补0 + 端口号
     *
     * @param ip
     * @param port
     * @return
     */
    private static Long dealIpPort(String ip, int port) {
        String[] ips = ip.split("\\.");
        StringBuilder sbr = new StringBuilder();
        for (int i = 0; i < ips.length; i++) {
            sbr.append(new DecimalFormat("000").format(Integer.parseInt(ips[i])));
        }
        return Long.parseLong(sbr.toString() + port);
    }

    @Override
    public synchronized String getNextId() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        String timestamp = dateFormat.format(new Date());

        if (timestamp.equals(lastTimestamp)) {
            long currentSequence = sequence.incrementAndGet() % MAX_SEQUENCE;
            if (currentSequence == 0) {
                // 如果递增数已达到最大值，则等待下一毫秒
                timestamp = tilNextTimestamp(timestamp, dateFormat);
            }
        } else {
            sequence.set(0);
        }

        lastTimestamp = timestamp;

        return timestamp + String.format("%d%08d", nodeId, sequence.get());
    }

    private String tilNextTimestamp(String lastTimestamp, SimpleDateFormat dateFormat) {
        String timestamp = dateFormat.format(new Date());
        while (timestamp.equals(lastTimestamp)) {
            timestamp = dateFormat.format(new Date());
        }
        return timestamp;
    }
}
