package cn.pluss.platform.util;

import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author djh
 */
public class MapUtils {

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

    private static String classStr = "class";

    /**
     * map转MultiValueMap
     * @param map 原map
     * @return  。
     */
    public static MultiValueMap<String, Object> map2MultiValueMap(Map<String, Object> map) {
        val result = new LinkedMultiValueMap<String, Object>();

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                result.add(entry.getKey(), entry.getValue());
            }
        }

        return result;
    }
    public static Map<String, String> objectToMapString(final Object o, boolean isIgnoreBlankOrNull) {
        try {
            Map<String, String> map = new HashMap<String, String>();
            BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass());
            for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
                String name = descriptor.getName();
                if (classStr.equals(name))
                    continue;
                Object obj = descriptor.getReadMethod().invoke(o);
                if (isIgnoreBlankOrNull
                        && (obj == null || (obj instanceof String && StringUtil.isBlank((String) obj)))) {

                } else {
                    map.put(name, String.valueOf(obj));
                }
            }
            return map;
        } catch (IntrospectionException e) {
            logger.error("转换异常：{}", e);
        } catch (IllegalArgumentException e) {
            logger.error("转换异常：{}", e);
        } catch (IllegalAccessException e) {
            logger.error("转换异常：{}", e);
        } catch (InvocationTargetException e) {
            logger.error("转换异常：{}", e);
        }
        return null;
    }
}
