package com.wisedu.coeus.util;


import com.wisedu.coeus.core.ConstantStatic;
import org.apache.commons.lang.StringUtils;

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

/**
 * 字符串实用工具类
 */
public class Strings {
    public static final String EMPTY = "";

    /**
     * 判断一个字符串对象是否是""或null
     *
     * @param str 要判断的字符串对象
     * @return
     */
    public static boolean isEmpty(String str) {
        return StringUtils.isEmpty(str);
    }

    public static boolean isEmpty(Object obj) {
        boolean flag = false;
        if (obj == null) {
            flag = true;
        }
        return flag;
    }

    public static boolean isNotEmpty(Object obj) {
        boolean flag = false;
        if (obj != null) {
            flag = true;
        }
        return flag;
    }

    /**
     * 判断一个字符串对象是否不是""或null
     *
     * @param str 要判断的字符串对象
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return StringUtils.isNotEmpty(str);
    }

    public static boolean isBlank(String str) {
        return StringUtils.isBlank(str);
    }

    /**
     * 将一个字符串的前后空白去掉，如果为null转换成""
     *
     * @param str 要操作的字符串对象
     * @return
     */
    public static String trimToEmpty(String str) {
        return StringUtils.trimToEmpty(str);
    }

    /**
     * 将一个字符串的前后空白去掉，如果为""转换成null
     *
     * @param str
     * @return
     */
    public static String trimToNull(String str) {
        return StringUtils.trimToNull(str);
    }

    /**
     * 用指定的分割字符连接数组元素
     *
     * @param array     对象数组
     * @param separator 分割字符
     * @return
     */
    public static String join(Object[] array, String separator) {
        return StringUtils.join(array, separator);
    }

    /**
     * 用指定的分割字符连接数组元素
     *
     * @param collection 对象数组
     * @param separator  分割字符
     * @return
     */
    public static String join(Collection collection, String separator) {
        return StringUtils.join(collection, separator);
    }

    /**
     * 获取文件路径中文件主名，不含.和扩展名
     *
     * @param filePath 文件路径
     * @return
     */
    public static String getFileBaseName(String filePath) {
        filePath = filePath.replace('\\', '/');
        int pos = filePath.lastIndexOf('/');
        if (pos > 0) {
            filePath = filePath.substring(pos + 1, filePath.length());
        }
        pos = filePath.lastIndexOf('.');
        String baseName = filePath;

        if (pos > 0) {
            baseName = filePath.substring(0, pos);
        }
        return baseName;
    }

    /**
     * 获取文件路径中文件扩展名，不含.
     *
     * @param filePath 文件路径
     * @return
     */
    public static String getFileExtName(String filePath) {
        filePath = filePath.replace('\\', '/');
        int pos = filePath.lastIndexOf('/');
        if (pos > 0) {
            filePath = filePath.substring(pos + 1, filePath.length());
        }
        pos = filePath.lastIndexOf('.');
        String baseName = "";

        if (pos > 0) {
            baseName = filePath.substring(pos + 1, filePath.length());
        }
        return baseName;
    }

    public static String substringBeforeLast(String str, String separator) {
        return StringUtils.substringBeforeLast(str, separator);
    }


    /**
     * 字符串转成Long
     *
     * @param num ：要转化的数字字符串
     * @param def ：默认值
     * @return 返回 Long
     */
    public static Long getLong(String num, long def) {
        if (isEmpty(num)) {
            return def;
        }
        long ret = def;
        int i = num.indexOf(".");
        if (i == 0) {
            num = "0";
        } else if (i > 0) {
            num = num.substring(0, i);
        }
        try {
            ret = Long.parseLong(num);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    /**
     * 字符串转成Long
     *
     * @param num ：要转化的数字字符串
     * @return 返回 Long
     */
    public static Long getLong(String num) {
        return getLong(num, 0);
    }

    public static Long getLong(Object num) {
        return getLong(getString(num));
    }

    public static Long getLong(Object num, long def) {
        return getLong(getString(num), def);
    }

    /**
     * 字符串转成Integer
     *
     * @param num ：要转化的数字字符串
     * @param def ：默认值
     * @return 返回 Integer
     */
    public static Integer getInteger(String num, int def) {
        if (isEmpty(num)) {
            return def;
        }
        int ret = def;
        try {
            ret = Integer.valueOf(num);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        return ret;
    }
    
    public static Double getDouble(String num, double def) {
        if (isEmpty(num)) {
            return def;
        }
        double ret = def;
        try {
            ret = Double.valueOf(num);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    /**
     * 字符串转成Integer
     *
     * @param num ：要转化的数字字符串
     * @return 返回 Integer
     */
    public static Integer getInteger(String num) {
        if (isEmpty(num)) {
            return null;
        }
        int ret = 0;
        int i = num.indexOf(".");
        if (i == 0) {
            num = "0";
        } else if (i > 1) {
            num = num.substring(0, i);
        }
        try {
            ret = Integer.valueOf(num);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    public static Integer getInteger(Object num) {
        return getInteger(getString(num));
    }

    public static Integer getInteger(Object num, int def) {
        return getInteger(getString(num), def);
    }
    
    public static Double getDouble(Object num, double def) {
        return getDouble(getString(num), def);
    }

    public static String getStringNoBlank(String email){
        if(email!=null && !"".equals(email)) {
            Pattern p = Pattern.compile(ConstantStatic.SPECIAL_BLANK);
            Matcher m = p.matcher(email);
            return m.replaceAll("");
        }else {
            return email;
        }
    }

    /**
     * 替换字符
     *
     * @param str
     * @param searchChar
     * @param replaceChar
     * @return
     */
    public static String replaceChars(String str, char searchChar, char replaceChar) {
        return StringUtils.replaceChars(str, searchChar, replaceChar);
    }

    /**
     * 替换字符串
     *
     * @param str
     * @param searchString
     * @param replaceString
     * @return
     */
    public static String replace(String str, String searchString, String replaceString) {
        return StringUtils.replace(str, searchString, replaceString);
    }

    /**
     * 获取随机数
     *
     * @param length ：
     * @return ：
     */
    public static String getRandomString(int length) {
        StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int range = buffer.length();
        for (int i = 0; i < length; i++) {
            sb.append(buffer.charAt(r.nextInt(range)));
        }
        return sb.toString();
    }

    public static String getRandomLetter(int length) {
        StringBuffer buffer = new StringBuffer("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int range = buffer.length();
        for (int i = 0; i < length; i++) {
            sb.append(buffer.charAt(r.nextInt(range)));
        }
        return sb.toString();
    }
    
    public static String getRandomDigital(int length) {
        StringBuffer buffer = new StringBuffer("0123456789");
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int range = buffer.length();
        for (int i = 0; i < length; i++) {
            sb.append(buffer.charAt(r.nextInt(range)));
        }
        return sb.toString();
    }


    /**
     * if the input string is empty, then return the default string
     *
     * @param obj
     * @param def
     * @return string
     */
    public static String getString(Object obj, String def) {
        if (obj == null) {
            return def;
        }
        String result = obj.toString();
        return result.length() == 0 ? def : result;
    }

    public static String getString(Object obj) {
        return getString(obj, "");
    }

    public static String replaceFileSep(String sep) {
        if (File.separator.equals("\\")) {
            return Strings.replace(sep, "/", "\\");
        } else {
            return Strings.replace(sep, "\\", "/");
        }
    }

    public static String replaceUrlSep(String url) {
        return Strings.replace(url, "\\", "/");
    }

    public static String escapeHtml(String text) {
        String temp = Strings.replace(text, "&", "&amp;");

        temp = Strings.replace(temp, " ", "&nbsp;");
        temp = Strings.replace(temp, ">", "&gt;");
        temp = Strings.replace(temp, "<", "&lt;");
        temp = Strings.replace(temp, "\"", "&quot;");
        temp = Strings.replace(temp, "\n", "<br>");
        temp = Strings.replace(temp, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");

        return temp;
    }

    public static String decodeHtml(String text) {
        String temp = Strings.replace(text, "&amp;", "&");

        temp = Strings.replace(temp, "&nbsp;", " ");
        temp = Strings.replace(temp, "&gt;", ">");
        temp = Strings.replace(temp, "&lt;", "<");
        temp = Strings.replace(temp, "&quot;", "\"");
        temp = Strings.replace(temp, "<br>", "\n");
        temp = Strings.replace(temp, "&nbsp;&nbsp;&nbsp;&nbsp;", "\t");

        return temp;
    }

    public static String stripUnsafeTag(String text) {
        String temp = text.replaceAll("<script[^>]*>([^<]*)</script>", "");


        return temp;
    }

    public static boolean checkYearMonth(String validYear) {
        Pattern p = Pattern.compile("^\\d{4}((0\\d)|(1[0-2])|([0-9]))$");
        Matcher m = p.matcher(validYear);
        return m.matches();
    }

    public static String formatMillsToString(Long mills) {
        if (Strings.isEmpty(mills)) {
            return "00:00:00";
        }
        long ss = (mills / 1000) % 60;
        long mm = (mills / 60000) % 60;
        long hh = mills / 3600000;
        return getFormatString(hh) + ":" + getFormatString(mm) + ":" + getFormatString(ss);
    }

    public static String formatMillsToString2(Long mills) {
        if (Strings.isEmpty(mills)) {
            return "00:00";
        }
        long ss = (mills / 1000) % 60;
        long mm = mills / 60000;
        return getFormatString(mm) + ":" + getFormatString(ss);
    }

    public static String getFormatString(long time) {
        if (time < 10l) {
            return "0" + time;
        }
        return time + "";
    }

    public static String clearEmptyLine(String in) {
        Pattern pattern = Pattern.compile("\n");
        Matcher matcher = pattern.matcher(in);
        if (matcher.matches()) {
            return matcher.replaceAll("\n");
        }
        return in;
    }

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        return uuid;
    }

    public static String getYearAndMonth() {
        String shortYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR) - 2000);
        //月
        String month = String.valueOf(Calendar.getInstance().get(Calendar.MONTH) + 1);
        month = month.length() == 1 ? "0" + month : month;
        //日

        return shortYear + month;
    }



    public static String integerToString(Integer obj) {
        if (obj == null) {
            return null;
        }
        if (obj < 10) {
            return "0" + obj;
        }
        return obj + "";
    }

    /* 位数不足，前面补0
     * @param code
	 * @param len
	 * @return
	 */
    public static String codeAddOne(String code, int len) {
        Integer intOrder = Integer.parseInt(code);
        String strNo = intOrder.toString();
        while (strNo.length() < len) {
            strNo = "0" + strNo;
        }
        return strNo;
    }

    /**
     * 16进制转十进制
     *
     * @param hex ：
     * @return ：
     */
    public static Integer hexToDec(String hex) {
        for (int i = 0; i < hex.length(); i++) {
            if (!((hex.charAt(i) >= 48 && hex.charAt(i) <= 57) || (hex.charAt(i) >= 'a' && hex.charAt(i) <= 'f') || (hex.charAt(i) >= 'A' && hex.charAt(i) <= 'F'))) {
                return 0;
            }
        }
        return Integer.valueOf(hex, 16);
    }

    /**
     * 十进制转16进制
     *
     * @param num ：
     * @return ：
     */
    public static String decToHex(Integer num) {
        if (num == null) {
            return "0";
        }
        return Integer.toHexString(num);
    }

    
    public static boolean checkUserName(String userName) {
    	if (Strings.isEmpty(userName)) {
            return false;
        }
        Pattern enNamePattern = Pattern.compile("^[A-Za-z\\.\\- ]+$");
        Pattern chNamePattern = Pattern.compile("^[\\u3400-\\u4db5\\u4e00-\\u9fbb\\ue815-\\ue864\\uf92c-\\ufa29\\u00b7\\u2022\\.]+$");

        Matcher matcher;

        matcher = chNamePattern.matcher(userName);
        if (matcher.matches()) {
            return true;
        }

        matcher = enNamePattern.matcher(userName);
        if (matcher.matches()) {
            return true;
        }

        return false;
    }
    
    /**
     * 对模糊的中文名称进行，如果是模糊中文名进行清除
     * @param userName
     * @return
     */
    public static boolean getFuzzyChineseName(String userName,StringBuilder newName) {
        Pattern chNamePattern = Pattern.compile("^[\\u3400-\\u4db5\\u4e00-\\u9fbb\\ue815-\\ue864\\uf92c-\\ufa29\\u00b7\\u2022\\. \u3000]+$");
        Matcher matcher;
        String newUserName = userName;
        matcher = chNamePattern.matcher(userName);
        if (matcher.matches()) {
        	newUserName = Strings.replace(newUserName, " ", "");
        	newUserName = Strings.replace(newUserName, "\u3000", "");
        	if (Strings.isNotEmpty(newName)){
        		newName.setLength(0);
        		newName.append(newUserName);
        	}
        	return true;
        }
        return false;
    }

    /**
     * 判断字符是否为
     * @param text
     * @return
     */

    public static boolean isEmptyOrNullString(String text) {
        if (isEmpty(text)) return true;

        if ("null".equals(text) || "(null)".equals(text)) return true;

        return false;
    }
    public static String[] convert2Array(String text,String split) {
    	if(Strings.isEmpty(text)){
    		return null;
    	}
    	String[] strArray = null;
    	if(text.indexOf(split)>-1){
    		strArray = text.split(split);
    	}else{
    		strArray = new String[]{text};
    	}
    	return strArray;
    	
    }
    public static String[] convert2Array(String text) {
    	return convert2Array(text,",");
    }
    public static Integer[] convert2IntegerArray(String text,String split) throws NumberFormatException{
    	String[] strArr = convert2Array(text, split);
    	if(strArr == null){
    		return null;
    	}
    	Integer[] intArr = new Integer[strArr.length];
    	for(int i = 0;i<strArr.length;i++){
    		intArr[i] = Integer.valueOf(strArr[i]);
    	}
    	return intArr;
    	
    }
    public static Integer[] convert2IntegerArray(String text) throws NumberFormatException{
    	return convert2IntegerArray(text,",");
    }
    
    public static List<String> convert2StringList(String text,String split) throws NumberFormatException{
    	List<String> strList = new ArrayList<String>();
    	String[] strArr = convert2Array(text,split);
    	for(String s : strArr){
    		strList.add(s);
    	}
    	return strList;
    }
    
    public static List<String> convert2StringList(String text) {
    	return convert2StringList(text, ",");
    }
    
    public static List<Long> convert2LongList(String text,String split) throws NumberFormatException {
    	List<Long> lList = new ArrayList<Long>();
    	String[] strArr = convert2Array(text,split);
    	if(Strings.isEmpty(strArr)){
    		return null;
    	}
    	for(String s : strArr){
    		Long temp = Long.valueOf(s);
    		lList.add(temp);
    	}
    	return lList;
    }
    
    public static List<Long> convert2LongList(String text) throws NumberFormatException {
    	return convert2LongList(text, ",");
    }
    
    public static List<Integer> convert2IntegerList(String text,String split) throws NumberFormatException {
    	List<Integer> iList = new ArrayList<Integer>();
    	String[] strArr = convert2Array(text,split);
    	if(Strings.isEmpty(strArr)){
    		return null;
    	}
    	for(String s : strArr){
    		Integer temp = Integer.valueOf(s);
    		iList.add(temp);
    	}
    	return iList;
    }
    
    public static List<Integer> convert2IntegerList(String text) throws NumberFormatException {
    	return convert2IntegerList(text, ",");
    }
    
    public static String concat(String symbol,String... param){
    	if(param==null){
    		return null;
    	}
    	String result = "";
    	String[] params = param;
    	for(int i=0;i<params.length;i++){
    		result = i==0?params[i]:result+symbol+params[i]; 
    	}
    	return result;
    }
    public static String substring(String str) {
    	if(str==null){
    		return str;
    	}
    	String string = str;
		if(string.indexOf("</td")>0){
			string = string.substring(0,string.indexOf("</td"));
			if(string.lastIndexOf(">")>-1){
				string = string.substring(string.lastIndexOf(">")+1,string.length());
			}
		}
		if(string.indexOf("</TD")>0){
			string = string.substring(0,string.indexOf("</TD"));
			if(string.lastIndexOf(">")>-1){
				string = string.substring(string.lastIndexOf(">")+1,string.length());
			}
		}
    	return string;
    	
    }


    /**
     * 隐藏固定位数的手机号
     * @param mobile
     * @return
     */
    public static String getHideMobile(String mobile){
        String retValue ="";
        if (Strings.isEmpty(mobile)) return null;
        if (mobile.trim().length()>8){
            retValue = mobile.substring(0, 3)+"**"+mobile.substring(mobile.length()-4, mobile.length());
        }
        return retValue;
    }

    /**
     * 秒转换成小时
     * @param ilSecond
     * @return
     */
    public static String transSecondToHours(Integer ilSecond){
        java.text.DecimalFormat df=new java.text.DecimalFormat("#.00");
        double second  = Math.floor(ilSecond);
        int rate1 = 3600;
        int rate2 = 60;
        String retValue="";
        double result = 0;
        if (second>3600){ //时
            result = second/rate1;
            String aa = df.format(result);
            String[] str = aa.split("\\.");
            String strNum = str[0];
            int decimalNum = Strings.getInteger(str[1]);
            if (Strings.isNotEmpty(strNum) && Strings.getInteger(strNum)>=1){
                if (decimalNum>50){
                    retValue = Strings.getString(Strings.getInteger(strNum)+1);
                } else if(decimalNum==50){
                    retValue = strNum+".5";
                } else {
                    retValue = strNum;
                }
                retValue = retValue+"小时";
            } else {
                retValue = Math.round((decimalNum*60)/100)+"分钟";
            }

        } else if (second<3600 && second>=60) {
            result = second/rate2;
            String aa = df.format(result);
            String[] str = aa.split("\\.");
            String strNum = str[0];
            int decimalNum = Strings.getInteger(str[1]);
            if (Strings.isNotEmpty(strNum) && Strings.getInteger(strNum)>=1){
                if (decimalNum>50){
                    retValue = Strings.getString(Strings.getInteger(strNum)+1);
                } else if(decimalNum==50){
                    retValue = strNum+".5";
                } else {
                    retValue = strNum;
                }
                retValue = retValue+"分钟";
            } else {
                retValue = ((decimalNum*60)/100)+"秒";
            }
        } else {
            retValue = Strings.getString(second)+"秒";
        }
        return retValue;
    }

    /**
     * 转换字符串内url请求为超链
     */
    public static String converStringToLink(String str) {

        String[] endFormat = new String[]{".net", ".cn", ".com"};

        String regEx = "(ftp:\\/\\/|http:\\/\\/|https:\\/\\/)?([A-Za-z0-9_\\-]+\\.)+([A-Za-z0-9_\\-]+)(:\\d+)?\\/?[A-Za-z0-9\\+_\\.\\?=%&\\-@\\/$,]*";
        Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);

        StringBuffer result = new StringBuffer();
        String tempHead = "";
        String tempMiddle = "";
        String patterString = "";
        int num = 0;
        String strTemp = str;
        int count = 0;
        int index = 0;
        int pos = 0;
        int j=0,k=0;
        char[] chars;
        String linkHead;
        String linkEnd;
        boolean isLink;

        Matcher matTemp = p.matcher(strTemp);
        while (matTemp.find()) {   //获取总匹配数
            patterString = matTemp.group();
            index = strTemp.indexOf(patterString);
            if (index > -1) {
                count++;
                strTemp = strTemp.substring(index + patterString.length());
                matTemp = p.matcher(strTemp);
            }
        }

        Matcher m = p.matcher(str);
        if (count > 0) {
            while (m.find()) {
                linkHead = "";
                linkEnd = "";
                isLink = false;

                num++;

                // 匹配到的字符串
                patterString = m.group();

                index = str.indexOf(patterString);

                // 匹配到的字符串前面部分
                tempHead = str.substring(0, index);
                chars = tempHead.toCharArray();

                // 向前循环判断
                for (j = chars.length - 1; j >= 0; j--) {
                    if (chars[j] == '=' || chars[j] == '\"') {
                        // 在属性中，当作超链，不作处理
                        isLink = true;
                        break;
                    } else if (chars[j]=='>') {
                        // 在标签内容中，先认为不是超链，留给后面判断
                        break;
                    }
                }

                // 非超链需要处理
                if (!isLink) {
                    // 清除空白符号
                    linkEnd = str.substring(index + patterString.length()).replaceAll("\\s", "");
                    // 变成字符串，增加几个字符便于比较
                    chars = linkEnd.concat("***").toCharArray();
                    // 结束位置
                    pos = linkEnd.length();

                    for (j = 0; j < pos; j++) {
                        // 出现</a>
                        if (chars[j] == '<' && chars[j+1] == '/' && chars[j+2] == 'a' && chars[j+3] == '>') {
                            tempMiddle = patterString;
                            isLink = true;
                            break;
                        } else if (chars[j] == '<') {
                            break;
                        }
                    }
                }


                if (!isLink) {
                    // 非超链，需要增加超链处理
                    boolean isTrueFormat = false;
                    String tempLink = patterString;

                    strTemp = patterString.toLowerCase();

                    // 获取域名部分
                    pos = strTemp.indexOf("://");
                    if (pos > 0) {
                        strTemp = strTemp.substring(pos + 3);
                    }
                    pos = strTemp.indexOf("/");
                    if (pos > 0) {
                        strTemp = strTemp.substring(0, pos);
                    }
                    pos = strTemp.indexOf(":");
                    if (pos > 0) {
                        strTemp = strTemp.substring(0, pos);
                    }

                    for (String s : endFormat) {
                        if (strTemp.endsWith(s)) {
                            //判断是否为标准格式
                            strTemp = patterString.toLowerCase();
                            if (!strTemp.startsWith("http") && !strTemp.startsWith("ftp")) {
                                tempLink = "http://" + patterString;
                            }
                            tempMiddle = "<a href=\"" + tempLink + "\" target=\"_blank\">" + patterString + "</a>";
                            isTrueFormat = true;
                            break;
                        }
                    }
                    if (!isTrueFormat) {
                        tempMiddle = patterString;
                    }

                } else {
                    tempMiddle = patterString;
                }
                str = str.substring(index + patterString.length());
                result.append(tempHead).append(tempMiddle);
                if (num == count) {   // 最后一次
                    result.append(str);
                }
                m = p.matcher(str);
            }
        } else {
            result.append(str);
        }

        return result.toString();
    }
    
    public static String replaceSpecialSigns(String str){
    	String[] strings = {"&"};
    	for(String string : strings){
    		str = str.replaceAll(string, "");
    	}
    	return str;
    }

}
