package com.huigou.topsun.util;

import com.huigou.topsun.proofing.domain.vo.WorkInstructionVo;
import com.huigou.topsun.proofing.domain.workInstruction.model.WorkInstructionBaseInfo;
import com.huigou.topsun.proofing.domain.workInstruction.model.WorkInstructionMaterialInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.FatalBeanException;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;



public class MyBaseUtil {

    /**
     * 合并多个对象到目标对象中。
     *
     * @param target  目标对象，属性将被复制到该对象中
     * @param sources 源对象数组，从这些对象中复制属性到目标对象
     */
    public static void mergeObjects(Object target, Object... sources) {
        for (Object source : sources) {
            if (source != null) {
                BeanUtils.copyProperties(source, target, getNullAndEmptyPropertyNames(source));
            }
        }
    }

    /**
     * 获取源对象中为空的属性名数组。
     * @param source 源对象，用于获取属性名和属性值
     * @return 空属性名数组
     */
    private static String[] getNullAndEmptyPropertyNames(Object source) {
        final PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(source.getClass());
        String[] nullAndEmptyPropertyNames = new String[propertyDescriptors.length];
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor pd = propertyDescriptors[i];
            Method readMethod = pd.getReadMethod();
            try {
                if (readMethod != null) {
                    Object value = readMethod.invoke(source);
                    if (value == null || "".equals(value)) {
                        nullAndEmptyPropertyNames[i] = pd.getName();
                    }
                }
            } catch (Exception ex) {
                throw new FatalBeanException("Could not copy properties from source to target", ex);
            }
        }
        return nullAndEmptyPropertyNames;
    }

    public static void main(String[] args) {


        WorkInstructionVo workInstructionVo = new WorkInstructionVo();
        workInstructionVo.setApprovalStatus("ss");
        WorkInstructionMaterialInfo workInstructionMaterialInfo = new WorkInstructionMaterialInfo();
        workInstructionMaterialInfo.setBomNo("hhhh");
        WorkInstructionBaseInfo workInstructionBaseInfo = new WorkInstructionBaseInfo();
        workInstructionBaseInfo.setBrand("wwwwww");

        MyBaseUtil.mergeObjects(workInstructionVo, workInstructionMaterialInfo, workInstructionBaseInfo,null);

        System.out.println("");

    }
}

