package com.jiayue.ipfcst.client.utils;

import io.swagger.annotations.ApiModelProperty;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * EntityUtil
 *
 * @author L.ym
 * @date 2020-08-28
 **/
@UtilityClass
public class EntityUtil {

    /**
     * 比较两个实体的属性值
     *
     * @param oldBean
     * @param newBean
     * @param ignoreList
     * @return java.util.List
     * @author L.ym
     * @date 2020/8/28
     **/
    @SneakyThrows
    public <T> List<String[]> checkDifference(Object oldBean, Object newBean, List<String> ignoreList) {
        T pojo1 = (T) oldBean;
        T pojo2 = (T) newBean;
        Class clazz = pojo1.getClass();
        Field[] fields = pojo1.getClass().getDeclaredFields();
        List<String[]> result = new ArrayList<>();

        for (Field field : fields) {
            // 如果当前属性选择忽略比较，跳到下一次循环
            if (ignoreList != null && ignoreList.contains(field.getName())) {
                continue;
            }
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            Method getMethod = pd.getReadMethod();
            Object o1 = getMethod.invoke(pojo1);
            Object o2 = getMethod.invoke(pojo2);
            //现值等于null不比对（等于null不更新）
            if (o2 == null) {
                o2 = "";
            }
            if (o1 == null || !o1.toString().equals(o2.toString())) {
                String[] strArray = new String[4];
                ApiModelProperty fieldName = field.getAnnotation(ApiModelProperty.class);
                //字段名
                strArray[0] = field.getName();
                //中文（如果为空就展示字段名)
                strArray[1] = fieldName == null ? field.getName() : fieldName.value();
                //原值
                strArray[2] = o1 == null ? "null" : o1.toString();
                //现值
                strArray[3] = o2.toString();
                result.add(strArray);
            }
        }
        return result;
    }

    /**
     * 比较两个实体的属性值
     *
     * @param oldBean
     * @param newBean
     * @return java.util.List
     * @author L.ym
     * @date 2020/8/28
     **/
    public List<String[]> checkDifference(Object oldBean, Object newBean) {
        return checkDifference(oldBean, newBean, null);
    }
}
