package cn.com.ctop.common.module.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class Base64Utils {
    private static Pattern reunicodePattern = Pattern.compile("[0-9]+");

    private Base64Utils() {

    }

    public static String decode1(String s) {
        Matcher m = reunicodePattern.matcher(s);
        StringBuffer sb = new StringBuffer(s.length());
        while (m.find()) {
            m.appendReplacement(sb, Character.toString((char) Integer.parseInt(m.group(1), 16)));
        }
        m.appendTail(sb);
        return sb.toString();
    }

    /**
     * 解码
     *
     * @param text
     * @return
     */
    public static String decode(String text) {
        if (text == null) {
            return null;
        }
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            return new String(decoder.decode(text), StandardCharsets.UTF_8);
        } catch (Exception e) {
            return null;
        }
    }

    public static String imageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        // 对字节数组Base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encodeToString(data);
    }
}
