package com.bcxin.signature.util;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * Object转Map
 */
public class ObjectToMapUtil {

	private static final Logger logger = LoggerFactory.getLogger(ObjectToMapUtil.class);

	/**
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 * @Decription:
	 * @author：zhongjianhui
	 * @method ObjectToMap @date：2018/3/20 16:10 @params： * @param obj
	 */
	public static Map<String, Object> ObjectToMap(Object obj) {
		Map<String, Object> paramMap = new HashMap<>();
		// 父类
		if (ObjectUtil.isNotNull(obj)) {
			if (obj.getClass().getSuperclass() != null
					&& obj.getClass().getSuperclass().getDeclaredFields().length > 0) {
				Field[] fieldsSuper = obj.getClass().getSuperclass().getDeclaredFields();
				for (int i = 0; i < fieldsSuper.length; i++) {

					Field subField = fieldsSuper[i];

					Object value;
					try {

						if (subField.getModifiers() < 9) {
							value = BeanUtils.getProperty(obj, subField.getName());
							if (ObjectUtil.isNotNull(value)) {
								paramMap.put(fieldsSuper[i].getName(), value);
							}
						}
					} catch (Exception e) {
						logger.error(e.getMessage());
						e.printStackTrace();
					}
				}
			}

			Field[] fields = obj.getClass().getDeclaredFields();

			for (int i = 0; i < fields.length; i++) {
				Field subField = null;
				try {
					subField = obj.getClass().getDeclaredField(fields[i].getName());
				} catch (NoSuchFieldException e) {
					e.printStackTrace();
				}
				Object value;
				try {
					if (subField.getGenericType().toString().contains("com.bcxin")) {

						PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
						Object useValue = propertyUtilsBean.getNestedProperty(obj, subField.getName());
						if (ObjectUtil.isNotNull(useValue)) {
							System.out.println("useValue:" + useValue.toString());
							Map<String, Object> paramMap2 = ObjectToMap(useValue);
							paramMap.putAll(paramMap2);
						}
					}
					if (subField.getModifiers() < 9) {
						value = BeanUtils.getProperty(obj, subField.getName());
						if (ObjectUtil.isNotNull(value)) {
							paramMap.put(fields[i].getName(), value);
						}
					}
				} catch (NoSuchMethodException e) {

				} catch (ClassCastException e) {

				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (Exception e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
			}
		}
		return paramMap;
	}

	public static void main(String[] args) throws Exception {
	}
}
