package com.liquidnet.commons.lang.util;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class IDGenerator {
    private static final long twepoch = 1624118400000L;
//    private static final long twepoch = 961421243000L;
    private static final long workerIdBits = 2L;
    private static final long dataCenterIdBits = 1L;
    //// 最大支持机器节点数0~31，一共32个
    // 最大支持数据中心节点数0~31，一共32个
    @SuppressWarnings({"PointlessBitwiseExpression", "FieldCanBeLocal"})
    private static final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    @SuppressWarnings({"PointlessBitwiseExpression", "FieldCanBeLocal"})
    private static final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits);
    // 序列号12位
    private static final long sequenceBits = 12L;
    // 机器节点左移12位
    private static final long workerIdShift = sequenceBits;
    // 数据中心节点左移17位
    private static final long dataCenterIdShift = sequenceBits + workerIdBits;
    // 时间毫秒数左移22位
    private static final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
    @SuppressWarnings({"PointlessBitwiseExpression", "FieldCanBeLocal"})
    private static final long sequenceMask = -1L ^ (-1L << sequenceBits);// 4095

    private static final long workerId;
    private static final long dataCenterId;
    private static final boolean useSystemClock;
    private static long sequence = 0L;
    private static long lastTimestamp = -1L;

    static {
        workerId = getMachineNum() & maxWorkerId;
        dataCenterId = 1;
        useSystemClock = true;
    }

    /* ---------------------------------------------------------------------------------------- */

    public static synchronized String nextSnowId() {
        long timestamp = genTime();
        if (timestamp < lastTimestamp) {
            if (lastTimestamp - timestamp < 2000) {
                // 容忍2秒内的回拨，避免NTP校时造成的异常
                timestamp = lastTimestamp;
            } else {
                // 如果服务器时间有问题(时钟后退) 报错。
                throw new IllegalStateException(String.format("Clock moved backwards. Refusing to generate id for %sms", lastTimestamp - timestamp));
            }
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        long l = ((timestamp - twepoch) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) | (workerId << workerIdShift) | sequence;

//        return l;
        return l + ("" + System.nanoTime()).substring(9);
    }

    /**
     * 根据订单id生成订单号
     *
     * @param orderTicketId
     * @return
     */
    public static String ticketOrderCode(String orderTicketId) {
        String number = orderTicketId;
        int len = orderTicketId.length();
        String time = System.currentTimeMillis() / 1000 + "";
        String orderCode = "T" + number.substring(0, len - 4);
        orderCode += time.substring(7, 8);
        orderCode += number.substring(len - 2);
        orderCode += time.substring(8, 9);
        orderCode += number.substring(len - 4, len - 2);
        return orderCode;
    }

    /**
     * 根据 订单号生成qrCode
     *
     * @param orderTicketId
     * @return String
     */
    public static String ticketQrCode(String orderTicketId) {
        String qrCode = MD5Utils.md5(orderTicketId).toLowerCase();
        return "QR" + qrCode.substring(5) + "" + qrCode.substring(0, 4);
    }

    private static long genTime() {
        return useSystemClock ? SystemClock.now() : System.currentTimeMillis();
    }

    private static long tilNextMillis(long lastTimestamp) {
        long timestamp = genTime();
        // 循环直到操作系统时间戳变化
        while (timestamp == lastTimestamp) {
            timestamp = genTime();
        }
        if (timestamp < lastTimestamp) {
            // 如果发现新的时间戳比上次记录的时间戳数值小，说明操作系统时间发生了倒退，报错
            throw new IllegalStateException(
                    String.format("Clock moved backwards. Refusing to generate id for %sms", lastTimestamp - timestamp));
        }
        return timestamp;
    }

    private static long getMachineNum() {
        long machinePiece;
        StringBuilder sb = new StringBuilder();
        Enumeration<NetworkInterface> e = null;
        try {
            e = NetworkInterface.getNetworkInterfaces();

            while (e.hasMoreElements()) {
                NetworkInterface ni = e.nextElement();
                sb.append(ni.toString());
            }
        } catch (SocketException e1) {
            e1.printStackTrace();
        }
        machinePiece = sb.toString().hashCode();
        System.out.printf("\n###MachineNum=%s, MachineCodeString=%s\n\n", machinePiece, sb);
        return machinePiece;
    }

    /* ---------------------------------------------------------------------------------------- */

    public long getWorkerId(long id) {
        return id >> workerIdShift & ~(-1L << workerIdBits);
    }

    public long getDataCenterId(long id) {
        return id >> dataCenterIdShift & ~(-1L << dataCenterIdBits);
    }

    public long getGenerateDateTime(long id) {
        return (id >> timestampLeftShift & ~(-1L << 41L)) + twepoch;
    }

    /* ---------------------------------------------------------------------------------------- */
}
