package com.zehong.common.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author geng
 * 上报市局实体类组装工具类
 */
public class GovernmentDataCopyUtil {

    /**
     * 拷贝为市局实体
     * @param source 源
     * @param target 目标对象
     */
    public static void copyToGovernData(Object source,Object target) throws IllegalAccessException {
        Field[] fields = source.getClass().getDeclaredFields();
        Map<String,Field> targetMap = fieldsToMap(target.getClass().getDeclaredFields());
        for(Field field : fields){
            field.setAccessible(true);
            String name = field.getName();
            String targetName = Character.toLowerCase(name.charAt(1)) + name.substring(2);
            if(targetMap.containsKey(targetName)){
                Object value = field.get(source);
                if(null != value){
                    targetMap.get(targetName).set(target,value);
                }
            }
        }
    }

    /**
     * 拷贝为本地实体
     * @param source 源
     * @param target 目标对象
     */
    public static void copyToLocalData(Object source,Object target) throws IllegalAccessException {
        Field[] fields = source.getClass().getDeclaredFields();
        Map<String,Field> targetMap = fieldsToMap(target.getClass().getDeclaredFields());
        for(Field field : fields){
            field.setAccessible(true);
            String name = field.getName();
            String targetName = "f" + Character.toLowerCase(name.charAt(0)) + name.substring(1);
            if(targetMap.containsKey(targetName)){
                Object value = field.get(source);
                if(null != value){
                    targetMap.get(targetName).set(target,value);
                }
            }
        }
    }

    /**
     * field[]数组转map
     * @param fields  属性数组
     * @return map
     */
    private static Map<String, Field> fieldsToMap(Field[] fields){
        Map<String, Field> hashMap = new HashMap<>();
        for (Field field : fields) {
            //打开私有访问
            field.setAccessible(true);
            String name = field.getName();
            hashMap.put(name, field);
        }
        return hashMap;
    }
}
