package com.ruoyi.common.utils;

import java.math.BigInteger;

public class Base36Utils {
    private static final String BASE36_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    // 编码方法
    public static String encode(BigInteger number) {
        if (number.compareTo(BigInteger.ZERO) < 0) {
            throw new IllegalArgumentException("Number must be non-negative");
        }
        StringBuilder result = new StringBuilder();
        while (number.compareTo(BigInteger.ZERO) > 0) {
            BigInteger[] divmod = number.divideAndRemainder(BigInteger.valueOf(36));
            number = divmod[0];
            int remainder = divmod[1].intValue();
            result.insert(0, BASE36_CHARS.charAt(remainder));
        }
        return result.length() == 0 ? "0" : result.toString();
    }

    // 解码方法
    public static BigInteger decode(String base36) {
        BigInteger result = BigInteger.ZERO;
        for (char c : base36.toUpperCase().toCharArray()) {
            int digit = BASE36_CHARS.indexOf(c);
            if (digit == -1) {
                throw new IllegalArgumentException("Invalid Base36 character: " + c);
            }
            result = result.multiply(BigInteger.valueOf(36)).add(BigInteger.valueOf(digit));
        }
        return result;
    }
}
