package cn.hmsoft.helper;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/*********************
 * 字符串复制类
 * 
 * @author zxq
 * @create 2018-04-05 21:56:50
 * @version 5.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */
public class StringHelper {
	/*****************************
	 * 判断字符串是否为空（空值或者空格都认为是空）
	 */
	public static boolean isEmpty(String value) {
		return (value == null || value.trim().length() == 0);
	}

	/*****************************
	 * 判断是否为空（空值或者空格都认为是空）
	 */
	public static boolean isEmpty(Object value) {
		return (value == null || value.toString().trim().length() == 0);
	}

	/*****************************
	 * 判断字符串是否不为空（空值或者空格都认为是空）
	 */
	public static boolean isNotEmpty(String value) {
		return !isEmpty(value);
	}

	/*****************************
	 * 判断是否不为空（空值或者空格都认为是空）
	 */
	public static boolean isNotEmpty(Object value) {
		return !isEmpty(value);
	}

	/*****************************
	 * 数据库字段名称转换为java类属性 CUST_NAME => CustName;
	 */
	public static String toClassName(String columnName) {
		if (isEmpty(columnName))
			return "";
		StringBuilder sb = new StringBuilder();
		for (String s : columnName.split("_")) {
			if (s.length() > 0)
				sb.append(s.substring(0, 1).toUpperCase());
			if (s.length() > 1)
				sb.append(s.substring(1).toLowerCase());
		}
		return sb.toString();
	}

	/**********************************
	 * 数据库字段名称转换为java类属性 CUST_NAME => custName;
	 */
	public static String toFieldName(String columnName) {
		return lowerFirstChar(toClassName(columnName));

	}

	/**********************************************
	 * java类属性名称转换成数据库名称 custName=>CUST_NAME
	 */
	public static String toColumnName(String fieldName) {
		if (isEmpty(fieldName))
			return "";
		char c = Character.toUpperCase(fieldName.charAt(0));
		StringBuilder sb = new StringBuilder();
		sb.append(c);
		for (int i = 1; i < fieldName.length(); i++) {
			if (Character.isUpperCase(fieldName.charAt(i)))
				sb.append("_");
			sb.append(Character.toUpperCase(fieldName.charAt(i)));
		}
		return sb.toString().toUpperCase();
	}

	/***************************************
	 * 首字母大写
	 */
	public static String upperFirstChar(String source) {
		if (isEmpty(source))
			return "";
		if (source.length() == 1)
			return source.toUpperCase();
		return source.substring(0, 1).toUpperCase() + source.substring(1);
	}

	/*****************************************
	 * 首字母小写
	 */
	public static String lowerFirstChar(String source) {
		if (isEmpty(source))
			return "";
		if (source.length() == 1)
			return source.toUpperCase();
		return source.substring(0, 1).toLowerCase() + source.substring(1);
	}

	/*****************************************
	 * 分割不定长度的空白字符
	 */
	public static String[] splitWithSpace(String source) {
		return source.split("\\s+");
	}

	/***************************************************
	 * 左边补齐
	 */

	public static String leftPadding(String source, int length, char padding) {
		if (source == null)
			source = "";
		String value = "";
		for (int i = 0; i < length - source.length(); i++) {
			value += padding;
		}
		return value + source;
	}

	/***************************************************
	 * 右边补齐
	 */

	public static String rightPadding(String source, int length, String padding) {
		if (source == null)
			source = "";
		String value = "";
		for (int i = 0; i < length - source.getBytes().length; i++) {
			value += padding;
		}
		return source + value;
	}

	/*************************************
	 * 字符串到map 回车换行  冒号(:)分割
	 * 
	 */
	public static LinkedHashMap<String, String> toMap(String param_str) {
		LinkedHashMap<String, String> paramMap = new LinkedHashMap<String, String>();
		if(param_str == null)
			param_str = "";
		String[] values = param_str.trim().split("\r\n");
		if(values.length==1)
			values = param_str.trim().split("\n");
		if (StringHelper.isNotEmpty(param_str)) {
			for (String value : values) {
				String[] array = value.split(":");
				if (array.length > 1) {
					paramMap.put(array[0].trim(), value.substring(array[0].length() + 1, value.length()));
				}
			}
		}
		return paramMap;
	}
	
	
	/**
	 * 配置文件转换，等号分割
	 * @param propertiesString
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, String> toProperties(String propertiesString) {
		if( isEmpty(propertiesString))
			return Collections.EMPTY_MAP;

		Properties properties = new Properties();
		try {
			properties.load(new StringReader(propertiesString));
			return new HashMap<String, String>((Map) properties);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static Map<String, String> getUrlQueryParams(String query) {
		Map<String, String> result = new HashMap<>();
		query = query.trim();
		if (query.equals("")) {
			return result;
		}
		String[] params = query.split("&");
		for (String param : params) {
			String[] keyValue = param.split("=");
			if (keyValue.length == 1)
				result.put(keyValue[0], "");
			else
				result.put(keyValue[0], keyValue[1]);
		}
		return result;
	}
	
	
	/**
	 * 参数URL化，并按ascii排序
	 * @param paraMap
	 * @return
	 */
	public static String asUrlParams(Map<String, String> paraMap) {
		return asUrlParams(paraMap, true, true);
	}

	public static String asUrlParams(Enumeration  paraMap, boolean urlEncode, boolean keyToLower) {
		
		return "";
	}
	public static String asUrlParams(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower) {
		String buff = "";
		List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(paraMap.entrySet());
		Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
			@Override
			public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
				return (o1.getKey()).toString().compareTo(o2.getKey());
			}
		});
		// 构造URL 键值对的格式
		StringBuilder buf = new StringBuilder();
		for (Map.Entry<String, String> item : infoIds) {
			if (isNotEmpty(item.getKey())) {
				String key = item.getKey();
				String val = item.getValue();
				if (urlEncode)
					try {
						val = URLEncoder.encode(val, "utf-8");
					} catch (UnsupportedEncodingException e) {
					}

				if (keyToLower)
					buf.append(key.toLowerCase() + "=" + val);
				else
					buf.append(key + "=" + val);

				buf.append("&");
			}
		}
		buff = buf.toString();
		if (buff.isEmpty() == false)
			buff = buff.substring(0, buff.length() - 1);
		return buff;
	}
	
	public static String concat(Object... s) {
		StringBuffer buildKey = new StringBuffer(100);
		for (Object p : s) {
			if (p != null)
				buildKey.append(":").append(p.toString());
		}
		String r = buildKey.toString();
		return r.substring(1, r.length());
	}
}
