package com.ywt.alipaympapi.core.utils;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Jiangxiong.
 */
public class StringHelper {
    public static final String scriptReg = "<script[\\s\\S]+?</script>";
    public static final String iframeReg = "<iframe[\\s\\S]+?</iframe>";

    public static String clearHtmlTag(String content) {
        if (!isNullOrEmpty(content)) {
            content = clearSpecialContent(content, scriptReg);
            content = clearSpecialContent(content, iframeReg);
            content = clearSpecialContent(content, "(<[^>\\s]*\\b(\\w)+\\b[^>]*>)|([\\s]+)|(<>)|(&nbsp;)");
            content = content.replace("\"", "").replace("<", "").replace(">", "");
        }
        return content;
    }

    public static String clearImageAndScript(String content) {
        String regexExpression = "<script[\\s\\S]+</script *>|<s*img[^>]*>";
        return clearSpecialContent(content, regexExpression);
    }

    public static String clearSpecialContent(String content, String regexExpression) {
        if (isNullOrEmpty(content)) {
            return "";
        }
        Pattern pattern = Pattern.compile(regexExpression, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(content);
        content = matcher.replaceAll("");
        return content;
    }

    public static String replaceSpecialContent(String sourceStr, String targetStr, String regexExp, int flags) {
        Pattern pattern = Pattern.compile(regexExp, flags);
        Matcher matcher = pattern.matcher(sourceStr);
        sourceStr = matcher.replaceAll(targetStr);
        return sourceStr;
    }

    public static String substringContent(String sourceStr, String regexExp, int flags) {
        Pattern pattern = Pattern.compile(regexExp, flags);
        Matcher matcher = pattern.matcher(sourceStr);
        return matcher.find() ? matcher.group() : "";
    }

    public static boolean isNullOrEmpty(String value) {
        return value == null || "".equals(value);
    }


    /**
     * 判断传入的value是null还是空白的字符串
     *
     * @param value
     * @return
     */
    public static boolean isNullOrWhiteSpace(String value) {
        return value == null || "".equals(value) || "".equals(value.trim());
    }

    /**
     * 转半角的函数
     *
     * @param value 任意字符串
     * @return 半角字符串
     */
    public static String toDBC(String value) {
        char[] c = value.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * 获取没有连字号的UUID
     *
     * @return
     */
    public static String getUUIDWithoutHyphen() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String formatMobile(String mobile) {
        if (mobile == null || mobile.length() != 11) {
            return mobile;
        }

        return mobile.substring(0, 3) + " **** " + mobile.substring(7);
    }

    public static boolean isUrl(String str) {
        if (isNullOrWhiteSpace(str)) {
            return false;
        }

        Pattern pattern = Pattern
                .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\\\/])+$");
        return pattern.matcher(str).matches();
    }

    /**
     * 独占模式匹配 url, 避免引起回溯
     *
     */
    public static boolean isUrlPossessive(String str) {
        if (isNullOrWhiteSpace(str)) {
            return false;
        }

        Pattern pattern = Pattern
                .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)++([A-Za-z0-9-~\\\\/])+$");
        return pattern.matcher(str).matches();
    }

    /**
     * 生成32位md5码
     *
     * @param text
     * @return
     */
    public static String md5(String text) {
        StringBuilder builder = new StringBuilder();

        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(text.getBytes());

            for (byte b : result) {
                int number = b & 0xff;
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    builder.append("0");
                }
                builder.append(str);
            }

        } catch (NoSuchAlgorithmException e) {

        }

        return builder.toString();
    }

    /**
     * 文件大小表示
     *
     * @param bytes
     * @return
     */
    public static String getStrSize(long bytes) {
        BigDecimal size = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = size.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
        if (returnValue > 1) {
            return (returnValue + "MB");
        }
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = size.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();
        return (returnValue + "KB");
    }

    /**
     * 过滤emoji表情
     *
     * @param source
     * @return 过滤后的字符串
     */
    public static String filterEmoji(String source) {
        if (isNullOrWhiteSpace(source)) {
            return source;
        }
        return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "");
    }

    public static boolean isEmail(String email) {
        if (isNullOrWhiteSpace(email)) {
            return false;
        }
        String regEx = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 邮箱校验，规则：
     * 1. 以大写字母[A-Z]、小写字母[a-z]、数字[0-9]、下滑线[_]、减号[-]及点号[.]开头，并需要重复一次至多次[+]。
     * 2. 中间必须包括@符号。
     * 3. @之后需要连接大写字母[A-Z]、小写字母[a-z]、数字[0-9]、下滑线[_]、减号[-]及点号[.]，并需要重复一次至多次[+]。
     * 4. 结尾必须是点号[.]连接2至4位的大小写字母[A-Za-z]{2,4}。
     *
     * @param email 待校验字符串
     * @return 是否是合法的邮箱地址
     */
    public static boolean isEmailNew(String email) {
        if (isNullOrWhiteSpace(email)) {
            return false;
        }
        String regEx = "^([A-Za-z0-9_\\-.])+@([A-Za-z0-9_\\-.])+\\.([A-Za-z]{2,4})$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(email);
        return m.matches();
    }
    /**
     * 返回一个新字符串，它相当于从当前 String 对象中移除了指定字符的所有前导匹配项和尾随匹配项。
     *
     * @param str      字符串
     * @param trimChar 要删除的 Unicode 字符
     * @return 从当前字符串的开头移除 trimChar 字符， 如果从当前实例无法删除字符，此方法返回未更改的当前实例。。
     */
    public static String trim(String str, char trimChar) {
        char[] val = str.toCharArray();
        int len = val.length;
        int st = 0;

        while ((st < len) && (val[st] == trimChar)) {
            st++;
        }
        while ((st < len) && (val[len - 1] == trimChar)) {
            len--;
        }
        return ((st > 0) || (len < val.length)) ? str.substring(st, len) : str;
    }

}
