package com.vsu.fcounter.utils;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@interface ParamsName {
    String value();
}

public class BeanUtils {
    /**
     * @Method: toMap()
     * @author create by Tang
     * @date date 16/8/23 下午3:20
     * @Description: 把实体类转换成Map类
     */
    static public Map toMap(Object obj) {
        Class clazz = obj.getClass();
        Class superClass = clazz.getSuperclass();
        Field[] fields = clazz.getDeclaredFields();
        Field[] superFields = superClass.getDeclaredFields();
        if (fields == null || fields.length == 0 ){
            return Collections.EMPTY_MAP;
        }
        Map params = new HashMap<>();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.get(obj) != null){
                    ParamsName paramsName = field.getAnnotation(ParamsName.class);
                    String key;
                    if (paramsName == null){
                        key = field.getName();
                    }else {
                        key = paramsName.value();
                    }
                    if (field.get(obj) != null){
                        params.put(key , field.get(obj));
                    }else {
                        params.put(key, "null");
                    }
                }
            }
            for (Field superField : superFields){
                if (superField.get(obj) != null){
                    superField.setAccessible(true);
                    ParamsName superParamsName = superField.getAnnotation(ParamsName.class);
                    String superKey;
                    if (superParamsName == null){
                        superKey = superField.getName();
                    }else {
                        superKey = superParamsName.value();
                    }
                    if (superField.get(obj) != null){
                        params.put(superKey, superField.get(obj));
                    }else {
                        params.put(superKey, "null");
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return params;
    }
}