package com.chinaweal.aiccs.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description:
 * @Author: TiAmo-cc
 * @Email: 1049976610@qq.com
 * @Date: 2026/1/3 21:39
 */
public class BeanUtil {

    public static void copyBean(Object source, Object target) {
        Set<String> emptyAttribute = new HashSet();
        BeanWrapper sourceWrapper = new BeanWrapperImpl(source);
        PropertyDescriptor[] descriptors = sourceWrapper.getPropertyDescriptors();
        Arrays.stream(descriptors).forEach((descriptor) -> {
            Object value = sourceWrapper.getPropertyValue(descriptor.getName());
            if (emptyObject(value)) {
                emptyAttribute.add(descriptor.getName());
            }

        });
        if (emptyAttribute.size() != 0) {
            String[] result = new String[emptyAttribute.size()];
            String[] emptyProperties = (String[])emptyAttribute.toArray(result);
            BeanUtils.copyProperties(source, target, emptyProperties);
        } else {
            BeanUtils.copyProperties(source, target);
        }

    }

    private static boolean emptyObject(Object obj) {
        if (!(obj instanceof String)) {
            return obj == null;
        } else {
            String valueStr = String.valueOf(obj);
            return "null".equals(valueStr) || "".equals(valueStr);
        }
    }
}
