package com.njcn.common.utils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Description:
 * 接口文档访问地址：http://serverIP:port/swagger-ui.html
 * Date: 2022/10/21  9:32【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
public class NjcnBeanUtil {


    /**
     * beancopy
     * 大小写可以忽略
     * 下划线 _ 被忽略
     *
     * @param source
     * @param target
     * @param <T>
     * @return
     */
    public static <T> T copyPropertiesIgnoreCase(Object source, Object target) {
        Map<String, Field> sourceMap = CacheFieldMap.getFieldMap (source.getClass ( ));
        CacheFieldMap.getFieldMap (target.getClass ( )).values ( ).forEach ((it) -> {
            Field field = sourceMap.get (it.getName ( ).toLowerCase ( ).replace ("_", ""));
            if (field != null) {
                it.setAccessible (true);
                field.setAccessible (true);
                try {
                    //忽略null和空字符串
//                        if(field.get(source)!=null&& StringUtils.isBlank(field.get(source).toString()))
                    it.set (target, field.get (source));
                } catch (IllegalAccessException e) {
                    e.printStackTrace ( );
                }
            }
        });
        return (T) target;
    }

    private static class CacheFieldMap {
        private static Map<String, Map<String, Field>> cacheMap = new HashMap<> ( );

        private static Map<String, Field> getFieldMap(Class clazz) {
            Map<String, Field> result = cacheMap.get (clazz.getName ( ));
            if (result == null) {
                synchronized (CacheFieldMap.class) {
                    if (result == null) {
                        Map<String, Field> fieldMap = new HashMap<> ( );
                        for (Field field : getAllFields (clazz)) {
                            fieldMap.put (field.getName ( ).toLowerCase ( ).replace ("_", ""), field);
                        }
                        cacheMap.put (clazz.getName ( ), fieldMap);
                        result = cacheMap.get (clazz.getName ( ));
                    }
                }
            }
            return result;
        }
    }

    /**
     * 获取本类及其父类的字段属性
     *
     * @param clazz 当前类对象
     * @return 字段数组
     */
    public static Field[] getAllFields(Class<?> clazz) {
        List<Field> fieldList = new ArrayList<> ( );
        while (clazz != null) {
            fieldList.addAll (new ArrayList<> (Arrays.asList (clazz.getDeclaredFields ( ))));
            clazz = clazz.getSuperclass ( );
        }
        Field[] fields = new Field[fieldList.size ( )];
        return fieldList.toArray (fields);
    }


}
