package com.seer.teach.common.utils;

import java.net.NetworkInterface;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicLong;

public class OrderIdGenerator {
    // 序列号（每毫秒最大99999）
    private static final AtomicLong SEQUENCE = new AtomicLong(0);
    // 机器ID（3位）
    private static int MACHINE_ID;
    // 时间格式化器
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    public static final String PAY_REFUND_ORDER_PREFIX = "PR";

    public static final String PAY_RECHARGE_ORDER_PREFIX = "PR";

    public static final String PAY_ORDER_PREFIX = "PP";

    public static final String MALL_ORDER_PREFIX = "MP";

    public static final String MALL_CHILD_ORDER_PREFIX = "MPC";

    public static final String MALL_MERCHANT_ORDER_PREFIX = "MMW";

    static {
        try {
            // 获取MAC地址并生成机器ID
            StringBuilder macSB = new StringBuilder();
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    for (byte b : mac) {
                        macSB.append(String.format("%02X%s", b, (b < mac.length - 1) ? "-" : ""));
                    }
                    break;
                }
            }
            // 生成2位机器ID
            MACHINE_ID = Math.abs(macSB.toString().hashCode() % 100);
        } catch (Exception e) {
            // 异常时使用默认ID
            MACHINE_ID = 0;
        }
    }

    public static String generateOrderId() {
        long sequence = SEQUENCE.updateAndGet(seq -> (seq + 1) % 100);
        // 组合订单号
        return String.format(
                "%s%02d%02d",
                dateTimeFormatter.format(LocalDateTime.now()),
                MACHINE_ID,
                sequence
        );
    }

    public static String generateOrderId(String prefix) {
        return prefix + generateOrderId();
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }

}