package com.neusoft.smart.pos.framework.utils;

import com.google.common.collect.Maps;
import org.apache.commons.beanutils.BeanMap;

import java.util.Map;

public class MapBeanUtils {

    /**
     * 将对象转换为map
     * @param bean
     * @return
     */
    public static <T> Map<String, String> beanToMap(T bean) {
        Map<String, String> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = new BeanMap(bean);
            for (Object key : beanMap.keySet()) {
                if(null == beanMap.get(key)){
                    map.put(key+"","");
                } else if (key.toString().equalsIgnoreCase("class")) {
                    continue;
                } else if (String.valueOf(beanMap.get(key)).startsWith("[")){
                        continue;
                }else{
                    map.put(key+"", String.valueOf(beanMap.get(key)));
                }
            }
        }
        return map;
    }

    /**
     * 将map转换为对象
     * @return
     */
    public static <T> T mapToBean(Map map, Class<T> beanClass){
        if (map == null){
            return null;
        }
        T bean = null;
        try {
            bean = beanClass.newInstance();
            org.apache.commons.beanutils.BeanUtils.populate(bean, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    /**
     * 将map转换为对象
     * @return
     */
    public static <T> void mapToBean(Map properties, T bean){
        if (bean != null && properties != null) {

            properties.forEach((key, value) -> {
                if (key != null) {
                    try {
                        org.apache.commons.beanutils.BeanUtils.setProperty(bean, key.toString(), value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

}
