package com.bcxin.message.common.utils;

import cn.hutool.core.codec.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Stack;

public class Base64Util {

    private static final String CHAR_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";

    /**
     * description：字符串Base64
     * author：linchunpeng
     * date：2025/7/9
     */
    public static String stringToBase64(String str) {
        return Base64.encode(str);
    }

    /**
     * description：文件转Base64
     * author：linchunpeng
     * date：2024/3/14
     */
    public static String fileToBase64(File file, boolean isConfuse) {
        if (isConfuse) {
            //需要混淆
            String base64 = RandomStringUtils.random(1, CHAR_STRING) + Base64.encode(file) + RandomStringUtils.random(1, CHAR_STRING);
            return reverse(base64);
        } else {
            return Base64.encode(file);
        }
    }

    /**
     * description：Base64转文件
     * author：linchunpeng
     * date：2024/3/14
     */
    public static File base64ToFile(String base64, String filePath, boolean isConfuse) {
        String content = base64;
        if (isConfuse) {
            //是混淆，解除
            content = reverse(base64);
            content = content.substring(1, content.length() - 1);
        }
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        byte[] buffer;
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            buffer = base64Decoder.decodeBuffer(content);
            FileOutputStream out = new FileOutputStream(filePath);
            out.write(buffer);
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return file;
    }

    private static String reverse(String content) {
        int stackSize = content.length();
        Stack<Character> theStack = new Stack<>();
        for (int i = 0; i < stackSize; i++) {
            theStack.push(content.charAt(i));
        }
        StringBuffer result = new StringBuffer();
        while (!theStack.isEmpty()) {
            char ch = theStack.pop();
            result.append(ch);
        }
        return result.toString();
    }

}
