package com.hs.admin.util;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author:XIEHENG
 * @Date: 2018/8/6
 * @Time:9:32
 */
public class ObjUtil {

    /**
     * 获取对象下所有不为空的属性和值
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> checkfield(Object obj) {
        Map<String, Object> map = null;
        try {
            Class<?> objClass = obj.getClass();
            Field[] fields = objClass.getDeclaredFields();
            map = new HashMap<>();
            for (Field field : fields) {
                field.setAccessible(true);
                Object val = field.get(obj);
                if (val != null) {
                    map.put(field.getName(), val);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void initField(Object object) {
        try {
            Class<?> objectClass = object.getClass();
            Field[] fields = objectClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String type = field.getType().getSimpleName();
                if (field.get(object) == null) {
                    if (type.equals("String")) {
                        field.set(object, "");
                    } else if (type.equals("Integer")) {
                        field.set(object, new Integer(0));
                    } else if (type.equals("Long")) {
                        field.set(object, new Long(0));
                    } else if (type.equals("Char")) {
                        field.set(object, "");
                    } else if (type.equals("Date")) {
                        field.set(object, new Date());
                    } else if (type.equals("BigDecimal")) {
                        field.set(object, new BigDecimal(0));
                    } else if (type.equals("Double")) {
                        field.set(object, new Double(0));
                    } else if (type.equals("Byte")) {
                        field.set(object, new Byte("0"));
                    } else if (type.equals("Float")) {
                        field.set(object, new Float(0));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
