package top.continew.admin.utils;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;

import javax.xml.bind.DatatypeConverter;
import java.security.SecureRandom;
import java.util.Random;

public class InviteCodeGenerator {
    private static final int CODE_LENGTH = 32; // 邀请码长度
    private static final int RANDOM_CODE_LENGTH = 8; // 随机码长度
    private static final SecureRandom RANDOM = new SecureRandom();

    private static final String[] CHARACTERS = new String[]{"a", "b", "c", "d", "e", "f", "g", "h",
            "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
            "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
            "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"
    };


    public static String generateInviteCode() {
        StringBuilder code = new StringBuilder();
        StringBuilder randomCode = new StringBuilder();

        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length);
            code.append(CHARACTERS[index]);
        }
        for (int i = 0; i < RANDOM_CODE_LENGTH; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length);
            randomCode.append(CHARACTERS[index]);
        }

        //邀请码+随机码组成一个字符
        String tempCode = code.toString() + randomCode.toString();
        byte[] digest = DigestUtil.md5(tempCode);
        String sMD5EncryptResult = DatatypeConverter.printHexBinary(digest).toUpperCase();
        String[] resUrl = new String[4];
        //得到 4组短链接字符串
        for (int i = 0; i < 4; i++) {
            // 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
            String sTempSubString = sMD5EncryptResult.substring(i * 8, i * 8 + 8);
            // 这里需要使用 long 型来转换，因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 , 如果不用 long ，则会越界
            long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
            String outChars = "";
            //循环获得每组6位的字符串
            for (int j = 0; j < 6; j++) {
                // 把得到的值与 0x0000003D 进行位与运算，取得字符数组 chars 索引(具体需要看chars数组的长度   以防下标溢出，注意起点为0)
                long index = 0x0000003D & lHexLong;
                // 把取得的字符相加
                outChars += CHARACTERS[(int) index];
                // 每次循环按位右移 5 位
                lHexLong = lHexLong >> 5;
            }
            // 把字符串存入对应索引的输出数组
            resUrl[i] = outChars;
        }

        return resUrl[0];
    }

    public static void main(String[] args) {
        // 生成5个邀请码示例
        for (int i = 0; i < 5; i++) {
            System.out.println("邀请码 " + (i + 1) + ": " + generateInviteCode());
        }
    }
}
