package cn.estsh.i3plus.pojo.base.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

	public static boolean isEmpty(Object obj){
		
		if(obj ==null || obj.toString().trim().equals("")){
			return true;
		}
		
		return false;
	}

	/**
	 * 获取对象所有属性名
	 * @param clazz
	 * @return
	 */
	public static String[] getFields(Class clazz) {
		Field[] fields = clazz.getDeclaredFields();
		String[] fieldNames = new String[fields.length];
		for(int i=0;i<fields.length;i++){
			fieldNames[i]=fields[i].getName();
		}
		return fieldNames;
	}

	/**
	 * 获取对象所有属性名
	 * @param clazz
	 * @return
	 */
	public static List<String> getFieldList(Class clazz) {
		Field[] fields = clazz.getDeclaredFields();
		Field[] superFields = clazz.getSuperclass().getDeclaredFields();
		List<String> fieldNames = new ArrayList<>();
		for(int i = 0;i < fields.length; i++){
			fieldNames.add(fields[i].getName());
		}
		for(int i = 0;i < superFields.length; i++){
			fieldNames.add(superFields[i].getName());
		}
		return fieldNames;
	}

	/**
	 * 根据属性名和对象获取属性对应的值
	 * @param fieldName
	 * @param o
	 * @return
	 */
	public static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			return null;
		}
	}

	private static Pattern linePattern = Pattern.compile("_(\\w)");

	/** 驼峰转下划线 */
	public static Map<String, Object> humpToLine(Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<>();
		for (String str : map.keySet()) {
			str = str.toLowerCase();
			Matcher matcher = linePattern.matcher(str);
			StringBuffer sb = new StringBuffer();
			while (matcher.find()) {
				matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
			}
			matcher.appendTail(sb);
			resultMap.put(sb.toString(), map.get(str));
		}
		return resultMap;
	}
}
