package com.thinkunion.park.service.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.*;

@Slf4j
public class BeanUtil {

    public static <T> T copyBean(Object source,Class<T> target){
        T t = null;
        try {
            t = target.getDeclaredConstructor().newInstance();
            if (Objects.isNull(source)){
                return t;
            }
            BeanUtils.copyProperties(source,t);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return t;
    }



    public static <T> List<T> copyList(List list, Class<T> target){
        ArrayList<T> result = new ArrayList<>();
        for (Object source : list) {
            T t = null;
            try {
                t = target.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            BeanUtils.copyProperties(source,t);
            result.add(t);
        }
        return result;
    }

    /**
     *
     * @param src
     * @param target
     */
    public static <T> T  copyPropertiesIgnoreNull(Object src, Object target,Class<T> reClass) {
        T t = null;
        try {
            t = reClass.getDeclaredConstructor().newInstance();
            if (Objects.isNull(src)){
                return t;
            }
            BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
            BeanUtils.copyProperties(target,t);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return t;
    }

    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
