package cn.iocoder.yudao.framework.common.util.string;

import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil extends StringUtils {

    public static final String ISO_8859_1 = "iso-8859-1";
    public static final String UTF_8      = "utf-8";
    public static final String EMPY_STRING = "";
    /**
     * 字符串校验
     * @param str
     * @return
     * @author changeTom
     * @email 13424504690@163.com
     * @version 修改时间 2017-12-18
     */
    public static boolean isEmpty(String str) {
        if( null == str || EMPY_STRING.equals(str.trim()) ){
            return true;
        }
        return false;
    }

    public static boolean isEmptyORNull(String str) {

        if (null == str || EMPY_STRING.equals(str.trim()) || "null".equals(str.trim()) || "undefined".equals(str.trim())) {
            return true;
        }
        return false;
    }

    public static boolean isNotEmpty(String str) {
        if ( null == str || EMPY_STRING.equals(str.trim()) || "null".equals(str.trim()) || "undefined".equals(str.trim())) {
            return false;
        }
        return true;

    }

    public static boolean isNotEmptyORNull(String str) {
        if (null != str && ! EMPY_STRING.equals(str.trim()) && !"null".equals(str.trim()) && !"undefined".equals(str.trim())) {
            return true;
        }
        return false;
    }

    public static String numberFormat(Double number, String format) {
        if (number == null || format == null || EMPY_STRING.equals(format)) {
            return EMPY_STRING;
        }

        try {
            DecimalFormat df = new DecimalFormat(format);

            return df.format(number);
        }
        catch (Exception e) {
            return EMPY_STRING;
        }
    }

    public static String hideString(String input, int startPos, int endPos) {
        if (isEmpty(input)) {
            return input;
        }

        int len = input.length();

        if (startPos < 0 || endPos > (len - 1)) {
            return input;
        }

        char[] chars = input.toCharArray();

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < chars.length; i++) {
            if (i < startPos || i > endPos) {
                sb.append(chars[i]);
            }
            else {
                sb.append('*');
            }
        }

        return sb.toString();
    }

    public static String keepSecretString(String firstName, String lastName) {

        String keepSecretString = firstName + " " + lastName;
        StringBuffer sb = new StringBuffer();
        if (keepSecretString.length() < keepSecretString.getBytes().length) {
            keepSecretString = keepSecretString.replace(" ", EMPY_STRING);
            // 中文判断
            char[] chars = keepSecretString.toCharArray();
            System.out.println(chars.length);
            for (int i = 0; i < chars.length; i++) {
                if (i < 1) {
                    sb.append(chars[i]);
                }
                else {
                    sb.append('*');
                }
            }
        }
        else {

            if (StringUtil.isNotEmpty(firstName) && StringUtil.isNotEmpty(lastName)) {
                char[] firstNameChars = firstName.toCharArray();
                char[] lastNameChars = lastName.toCharArray();
                for (int i = 0; i < firstNameChars.length; i++) {
                    if (i < 1 || i > firstNameChars.length) {
                        sb.append(firstNameChars[i]);
                    }
                    else {
                        sb.append('*');
                    }
                }
                sb.append(" ");
                for (int i = 0; i < lastNameChars.length; i++) {
                    if (i < 0 || i > lastNameChars.length - 2) {
                        sb.append(lastNameChars[i]);
                    }
                    else {
                        sb.append('*');
                    }
                }
            }
            else if (StringUtil.isEmpty(firstName) || StringUtil.isEmpty(lastName)) {
                keepSecretString = keepSecretString.replace(" ", EMPY_STRING);
                char[] chars = keepSecretString.toCharArray();
                for (int i = 0; i < chars.length; i++) {
                    if (i < 1 || i > chars.length - 2) {
                        sb.append(chars[i]);
                    }
                    else {
                        sb.append('*');
                    }
                }
            }
        }
        return sb.toString();

    }

    /**
     * 格式化输出电话号码和传真号码
     *
     * @param str 待处理的字符串
     * @return
     * @author Simon.Ye <samlinye@163.com>
     */
    public static String getFriendlyPhoneNumber(String str) {
        if (isEmpty(str)) {
            return EMPY_STRING;
        }

        Pattern pattern;
        Matcher matcher;

        String countryCode = EMPY_STRING;
        String areaCode = EMPY_STRING;
        String number = EMPY_STRING;

        pattern = Pattern.compile("^\\([+]*([0-9]*)\\)([0-9]+)[-]+([0-9]+)$");
        matcher = pattern.matcher(str);
        while (matcher.find()) {
            countryCode = matcher.group(1);
            areaCode = matcher.group(2);
            number = matcher.group(3);
            return "(+" + countryCode + ")" + areaCode + "-" + number;
        }

        matcher.reset();
        pattern = Pattern.compile("^([0-9]+)[-]+([0-9]+)$");
        matcher = pattern.matcher(str);
        while (matcher.find()) {
            areaCode = matcher.group(1);
            number = matcher.group(2);
            return areaCode + "-" + number;
        }

        matcher.reset();
        pattern = Pattern.compile("^([0-9]+)-([0-9]+)-([0-9]+)$");
        matcher = pattern.matcher(str);
        while (matcher.find()) {
            countryCode = matcher.group(1);
            areaCode = matcher.group(2);
            number = matcher.group(3);
            return "(+" + countryCode + ")" + areaCode + "-" + number;
        }

        matcher.reset();
        pattern = Pattern.compile("^([0-9]+)-([0-9]+)$");
        matcher = pattern.matcher(str);
        while (matcher.find()) {
            areaCode = matcher.group(1);
            number = matcher.group(2);
            return areaCode + "-" + number;
        }

        return str;
    }

    /**
     * 格式化输出手机号码
     *
     * @param str 待处理的字符串
     * @return
     * @author Simon.Ye <samlinye@163.com>
     */
    public static String getFriendlyMobileNumber(String str) {
        if (isEmpty(str)) {
            return EMPY_STRING;
        }

        Pattern pattern;
        Matcher matcher;

        String countryCode = EMPY_STRING;
        String number = EMPY_STRING;

        pattern = Pattern.compile("^\\([+]*([0-9]*)\\)([0-9]+)$");
        matcher = pattern.matcher(str);
        while (matcher.find()) {
            countryCode = matcher.group(1);
            number = matcher.group(2);
            return "(+" + countryCode + ")" + number;
        }

        matcher.reset();
        pattern = Pattern.compile("^([0-9]+)-([0-9]+)$");
        matcher = pattern.matcher(str);
        while (matcher.find()) {
            countryCode = matcher.group(1);
            number = matcher.group(2);
            return "(+" + countryCode + ")" + number;
        }

        return str;
    }

    public static String getImageAbslouteUrl(String url, String mediaPath) {
        if (!isNotEmpty(url) || !isNotEmpty(mediaPath)) {
            return EMPY_STRING;
        }
        if (url.startsWith("/")) {
            return mediaPath + url;
        }
        return mediaPath + "/" + url;
    }

    public static String replaceSign(String str) {
        if (isNotEmpty(str) && str.indexOf(",") != -1) {
            str = str.replaceAll(",", "\\|");
        }
        return str;
    }

    public static String replaceSign(String str, String from, String to) {
        if (isNotEmpty(str) && str.indexOf(from) != -1) {
            str = str.replaceAll(from, to);
        }
        return str;
    }

    public static String toString(Object obj) {
        return obj != null ? obj.toString() : EMPY_STRING;
    }

    /**
     * 编码转换
     *
     * @param str             需要转换的字符串
     * @param currentEncoding 当前内码
     * @param targetEncoding  目标内码
     * @return
     */
    public static String toEncoding(String str, String currentEncoding, String targetEncoding) {
        try {
            if (str != null && !str.equals(EMPY_STRING)) {
                return new String(str.getBytes(currentEncoding), targetEncoding);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String arrayToString(Object[] array) {
        StringBuffer sb = new StringBuffer();
        String result = EMPY_STRING;
        if (array != null && array.length > 0) {
            for (Object temp : array) {
                if (temp != null) {
                    sb.append(String.valueOf(temp));
                    sb.append(",");
                }
            }
            result = sb.substring(0, sb.toString().length() - 1);
        }
        return result;
    }

    /**
     *
     * @param list 转成 a,b,c
     * @return
     */
    public static String listToString(List<String> list) {
        StringBuffer sb = new StringBuffer();
        String result = EMPY_STRING;
        if (list != null && list.size() > 0) {
            for (Object temp : list) {
                sb.append(String.valueOf(temp).trim());
                sb.append(",");
            }
            result = sb.length() > 0 ? sb.substring(0, sb.toString().length() - 1) : EMPY_STRING;
        }
        return result;
    }

    /**
     *
     * @param arrayString 如：a,b,c,
     * @return
     */
    public static List<String> StringToList(String arrayString) {
        List<String> resultList = new ArrayList<String>();
        if (null != arrayString) {
            String[] stringArray = arrayString.split(",");
            if (stringArray != null && stringArray.length > 0) {
                for (String temp : stringArray) {
                    resultList.add(temp);
                }
            }
        }
        return resultList;
    }

    public static String getValueFromMap(Map<String, String> paramMap, String key) {
        if (isEmpty(key))
            return EMPY_STRING;
        String result = EMPY_STRING;
        if (paramMap.containsKey(key)) {
            result = paramMap.get(key);
            result = result != null ? result : EMPY_STRING;
        }
        return result;

    }

    public static String arrayToStringSQL(Object[] array) {
        StringBuffer sb = new StringBuffer();
        String result = EMPY_STRING;
        if (array != null && array.length > 0) {
            for (Object temp : array) {
                sb.append("'" + String.valueOf(temp) + "'");
                sb.append(",");
            }
            result = sb.substring(0, sb.toString().length() - 1);
        }
        return result;
    }

    /************************************************新增工具类**********************************************/

    /**
     * 检测对象是否为空
     *
     * @param obj
     * @return
     */
    public static boolean checkObj(Object obj) {
        boolean bool = true;
        if (obj == null || EMPY_STRING.equals(obj.toString().trim()))
            bool = false;
        return bool;
    }

    /**
     * 判断是否数值
     *
     * @param str
     * @return
     */
    public static boolean isNum(String str) {
        boolean flg;
        try {
            Double.parseDouble(str);
            flg = true;
        }
        catch (Exception ex) {
            flg = false;
        }
        return flg;
    }
    public static  String toDouble(String str){
        boolean flg = StringUtil.isNum(str);
        if (flg){
            return str;
        }
        return "0";
    }

    public static String adjustUrl(String url, int size) {
        String returnResult = "#";
        if (StringUtil.isNotEmptyORNull(url)) {
            StringBuffer imageUrl = new StringBuffer(url);
            returnResult = imageUrl.insert(imageUrl.lastIndexOf("."), "-" + String.valueOf(size) + "-" + String.valueOf(size)).toString();
        }
        return returnResult;
    }

    /**
     * 去除字符串左右两边的第一个目标字符
     *
     * @param replaceStr 目标字符
     * @return
     */
    public static String removeLeftAndRightTheFirstStr(String value, String replaceStr) {
        if (value != null) {
            if (value.indexOf(replaceStr) == 0 && value.lastIndexOf(replaceStr) == value.length() - 1) {
                value = value.substring(1, value.length() - 1);
            }
        }
        return value;
    }

    /**
     * 格式化金额
     * <pre>如100分转换成元，结果打印0.10</pre>
     *
     * @param value 目标字符
     * @return ##,##0.00
     */
    public static String formatMoney(String value) {
        try {
            if (org.apache.commons.lang3.StringUtils.isNumeric(value)) {
                DecimalFormat myformat = new DecimalFormat();
                myformat.applyPattern("##,##0.00");
                value = myformat.format(Double.parseDouble(value) / 100);
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return value;
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符
     * @param str 要去除空格、回车、换行符、制表符的字符串
     * @return
     */
    public static String getStringNoBlank(String str) {
        if(str!=null && !EMPY_STRING.equals(str)) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");    /*\s 空格(\u0008), \t 水平制表符(\u0009), \r 换行(\u000d), \n 回车(\u000a) */
            Matcher m = p.matcher(str);
            String strNoBlank = m.replaceAll(EMPY_STRING);
            return strNoBlank;
        }else {
            return str;
        }
    }
    /**
     * 将字符串中的回车、换行符替换成HTML形式的换行符
     * @param str 要转换的字符串
     * @return
     */
    public static String carriageReturnConvertToHtml(String str) {
    	if(str!=null && !EMPY_STRING.equals(str)) {
    		Pattern p = Pattern.compile("\r\n");    /*\s 空格(\u0008), \t 水平制表符(\u0009), \r 换行(\u000d), \n 回车(\u000a) */
    		Matcher m = p.matcher(str);
    		String result = m.replaceAll("</br>");
    		return result;
    	}else {
    		return str;
    	}
    }

    /**
     * 将字符串中的空格替换成HTML形式的空格&nbsp;
     * @param str 要转换的字符串
     * @return
     */
    public static String convertBlankToHtml(String str) {
    	if(str!=null && !EMPY_STRING.equals(str)) {
    		Pattern p = Pattern.compile("\\s");    /*\s 空格(\u0008), \t 水平制表符(\u0009), \r 换行(\u000d), \n 回车(\u000a) */
    		Matcher m = p.matcher(str);
    		String result = m.replaceAll("&nbsp;");
    		return result;
    	}else {
    		return str;
    	}
    }

    /**
     * 验证前台传过来的ids是否合法
     * @param ids
     * @return 数据合法返回true,否则返回false
     */
    public static boolean validateIdsIsLegal(String ids) {
    	if(ids!=null && !EMPY_STRING.equals(ids)) {
    		String[] idArray = ids.split(",");
        	for(String id:idArray){
        		//如果是不合法的数据，将会报错
        		try {
					Integer.parseInt(id);
				} catch (NumberFormatException e) {
					e.printStackTrace();
					return false;
				}
        	}

    	}
    	return true;
    }
    /**
     * 判断是否为中文
     * @param args
     */
    public static boolean isChineseChar(String str){
        boolean temp = false;
        Pattern p=Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m=p.matcher(str);
        if(m.find()){
            temp =  true;
        }
        return temp;
    }
    /**
     * 判断首字符是否为字母
     * @param str
     * @return
     */
    public static boolean isAlpha(String str){
    	char c=str.charAt(0);
    	int i=(int) c;
	    if((i>=65&&i<=90)||(i>=97&&i<=122)){
	    	return   true;
	    }else{
	    	return   false;
	    }
    }


    public static String getDataStr(String str){
		return str==null?EMPY_STRING:str;
	}

    public static Integer getDataInt(Integer integer){
    	return integer==null?0:integer;
    }


    /**
	* 首字母大写
	*
	* @param srcStr
	* @return
	*/
	public static String firstCharacterToUpper(String srcStr) {
	   return srcStr.substring(0, 1).toUpperCase() + srcStr.substring(1);
	}
	/**
	* 替换字符串并让它的下一个字母为大写
	* @param srcStr
	* @param org
	* @param ob
	* @return
	*/
	public static String replaceUnderlineAndfirstToUpper(String srcStr,String org,String ob)
	{
	   String newString = EMPY_STRING;
	   int first=0;
	   while(srcStr.indexOf(org)!=-1)
	   {
	    first=srcStr.indexOf(org);
	    if(first!=srcStr.length())
	    {
	     newString=newString+srcStr.substring(0,first)+ob;
	     srcStr=srcStr.substring(first+org.length(),srcStr.length());
	     srcStr=firstCharacterToUpper(srcStr);
	    }
	   }
	   newString=newString+srcStr;
	   return newString;
	}
    /**
     *
     * @Description 方法描述: 查看字符串
     * @param str
     * @return
     * @author  changeTom
     * @date 时间: 2018年6月26日 下午3:56:43
     */
	public static int getSplit(String str){
		if(StringUtil.isEmpty(str)){
			return 0;
		}
		return  str.split("\\.").length;
	}


	/**
	 *
	 * @Description 方法描述:去下划线并转成驼峰  例如: dis_play 转为 disPlay
	 * @return
	 * @author  changeTom
	 * @date 时间: 2018年8月20日 下午2:56:52
	 */
	public static String getTableNameHump(String tablename) {
		boolean frist =false;
		StringBuffer sb = new StringBuffer();
		for(String talenamepart : tablename.split("_")){
			if(frist){
				sb.append(talenamepart.substring(0, 1).toUpperCase());
				sb.append(talenamepart.substring(1));
			}else{
				sb.append(talenamepart);
				frist = true;
			}
		}
		return sb.toString();
	}

	public static String getTableNameAs(String tablename){
		return "IFNULL("+tablename +",'') AS " + getTableNameHump(tablename);
	}
	/**
	 * 在一个串字符串中得到汉字
	 * @return
	 */
	public static List<String> getChineseCharacter(String str){
		List<String> hanziList = new ArrayList<String>();
		Pattern p = null;
		Matcher m = null;
		String value = null;
		p = Pattern.compile("([\u4e00-\u9fa5]+)");//          汉字的在unicode编码的范围区域：\u4e00-\u9fa5
		m = p.matcher(str);
		while (m.find()) {
			value = m.group(0);
			hanziList.add(value);//先一个个匹配取出放在list集合中
		}
		return hanziList;
	}


    public static String underline2Camel(String underline){
        Pattern pattern = Pattern.compile("[_]\\w");
        String camel = underline;
        Matcher matcher = pattern.matcher(camel);
        while(matcher.find()){
            String w = matcher.group().trim();
            camel = camel.replace(w,w.toUpperCase().replace("_", EMPY_STRING));
        }
        return camel;
    }

    /**
     * 驼峰法转下划线
     *
     * @param line
     *            源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line) {
        Pattern humpPattern = Pattern.compile("[A-Z]");
        if (line == null || "".equals(line)) {
            return "";
        }
        Matcher matcher = humpPattern.matcher(line);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


    /**
     * 删除字符串后面为0的字符
     */
    public static String delZero(String src) {
		if (src.endsWith("0"))
			return delZero(src.substring(0, src.length() - 1));
		else
			return src;
	}

	public static String getPlanname(String type, int rotation) {
        String chineseNum = null;
        switch (rotation) {
            case 0:
                chineseNum = "一";
                break;
            case 1:
                chineseNum = "二";
                break;
            case 2:
                chineseNum = "三";
                break;
            case 3:
                chineseNum = "四";
                break;
            case 4:
                chineseNum = "五";
                break;
            case 5:
                chineseNum = "六";
                break;
            case 6:
                chineseNum = "七";
                break;
            case 7:
                chineseNum = "八";
                break;
            case 8:
                chineseNum = "九";
                break;
            default:
                chineseNum = "十";
                break;
        }
        String result = null;
        if (type.equals("填报")) {
            result = "第" + chineseNum + "轮(指标填报)";
            //result = "一".equals(chineseNum) ? "第" + chineseNum + "轮(指标填报)" : "第" + chineseNum + "轮(指标审核)";
        }else if (type.equals("指标调整")) {
            result = "第" + chineseNum + "轮(指标调整)";
        }else if (type.equals("评分")) {
            result = "第" + chineseNum + "轮(评分)";
        }
        return result;
    }

	public static Integer getRotation(String planname) {
        String param = planname.substring(0,3);
        Integer num = null;
        switch (param) {
            case "第一轮":
                num = 0;
                break;
            case "第二轮":
                num = 1;
                break;
            case "第三轮":
                num = 2;
                break;
            case "第四轮":
                num = 3;
                break;
            case "第五轮":
                num = 4;
                break;
            case "第六轮":
                num = 5;
                break;
            case "第七轮":
                num = 6;
                break;
            case "第八轮":
                num = 7;
                break;
            case "第九轮":
                num = 8;
                break;
            default:
                num = 9;
                break;
        }
        return num;
    }

}