package com.yc.ship.module.trade.utils;

import com.yc.ship.module.trade.framework.annotation.ForUpdate;

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

/**
 * @author ：qsl
 * &#064;description：TODO
 * &#064;date  ：2026/1/12 16:10
 **/
public class BeanUtils {

    /**
     * 获取变更内容
     *
     * @param newBean 更改前的Bean
     * @param oldBean 更改后的Bean
     * @param <T>
     * @return
     */
    public static <T> String getChangedFields(T newBean, T oldBean) {
        if (newBean == null || oldBean == null) {
            return "";
        }
        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(newValue instanceof BigDecimal && oldValue instanceof BigDecimal) {
                        if(((BigDecimal) newValue).compareTo((BigDecimal) oldValue) == 0) {
                            continue;
                        }
                    }
                    newValue = newValue == null ? "" : newValue;
                    oldValue = oldValue == null ? "" : oldValue;
                    if (!Objects.equals(newValue, oldValue)) {
                        //获取字段名称
                        builder.append(field.getAnnotation(ForUpdate.class).fieldName());
                        builder.append(": 【更改前：");
                        builder.append(newValue);
                        builder.append(", 更改后：");
                        builder.append(oldValue);
                        builder.append("】\n");
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
        return builder.toString();
    }
}