package com.lantone.structure.util;

import com.google.common.collect.Maps;
import com.lantone.common.util.StringUtil;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: map工具类
 * @author: gaodm
 * @time: 2018/9/4 9:24
 */
public class MapUtil {


    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }

        Object obj = beanClass.newInstance();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            if (setter != null) {
                setter.invoke(obj, map.get(property.getName()));
            }
        }

        return obj;
    }

    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter != null ? getter.invoke(obj) : null;
            map.put(key, value);
        }
        return map;
    }

    /**
     * 复制一个map
     *
     * @param map
     * @return
     */
    public static Map<String, Object> copyMap(Map<String, Object> map) {
        if (map == null) {
            return null;
        }
        Map<String, Object> retMap = Maps.newHashMap();
        map.keySet().forEach(key -> {
            retMap.put(key, map.get(key));
        });
        return retMap;
    }

    /**
     * map key同义词赋值
     *
     * @param map
     * @param sourceKey
     * @param targetKeys
     */
    public static void keyAssig(Map<String, String> map, String sourceKey, String... targetKeys) {
        if (map == null || StringUtil.isBlank(sourceKey) || targetKeys == null || targetKeys.length == 0 || StringUtil.isNotBlank(map.get(sourceKey))) {
            return;
        }
        for (String targetKey : targetKeys) {
            if (StringUtil.isNotBlank(map.get(targetKey))) {
                map.put(sourceKey, map.get(targetKey));
                break;
            }
        }
    }

}