package com.yifu.cloud.plus.v1.yifu.common.core.util.equator;

import com.github.dadiyang.equator.Equator;
import com.github.dadiyang.equator.FieldInfo;
import com.github.dadiyang.equator.GetterBaseEquator;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: master
 * @description: hr字段比较器 SecondVal空字段忽略
 * @author: pwang
 * @create: 2020-06-24 13:14
 **/
public class HrEquator extends GetterBaseEquator {
    @Override
    protected boolean isFieldEquals(FieldInfo fieldInfo) {
        //空字段空串不更新忽略（单独处理的地方记录）
        if(null == fieldInfo.getSecondVal() || (fieldInfo.getSecondVal() instanceof String && "" == ((String) fieldInfo.getSecondVal()).trim())){
            return true;
        }
        if (fieldInfo.getFirstVal() instanceof BigDecimal) {
            BigDecimal first = (BigDecimal) fieldInfo.getFirstVal();
            BigDecimal second = (BigDecimal) fieldInfo.getSecondVal();

            if (null != second && first.compareTo(second) == CommonConstants.dingleDigitIntArray[0]) {
                return true;
            }else{
                return false;
            }
        }
        return super.isFieldEquals(fieldInfo);
    }
    /**
     * 比较对象的差异，返回差异的属性名
     * @Author huyc
     * @Date 2022-06-22 11:32
     * @param oldInfo
     * @param newInfo
     * @return
     **/
    public static String comparisonValue(Object oldInfo, Object newInfo){
        StringBuffer sb = new StringBuffer(CommonConstants.EMPTY_STRING);
        Equator equator = new HrEquator();
        // 获取不同的属性
        List<FieldInfo> diff = equator.getDiffFields(oldInfo, newInfo);
		Map<String, Integer> curMap = new HashMap<>();
		String fieldName;
		boolean newChange = false;
        if (!Common.isEmpty(diff)) {
            for(FieldInfo field:diff){
				fieldName = field.getFieldName();
				curMap.put(fieldName, 1);
				if (!"updateTime".equals(fieldName) && !"updateBy".equals(fieldName)) {
					newChange = true;
					sb.append(field.getFieldName()).append(",");
				}
            }
        }
		// 从有值变为空，也要记录变更日志
		List<FieldInfo> diff2 = equator.getDiffFields(newInfo, oldInfo);
        if (!Common.isEmpty(diff2)) {
            for(FieldInfo field:diff2){
				fieldName = field.getFieldName();
				if (curMap.get(fieldName) == null && !"updateTime".equals(field.getFieldName()) && !"updateBy".equals(field.getFieldName())) {
					newChange = true;
					sb.append(field.getFieldName()).append(",");
				}
            }
        }
		if (newChange) {
			sb.deleteCharAt(sb.length()-1);
		}
		return sb.toString();
    }

}
