package com.younike.common.utils.integral;


import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * 字符串工具类
 *
 * @author jude
 * @date 2018-12-05
 */
public class MyStringUtil {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    private static final String FIELD_SIGN = "sign";

    /**
     * 判断是否是空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str.trim())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否不是空
     *
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        if ((str != null) && !"".equals(str.trim())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 生成模糊查询条件
     *
     * @return
     */
    public static String makeLike(String value) {
        return "%" + value.trim() + "%";
    }

    /**
     * 生成四位编号
     *
     * @param code
     * @return
     */
    public static String formatCode(String code) {
        try {
            int length = code.length();
            Integer num = Integer.valueOf(code.substring(length - 4, length)) + 1;
            String codenum = num.toString();
            int codelength = codenum.length();
            for (int i = 4; i > codelength; i--) {
                codenum = "0" + codenum;
            }
            return codenum;
        } catch (NumberFormatException e) {
            return "0100";
        }
    }

    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串16位
     */
    public static String generateNonceStr16() {
        char[] nonceChars = new char[16];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * map按字母排序拼接参数
     *
     * @return String 随机字符串
     */
    public static StringBuilder mapSort(final Map<String, String> data) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.deleteCharAt(sb.length()-1);
        return  sb;
    }
}
