package com.sonic.frog.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class MaskUtils {
 
    /**
     * 隐藏手机号
     *
     * @param mobile
     * @return
     */
    public static String maskMobile(String mobile) {
        if (StringUtils.isEmpty(mobile) || (mobile.length() != 11)) {
            return mobile;
        }
        return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    /**
     * 隐藏手机号
     *
     * @param mobile
     * @return
     */
    public static String maskMobile2(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return mobile;
        }
        if (mobile.startsWith("+")) {
            mobile = mobile.substring(1);
        }
        if (mobile.length() == 7) {
            return mobile.replaceAll("(\\d{3})(\\d{4})", "***$2");
        }
        return mobile.replaceAll("(\\d{0,7})(\\d{4})(\\d{4})", "$1****$3");
    }

    /**
     * 隐藏邮箱信息
     *
     * @param email
     * @return
     */
    public static String maskEmail(String email) {
        if (StringUtils.isEmpty(email)) return "";

        String prefix = "";
        try {
            if (email.indexOf("@") > 5) {
                prefix = email.substring(0, 3);
            } else {
                prefix = email.substring(0, 1);
            }

            String middle = "";
            if (prefix.length() < email.indexOf("@")) {
                for (int i = prefix.length(); i < email.indexOf("@"); i++) {
                    middle += "*";
                }
            }

            String suffix = email.substring(email.indexOf("@"));
            return prefix + middle + suffix;
        } catch (Exception e) {
            log.error(
                    String.format("email encrypt fail, param:%s, errorMsg:%s", email, e.getMessage()), e
            );
            return "";
        }
    }

}
