package com.dsk.common.utils;

import java.util.HashMap;

public class EncodeIdUtil {


    private static String table = "VyB2Kz79QWYjpiD5lRCIMwJEhqFSx0GN1cveZfU4gs6rk8dPbLtAomOnT3";
    private static HashMap<String, Integer> mp = new HashMap<>();
    private static HashMap<Integer, String> mp2 = new HashMap<>();
    static int[] ss = {2, 7, 5, 1, 4, 8, 3, 0, 6};
    static long xor = 177451812;
    static long add = 8728348608L;

    /**
     * 解码
     * @param s 编码的随机字符串
     * @return 原自增ID
     */
    public static String avDecode(String s) {
        long r = 0;
        for (int i = 0; i < table.length(); i++) {
            String s1 = table.substring(i, i + 1);
            mp.put(s1, i);
        }
        for (int i = 0; i < 9; i++) {
            r = r + mp.get(s.substring(ss[i], ss[i] + 1)) * power(58, i);
        }
        return  String.valueOf((r - add) ^ xor);
    }

    /**
     * 编码
     * @param st 原自增ID
     * @return 编码后的随机字符串
     */
    public static String bvEncode(String st) {
        StringBuilder sb = new StringBuilder("         ");
        long s = Long.parseLong(st);
        s = (s ^ xor) + add;
        for (int i = 0; i < table.length(); i++) {
            String s1 = table.substring(i, i + 1);
            mp2.put(i, s1);
        }
//        mp2.forEach((inx, str) -> System.out.print(str));
        for (int i = 0; i < 9; i++) {
            String r = mp2.get((int) (s / power(table.length(), i) % table.length()));
            sb.replace(ss[i], ss[i] + 1, r);
        }
        return sb.toString();
    }

    private static long power(int a, int b) {
        long power = 1;
        for (int c = 0; c < b; c++)
            power *= a;
        return power;
    }

    /**
     * 把unicode编码转换成正常字符
     *
     * @param hex
     * @return
     */
    public static String binaryToUnicode(String hex) {
        int i;
        int n;
        int j;
        n = hex.length() / 2;
        j = 0;
        char[] content = new char[n];
        for (i = 0; i < n; i++) {
            j = i * 2;
            content[i] = (char) Integer.parseInt(hex.substring(j, j + 2), 16);
        }
        return new String(content);
    }

    /**
     * 把字符转换成unicode编码
     *
     * @param content
     * @return
     */
    public static String unicodeToBinary(String content) {
        String hexStr = "";
        char[] contentBuffer = content.toCharArray();
        String s;
        int n;
        for (int i = 0; i < content.length(); i++) {
            n = (int) contentBuffer[i];
            s = Integer.toHexString(n);
//			if (s.length() > 4) {
//				s = s.substring(0, 4);
//			} else {
//				s = "0000".substring(0, 4 - s.length()) + s;
//			}
            hexStr = hexStr + s;
        }
        return hexStr;
    }
}
