package thyyxxk.webserver.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author dj
 */
@Slf4j
public class StringUtil {

    private static final Pattern CHINESE_CHARACTERS = Pattern.compile("[\u4E00-\u9FA5|\\！|\\，|\\。|\\（|\\）|\\《|\\》|\\“|\\”|\\？|\\：|\\；|\\【|\\】]");

    private static final Pattern CARRY_ENGLISH = Pattern.compile(".*\\d+.*");

    public static boolean isBlank(String str) {
        return null == str || str.trim().isEmpty();
    }

    public static <T> T nullIf(T t1, T t2) {
        if (t1 instanceof String) {
            return isBlank((String) t1) ? t2 : t1;
        }
        return null == t1 ? t2 : t1;
    }

    public static boolean notBlank(String str) {
        return null != str && !"".equals(str.trim());
    }

    public static boolean validValue(String str) {
        return notBlank(str) && !"-".equals(str.trim());
    }

    public static boolean equalsIgnoreNull(String a, String b) {
        if (null == a) {
            a = "";
        }
        if (null == b) {
            b = "";
        }
        return a.equals(b);
    }

    public static boolean invalidValue(String str) {
        return isBlank(str) || "-".equals(str.trim());
    }

    public static boolean invalidBirthPlace(String str) {
        return isBlank(str) || str.trim().length() < 6;
    }

    public static String[] triageDeptString2Array(String deptCodes) {
        return null == deptCodes ? new String[]{} : deptCodes.substring(1, deptCodes.length() - 1).replaceAll("\"", "").split(",");
    }

    public static String desensitizeName(String name) {
        if (isBlank(name) || name.length() == 1) {
            return name;
        }
        if (!name.contains(" ")) {
            return executeDesensitize(name);
        }
        String[] arr = name.split(" ");
        StringBuilder result = new StringBuilder();
        for (String part : arr) {
            result.append(" ").append(executeDesensitize(part));
        }
        return result.substring(1);
    }

    private static String executeDesensitize(String str) {
        if (str.length() == 2) {
            return str.charAt(0) + "*";
        }
        StringBuilder builder = new StringBuilder();
        builder.append(str.charAt(0));
        for (int i = 1; i < str.length() - 1; i++) {
            if (str.charAt(i) == ' ') {
                builder.append(" ");
            } else {
                builder.append("*");
            }
        }
        builder.append(str.charAt(str.length() - 1));
        return builder.toString();
    }

    /**
     * 把原始字符串分割成指定长度的字符串列表
     *
     * @param inputString 原始字符串
     * @param length      指定长度
     * @return 。。
     */
    public static List<String> getStringList(String inputString, int length) {
        int size = inputString.length() / length;
        if (inputString.length() % length != 0) {
            size += 1;
        }
        return getStrList(inputString, length, size);
    }

    /**
     * 把原始字符串分割成指定长度的字符串列表
     *
     * @param inputString 原始字符串
     * @param length      指定长度
     * @param size        指定列表大小
     * @return ..
     */
    public static List<String> getStrList(String inputString, int length, int size) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            String childStr = substring(inputString, i * length, (i + 1) * length);
            list.add(childStr);
        }
        return list;
    }

    /**
     * @param str 需要判断的字符串
     * @return 返回 到底要不要 toUpperCase
     */
    public static String isContainChinese(String str) {
        if (isBlank(str)) {
            return "%";
        }
        str = str.trim();
        if (isChinese(str)) {
            return "%" + str + "%";
        }

        Matcher m1 = CARRY_ENGLISH.matcher(str);
        if (m1.matches()) {
            return "%" + str + "%";
        }
        return "%" + str.toUpperCase() + "%";
    }

    /**
     * 判断是否是中文
     *
     * @param str 字符串
     * @return 提示
     */
    public static boolean isChinese(String str) {
        if (isBlank(str)) {
            return false;
        }
        str = str.trim();
        Matcher m = CHINESE_CHARACTERS.matcher(str);

        return m.find();
    }

    public static String englishToCapital(String str) {
        if (isBlank(str)) {
            return "";
        }
        Matcher m = CHINESE_CHARACTERS.matcher(str);
        if (m.find()) {
            return str;
        }
        return str.toUpperCase();
    }

    /**
     * 驼峰转下划线
     *
     * @param str 数据
     * @return 返回数据
     */
    public static String humpToUnderline(String str) {
        String regex = "([A-Z])";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String target = matcher.group();
            str = str.replaceAll(target, "_" + target.toLowerCase());
        }
        return str;
    }

    private static final Pattern linePattern = Pattern.compile("_(\\w)");


    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


    /**
     * 分割字符串，如果开始位置大于字符串长度，返回空
     *
     * @param str 原始字符串
     * @param f   开始位置
     * @param t   结束位置
     * @return 。。
     */
    public static String substring(String str, int f, int t) {
        if (f > str.length()) {
            return null;
        }
        if (t > str.length()) {
            return str;
        } else {
            return str.substring(f, t);
        }
    }

    /**
     * 字符串相似度算法
     */
    public static double getSimilarDegree(String source, String target) {
        Map<Character, int[]> vector = new HashMap<>();
        int[] charCountArray;
        for (char sourceChar : source.toCharArray()) {
            if (vector.containsKey(sourceChar)) {
                vector.get(sourceChar)[0]++;
            } else {
                charCountArray = new int[2];
                charCountArray[0] = 1;
                vector.put(sourceChar, charCountArray);
            }
        }
        for (char targetChar : target.toCharArray()) {
            if (vector.containsKey(targetChar)) {
                vector.get(targetChar)[1]++;
            } else {
                charCountArray = new int[2];
                charCountArray[1] = 1;
                vector.put(targetChar, charCountArray);
            }
        }
        double v1Modulo = 0d;
        double v2Modulo = 0d;
        double vProduct = 0d;
        for (Map.Entry<Character, int[]> entry : vector.entrySet()) {
            int[] tempArray = entry.getValue();
            v1Modulo += tempArray[0] * tempArray[0];
            v2Modulo += tempArray[1] * tempArray[1];
            vProduct += tempArray[0] * tempArray[1];
        }
        v1Modulo = Math.sqrt(v1Modulo);
        v2Modulo = Math.sqrt(v2Modulo);
        return vProduct / (v1Modulo * v2Modulo);
    }

    public static String stringArrayToCharacter(String[] lytype) {
        if (lytype == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        if (lytype.length > 0) {
            for (int i = 0; i < lytype.length; i++) {
                if (i < lytype.length - 1) {
                    sb.append(lytype[i]).append(",");
                } else {
                    sb.append(lytype[i]);
                }
            }
        }
        return sb.toString();
    }


    public static String replaceElementValue(String str, Map<String, String> map) {
        if (!StringUtils.hasText(str)) {
            return str;
        }
        //定义${开头 ，}结尾的占位符
        PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");
        //调用替换
        return propertyPlaceholderHelper.replacePlaceholders(str, map::get);
    }

    /**
     * 首字母大写(进行字母的ascii编码前移，效率是最高的)
     *
     * @param fieldName 需要转化的字符串
     */
    public static String capitalizeTheFirstLetter(String fieldName) {
        char[] chars = fieldName.toCharArray();
        chars[0] = toUpperCase(chars[0]);
        return String.valueOf(chars);
    }

    public static String getMethodName(String fieldName) {
        return "get" + capitalizeTheFirstLetter(fieldName);
    }

    public static String setMethodName(String fieldName) {
        return "set" + capitalizeTheFirstLetter(fieldName);
    }

    /**
     * 字符转成大写
     *
     * @param c 需要转化的字符
     */
    public static char toUpperCase(char c) {
        if (97 <= c && c <= 122) {
            c ^= 32;
        }
        return c;
    }

    public static boolean isEmpty(String[] string) {
        return string == null || string.length == 0;
    }

    public static boolean isEmpty(String string) {
        return string == null || string.trim().isEmpty() || "null".equals(string.trim());
    }

    public static boolean isNotEmpty(String string) {
        return !isEmpty(string);
    }

    public static boolean isEmpty(Object o) {
        return o == null || "".equals(o);
    }

    public static String trim(String str) {
        return str == null ? null : str.trim();
    }
}

