package org.ta.pddserver.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;

public class ObjectCommonTool {

    public static HashMap objectToMap(Object obj) {
        HashMap<String, Object> map = new HashMap<>();
        if (obj == null) {
            return null;
        }

        Field[] fields = obj.getClass().getDeclaredFields();//获取类的各个属性值
        for (Field field : fields) {
            String fieldName = field.getName();//获取类的属性名称
            if (getValueByFieldName(fieldName, obj) != null)//获取类的属性名称对应的值
            {
                map.put(fieldName, getValueByFieldName(fieldName, obj));
            }
        }
        fields = obj.getClass().getSuperclass().getDeclaredFields();//获取类的各个属性值
        for (Field field : fields) {
            String fieldName = field.getName();//获取类的属性名称
            if (getValueByFieldName(fieldName, obj) != null)//获取类的属性名称对应的值
            {
                map.put(fieldName, getValueByFieldName(fieldName, obj));
            }
        }
        return map;
    }

    private static Object getValueByFieldName(String fieldName, Object object) {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldName.substring(1);
        try {
            Method method = object.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(object, new Object[]{});
            return value;
        } catch (Exception e) {
            return null;
        }
    }

    public static MultiValueMap<String, String> objectToMultiValueMap(Object obj) {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        if (obj == null) {
            return null;
        }

        Field[] fields = obj.getClass().getDeclaredFields();//获取类的各个属性值
        for (Field field : fields) {
            String fieldName = field.getName();//获取类的属性名称
            if (getValueByFieldName(fieldName, obj) != null)//获取类的属性名称对应的值
            {
                map.add(fieldName, JSON.toJSONString(getValueByFieldName(fieldName, obj)));
            }
        }
        fields = obj.getClass().getSuperclass().getDeclaredFields();//获取类的各个属性值
        for (Field field : fields) {
            String fieldName = field.getName();//获取类的属性名称
            if (getValueByFieldName(fieldName, obj) != null)//获取类的属性名称对应的值
            {
                map.add(fieldName, JSON.toJSONString(getValueByFieldName(fieldName, obj)));
            }
        }
        return map;
    }
}
