package cn.estsh.i3plus.pojo.base.util;

import com.google.common.collect.Lists;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanMapUtils {
    /**
     * 将对象属性转化为map结合
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }


    /**
     * 将map集合中的数据转化为指定对象的同名属性中
     */
    public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) throws Exception {
        T bean = clazz.newInstance();
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;

    }

    /**
     * 键值对转换为对象
     *
     * @param mapList
     * @return
     */
    public static List<Object> generateObjectByField(List<Map<String, String>> mapList) {
        try {
            List<Object> resultList = new ArrayList<>();
            for (Map<String, String> propertyMap : mapList) {
                BeanGenerator generator = new BeanGenerator();
                for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
                    generator.addProperty(entry.getKey(), String.class);
                }
                // 构建对象
                Object obj = generator.create();
                // 赋值
                for (Map.Entry<String, String> en : propertyMap.entrySet()) {
                    BeanUtils.setProperty(obj, en.getKey(), en.getValue());
                }
                resultList.add(obj);
            }
            return resultList;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 将List<obj>转换为List<Map<String,Object>>
     * @param objList
     * @param <T>
     * @return
     */
    public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
        List<Map<String, Object>> list = Lists.newArrayList();
        if (objList != null && objList.size() > 0) {
            Map<String, Object> map = null;
            T bean = null;
            for (int i = 0, size = objList.size(); i < size; i++) {
                bean = objList.get(i);
                map = beanToMap(bean);
                list.add(map);
            }
        }
        return list;
    }
}
