package com.huigou.topsun.util;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {

	/**
	 * @Description TODO(自动生成uuid)
	 */
	public static String createUuid() {
		UUID u = UUID.randomUUID();
		String uuid = u.toString().replace("-", "").toUpperCase();
		return uuid;
	}

	/**
	 * 实体类转Map
	 *
	 * @param obj
	 * @return
	 */
	public static HashMap<String, String> entityToMap(Object obj) {
		HashMap<String, String> map = new HashMap();
		for (Field field : obj.getClass().getDeclaredFields()) {
			try {
				boolean flag = field.isAccessible();
				field.setAccessible(true);
				Object o = field.get(obj);
				if (o != null) {
					Field contField = obj.getClass().getDeclaredField(field.getName());
					JsonProperty voField = contField.getAnnotation(JsonProperty.class);
					String s = voField.value();
					map.put(s, o.toString());
				}
				field.setAccessible(flag);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	/**
	 * 下划线转驼峰法
	 * @param line 源字符串
	 * @param smallCamel 大小驼峰,是否为小驼峰
	 * @return 转换后的字符串
	 */
	public static String underlineToCamel(String line,boolean smallCamel){
		if(line==null||"".equals(line)){
			return "";
		}
		StringBuffer sb=new StringBuffer();
		Pattern pattern=Pattern.compile("([A-Za-z\\d]+)(_)?");
		Matcher matcher=pattern.matcher(line);
		while(matcher.find()){
			String word=matcher.group();
			sb.append(smallCamel&&matcher.start()==0?Character.toLowerCase(word.charAt(0)):Character.toUpperCase(word.charAt(0)));
			int index=word.lastIndexOf('_');
			if(index>0){
				sb.append(word.substring(1, index).toLowerCase());
			}else{
				sb.append(word.substring(1).toLowerCase());
			}
		}
		return sb.toString();
	}
	/**
	 * 驼峰法转下划线
	 * @param line 源字符串
	 * @return 转换后的字符串
	 */
	public static String camelToUnderline(String line){
		if(line==null||"".equals(line)){
			return "";
		}
		line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
		StringBuffer sb=new StringBuffer();
		Pattern pattern=Pattern.compile("[A-Z]([a-z\\d]+)?");
		Matcher matcher=pattern.matcher(line);
		while(matcher.find()){
			String word=matcher.group();
			sb.append(word.toUpperCase());
			sb.append(matcher.end()==line.length()?"":"_");
		}
		return sb.toString();
	}

}
