package cn.iocoder.yudao.module.system.util;

import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class StringUtil {
    /**
     * 登录密码
     */
    public static final String DEFAULT_PASSWORD = "yinianims123!@#";

    /**
     * 获取传入的长度随机字符串
     *
     * @param length
     * @return
     */
    public static String getRandomStringByLength(int length) {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 排序方法
     *
     * @param m
     * @return
     */
    public static String[] sortStringArray(Map<String, Object> m) {


        ArrayList<String> arrayList = new ArrayList<String>();

        for (Map.Entry<String, Object> entry : m.entrySet()) {

            if (!StringUtils.isEmpty(entry.getValue())) {
                String content = entry.getKey() + "=" + entry.getValue();

                arrayList.add(content);
            }

        }

        String[] arrayToSort = new String[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            arrayToSort[i] = arrayList.get(i);
        }
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        return arrayToSort;
    }

    /**
     * 排序方法
     *
     * @param m
     * @return
     */
    public static String[] sortMapArray(Map<String, String> m) {


        ArrayList<String> arrayList = new ArrayList<String>();

        for (Map.Entry<String, String> entry : m.entrySet()) {

            if (!StringUtils.isEmpty(entry.getValue())) {
                String content = entry.getKey() + "=" + entry.getValue();

                arrayList.add(content);
            }

        }

        String[] arrayToSort = new String[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            arrayToSort[i] = arrayList.get(i);
        }
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        return arrayToSort;
    }

    /**
     * @param plainText 明文
     * @return 32位密文
     */
    public static String encryption(String plainText) {
        String re_md5 = new String();
        try {


            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] result = messageDigest.digest(plainText.getBytes(Charset.forName("UTF-8"))); // 得到加密后的字符组数

            StringBuffer sb = new StringBuffer();

            for (byte b : result) {
                int num = b & 0xff; // 这里的是为了将原本是byte型的数向上提升为int型，从而使得原本的负数转为了正数
                String hex = Integer.toHexString(num); //这里将int型的数直接转换成16进制表示
                //16进制可能是为1的长度，这种情况下，需要在前面补0，
                if (hex.length() == 1) {
                    sb.append(0);
                }
                sb.append(hex);
            }

            return sb.toString();


        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }

    public static String formatTime(Date date, String formatter) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        return sdf.format(date);
    }

    public static String formatTime(Timestamp date, String formatter) {
        if (date == null)
            return "";
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        Date date_new = new Date(date.getTime());
        return sdf.format(date_new);
    }

    public static Date parseTime(String datestr, String formatter) throws Exception {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formatter);
            return sdf.parse(datestr);
        } catch (Exception ex) {
            Exception oe = new Exception("时间解析错误:" + ex.getMessage());
            throw oe;
        }
    }

    public static Timestamp parseStampTime(String datestr, String formatter) throws Exception {
        if (datestr == null) return null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formatter);
            return new Timestamp(sdf.parse(datestr).getTime());
        } catch (Exception ex) {
            Exception oe = new Exception("时间解析错误:" + ex.getMessage());
            throw oe;
        }
    }

    public static Timestamp parseStampTime1(String datestr) {
        if (StringUtils.isEmpty(datestr))
            return null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return new Timestamp(sdf.parse(datestr).getTime());
        } catch (Exception ex) {
            return null;
        }
    }

    public static Timestamp getCurrTimestamp() {
        return new Timestamp(new Date().getTime());
    }

    /**
     * 判断是否是手机号
     *
     * @param mobile
     * @return true-是，false-不是
     */
    public static boolean isMobileNO(String mobile) {
        if (mobile.length() != 11) {
            return false;
        } else {
            /**
             * 移动号段正则表达式  ^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\d{8}|(1705)\d{7}$
             */
            String pat1 = "^1[3456789]\\d{9}$";
            /**
             * 联通号段正则表达式
             */
            String pat2 = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
            /**
             * 电信号段正则表达式
             */
            String pat3 = "^((133)|(153)|(177)|(18[0,1,9])|(149))\\d{8}$";
            /**
             * 虚拟运营商正则表达式
             */
            String pat4 = "^((170))\\d{8}|(1718)|(1719)\\d{7}$";

            Pattern pattern1 = Pattern.compile(pat1);
            Matcher match1 = pattern1.matcher(mobile);
            boolean isMatch1 = match1.matches();
            if (isMatch1) {
                return true;
            }
            Pattern pattern2 = Pattern.compile(pat2);
            Matcher match2 = pattern2.matcher(mobile);
            boolean isMatch2 = match2.matches();
            if (isMatch2) {
                return true;
            }
            Pattern pattern3 = Pattern.compile(pat3);
            Matcher match3 = pattern3.matcher(mobile);
            boolean isMatch3 = match3.matches();
            if (isMatch3) {
                return true;
            }
            Pattern pattern4 = Pattern.compile(pat4);
            Matcher match4 = pattern4.matcher(mobile);
            boolean isMatch4 = match4.matches();
            if (isMatch4) {
                return true;
            }
            return false;
        }
    }

    /**
     * 是否包含字符，只允许数字和字母
     *
     * @param str
     * @return false-不包含，true-包含
     */
    public static boolean hasChar(String str) {
        String filter = stringFilter(str);
        return filter.length() != str.length();
    }

    public static String filterChar(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        String regEx = "[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
//        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        String regEx = "[^a-zA-Z0-9_]";
        // 清除掉所有特殊字符
//        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static boolean isNum(String str) {
        String reg = "^(\\d+[A-Za-z]+[A-Za-z0-9]*)|([A-Za-z]+\\d+[A-Za-z0-9]*)$";
        return !str.matches(reg);
    }

    /**
     * 判断str1中包含str2的个数
     *
     * @param str1
     * @param str2
     * @return counter
     */
    public static int countStr(String str1, String str2) {
        int counter = 0;
        if (str1.indexOf(str2) == -1) {
            return 0;
        } else if (str1.indexOf(str2) != -1) {
            counter++;
            countStr(str1.substring(str1.indexOf(str2) +
                    str2.length()), str2);
            return counter;
        }
        return 0;
    }

    /**
     * 使用正则表达式提取中括号中的内容
     *
     * @param msg
     * @return
     */
    public static List<String> extractMessageByRegular(String msg) {
        List<String> list = new ArrayList<String>();
//因为默认为贪婪模式,所以如果没有使用显示()组中的元素不能为大括号([^}]*),而是使用(.*),
//那么会匹配的字符串为:one}{two}{three
        Pattern p = Pattern.compile("\\{\\{([^}]*)\\}\\}");
        Matcher m = p.matcher(msg);
        while (m.find()) {
            list.add(m.group(1));
        }
        return list;
    }

    /**
     * * 判断一个对象数组是否为空
     *
     * @param objects 要判断的对象数组
     *                * @return true：为空 false：非空
     */
    public static boolean isEmpty(Object[] objects) {
        return isNull(objects) || (objects.length == 0);
    }

    /**
     * * 判断一个对象是否为空
     *
     * @param object Object
     * @return true：为空 false：非空
     */
    public static boolean isNull(Object object) {
        return object == null;
    }

    /**
     * * 判断一个对象数组是否非空
     *
     * @param objects 要判断的对象数组
     * @return true：非空 false：空
     */
    public static boolean isNotEmpty(Object[] objects) {
        return !isEmpty(objects);
    }


    public static void main(String[] args) {
        System.out.println(isMobileNO("11955650668"));
    }
}
