package com.hfkj.common;

import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.IDGenerator;

import java.util.Base64;
import java.util.Date;
import java.util.Random;

public class Base64Util {
	   /**
     * @param data
     * @return str
     * @throws Exception
     */
    public static String encode(String data) throws Exception{
//        String encodeBase64 = new BASE64Encoder().encode(data.getBytes("utf-8"));
        String encodeBase64 = Base64.getEncoder().encodeToString(data.getBytes("utf-8"));
        String safeBase64Str = encodeBase64.replace('+', '-');
        safeBase64Str = safeBase64Str.replace('/', '_');
        safeBase64Str = safeBase64Str.replaceAll("=", "");
        return safeBase64Str.replaceAll("\\s*", "");
    }

    public static String generateOrderNo(){
        try {
            // 5位随机数 + 1位线程生成数
            String randomNum = (new Random().nextInt(8999) + 1000) + IDGenerator.nextId(1);
            // 生成订单号
            return DateUtil.date2String(new Date(),"yyyyMMddHHmmss") + randomNum;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param safeBase64Str
     * @return str
     * @throws Exception
     */
    public static String decode(final String safeBase64Str) throws Exception{
        String base64Str = safeBase64Str.replace('-', '+');
        base64Str = base64Str.replace('_', '/');
        int mod4 = base64Str.length() % 4;
        if(mod4 > 0){
            base64Str += "====".substring(mod4);
        }

//        byte[] ret = new BASE64Decoder().decodeBuffer(base64Str);
        byte[] ret = Base64.getDecoder().decode(base64Str);
        return new String(ret, "utf-8");
    }

    public static void main(String[] args) throws Exception {
		System.out.println(encode("abcd1234"));
		System.out.println(decode("YWJjZDEyMzQ"));
	}
}
