package com.tzy.common.utils;

import java.math.BigInteger;

/**
 * BASE62
 */
public class BASE62Utils {

    private static final String BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static void main(String[] args) {
        // 模拟生成短链接
        //String i = encode(10000);
        //String i = encode(System.currentTimeMillis());
        // System.out.println("Generated Short Link Code: " + i);
        //System.out.println("Generated Short Link Code: " + decode(i));
        // System.out.println("Generated Short Link Code: " + decode("i2SPPRhg"));
    }

    /**
     * Base10数字转Base62
     * @param num 十进制数字
     * @return Base62编码的字符串
     */
    public static String encode(long num) {
        StringBuilder sb = new StringBuilder();
        do {
            int remainder = (int)(num % 62);
            sb.append(BASE62.charAt(remainder));
            num /= 62;
        } while (num > 0);
        return sb.reverse().toString();
    }

    /**
     * Base62编码的字符串转十进制数字
     * @param base62String
     * @return 十进制数字
     */
    public static long decode(String base62String) {
        BigInteger decoded = BigInteger.ZERO;
        for (int i = 0; i < base62String.length(); i++) {
            char c = base62String.charAt(i);
            int position = BASE62.indexOf(c);
            decoded = decoded.multiply(BigInteger.valueOf(62)).add(BigInteger.valueOf(position));
        }
        return decoded.longValue();
    }
}
