package com.fdkankan.sign;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Converter {

    public final static Base64.Encoder encoder = Base64.getEncoder();
    final static Base64.Decoder decoder = Base64.getDecoder();
    static char[] arr = {'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', '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'};

    /**
     * 给字符串加密
     * @param text
     * @return
     */
    public static String encode(String text) {
        byte[] textByte = new byte[0];
        try {
            textByte = text.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String encodedText = encoder.encodeToString(textByte);
        return encodedText;
    }

    /**
     * 给字符串加密
     * @param textByte
     * @return
     */
    public static String encode(byte[] textByte) {
        return encoder.encodeToString(textByte);
    }

    /**
     * 将加密后的字符串进行解密
     * @param encodedText
     * @return
     */
    public static String decode(String encodedText) {
        String text = null;
        try {
            text = new String(decoder.decode(encodedText), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return text;
    }

    /**
     * 根据逻辑截取加密后的密碼
     * @param text
     * @return
     */
    public static String subText(String text){
        //去掉前8位字符串
        text = text.substring(8);
        //去掉后8位字符串
        text = text.substring(0, text.length() - 8);
        //最后两个字符串换到前面，并且去掉剩下的后8位字符串
        String result = text.substring(text.length() - 2) + text.substring(0, text.length() - 10);
        return result;
    }


    public static  String getEncode(String str){
        int num = 2;
        String front = randomWord(8);
        String middle = randomWord(8);
        String end = randomWord(8);

        String str1 = str.substring(0, num);
        String str2 = str.substring(num);

        return front + str2 + middle + str1 + end ;
    }

    public static String randomWord ( Integer min) {
        String str = "";
        Integer range = min;
        // 随机产生
        for (int i = 0; i < range; i++) {
            int pos = (int) Math.round(Math.random() * (arr.length - 1));
            str += arr[pos];
        }
        return str;
    }
}
