package com.yida.data.device.telephone.util;

import java.nio.charset.StandardCharsets;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;

/**
 * 金额工具类
 */
public class BalanceUtil {
    // 随机串长度
    private static final Integer SUFFIX_LEN = 4;

    /**
     * 金额加密
     *
     * @param balance
     * @return
     */
    public static String encode(Double balance) {
        String target = balance + RandomUtil.randomString(SUFFIX_LEN);
        return Base64.encode(target.getBytes(StandardCharsets.UTF_8));
    }


    /**
     * 金额解密
     *
     * @param str
     * @return
     */
    public static Double decode(String str) {
        byte[] decode = Base64.decode(str);
        String decodeStr = new String(decode);
        String targetStr = decodeStr.substring(0, decodeStr.length() - SUFFIX_LEN);
        Double target = 0D;
        try {
            target = Double.valueOf(targetStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return target;
    }

}
