package com.dgtly.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapBeanUtil {
    /**
     * 实体对象转成Map
     *
     * @param obj 实体对象
     * @return
     */
    public static Map<String, Object> object2Map(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * Map转成实体对象
     *
     * @param map   实体对象包含属性
     * @param clazz 实体对象类型
     * @return
     */
    public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
        if (map == null) {
            return null;
        }
        Object obj = null;
        try {
            obj = clazz.newInstance();

            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }


    /**
     * 将list转为map 且以key字段为键
     * @param list
     * @param fieldName 作为关键字的字段
     * @return
     * @throws Exception
     */
    public static Map<?,?> listToMap(List<?> list, String fieldName ) throws Exception {
        Class<?> bean ;
        if(list.size()>0){
            bean =  list.get(0).getClass();
        }else{
            throw new NullPointerException("转换List数组为空");
        }

        Field field = null;
        try {
            field = bean.getDeclaredField(fieldName);
            field.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new NoSuchFieldException("未查找到字段名称为："+fieldName+"的属性");
        }
        Class<?> fieldType=field.getType();

        Map resultMap = new HashMap<>();
        for(int i=0;i<list.size();i++){
            Object o = list.get(i);
            Object keyField = field.get(o);
            if(!resultMap.containsKey(keyField)){
                resultMap.put(keyField,o);
            }
        }
        return resultMap;
    }

}
