package com.jeeplus.test.jobPosion.utils;

import com.jeeplus.test.jobPosion.annotation.ForUpdate;

import java.lang.reflect.Field;
import java.util.Objects;

public class BeanUtils {
    /**
     * 获取变更内容
     * @param newBean 更改后的Bean
     * @param oldBean 更改前的Bean
     * @param <T>
     * @return
     */
    public static <T> String getChangedFields(T newBean, T oldBean){
        Field[] fields = newBean.getClass().getDeclaredFields();
        StringBuilder builder = new StringBuilder();
        for(Field field : fields) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(ForUpdate.class)) {
                try {
                    Object newValue = field.get(newBean);
                    Object oldValue = field.get(oldBean);
                    if(!Objects.equals(newValue, oldValue)) {
                        builder.append(field.getAnnotation(ForUpdate.class).fieldName()); //获取字段名称
                        builder.append(": 【更改前：");
                        builder.append(oldValue);
                        builder.append(", 更改后：");
                        builder.append(newValue);
                        builder.append("】\n");
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
        return builder.toString();
    }
}
