package cn.com.ty.lift.business.common;

import cn.com.ty.lift.common.constants.FieldName;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * @author bieao
 * @date 2020/3/10
 * @description BeanUtil
 */
@Component
@Slf4j
public class BeanUtils {

    /**
     * @param oldEntry 原有实体
     * @param newEntry 修改后实体
     * @return
     * @description 属性比较
     * @date 2020/4/28 10:16 上午
     */
    public Map<String, String> compareAttribute(Object oldEntry, Object newEntry) throws NoSuchFieldException {
        Map<String, Object> oldResult = BeanUtil.beanToMap(oldEntry);
        oldResult.remove("createDate");
        oldResult.remove("updateDate");
        oldResult.remove("creatorId");
        oldResult.remove("updateId");
        Map<String, Object> newResult = BeanUtil.beanToMap(newEntry);
        newResult.remove("createDate");
        newResult.remove("updateDate");
        newResult.remove("creatorId");
        newResult.remove("updateId");
        Map<String, String> resultMap = new HashMap<>();
        StringBuilder beforeBuilder = new StringBuilder("修改前属性：");
        StringBuilder afterBuilder = new StringBuilder("修改后属性：");
        for (Map.Entry<String, Object> entry : oldResult.entrySet()) {
            Object oldValue = oldResult.get(entry.getKey());
            Object newValue = newResult.get(entry.getKey());
            if (Objects.isNull(newValue)) continue;
            Class<?> cls = newEntry.getClass();
            Field field = cls.getDeclaredField(entry.getKey());
            if (!field.isAnnotationPresent(FieldName.class)) continue;
            FieldName fieldName = field.getDeclaredAnnotation(FieldName.class);
            boolean result = ObjectUtil.notEqual(oldValue, newValue);
            if (result) {
                if (ObjectUtil.isEmpty(oldValue)) {
                    beforeBuilder.append(fieldName.name()).append("：").append("--");
                } else {
                    beforeBuilder.append(fieldName.name()).append("：").append(oldValue.toString());
                }
                afterBuilder.append(fieldName.name()).append(newValue.toString());
                resultMap.put("before", beforeBuilder.toString());
                resultMap.put("after", afterBuilder.toString());
            }
        }
        return resultMap;
    }
}
