package com.artfess.base.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对象处理
 *
 * @Author min.wu
 * @Date Created in 2022-02-23 10:15
 */
@Slf4j
public class DmpBeanUtil {
    /**
     * 复制bean的属性
     *
     * @param source 源 要复制的对象
     * @param target 目标 复制到此对象
     */
    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }

    /**
     * 复制对象
     *
     * @param source 源 要复制的对象
     * @param target 目标 复制到此对象
     * @param <T>
     * @return
     */
    public static <T> T copy(Object source, Class<T> target) {
        try {
            T newInstance = target.newInstance();
            BeanUtils.copyProperties(source, newInstance);
            return newInstance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 复制list
     *
     * @param source
     * @param target
     * @param <T>
     * @param <K>
     * @return
     */
    public static <T, K> List<K> copyList(List<T> source, Class<K> target) {

        if (null == source || source.isEmpty()) {
            return new ArrayList<>();
        }
        return source.stream().map(e -> copy(e, target)).collect(Collectors.toList());
    }

    /**
     * 设置公共字段空值
     * @param source
     */
    public static <T> void setPropertiesNull(Object source,Class<T> baseEntity) {
        Class<?> aClass = source.getClass();
        Arrays.stream(baseEntity.getDeclaredFields())
                .map(Field::getName)
                .collect(Collectors.toList()).forEach(o -> {
            Field field = null;
            try {
                field = aClass.getDeclaredField(o);
                Object object = aClass.newInstance();
                field.setAccessible(true);
                field.set(object,null);
            } catch (NoSuchFieldException e) {
                log.info("处理异常:{}",e.getMessage());
            } catch (IllegalAccessException e) {
                log.info("处理异常:{}",e.getMessage());
            } catch (InstantiationException e) {
                log.info("处理异常:{}",e.getMessage());
            }
        });

    }
}
