package jnpf.config;

import com.alibaba.fastjson.serializer.ValueFilter;
import jnpf.annotation.Sensitive;
import jnpf.enums.SensitiveTypeEnum;
import jnpf.util.DesensitizedUtils;

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

/**
 * 自定义浮点过滤器
 *
 * @author yanwenfu
 * @create 2020-11-12
 */
public class CustomValueFilter implements ValueFilter {

    /** 最小转换位数 */
    private static final int CHANGE_MIN_LEN = 15;

    @Override
    public Object process(Object object, String name, Object value) {

        if (null != value) {
            /*if (value instanceof BigDecimal) {
                return String.format("%.2f", ((BigDecimal) value).doubleValue());
            }*/
            if (value instanceof Long) {
                // long类型数值大于15位时转换为string类型返回
                if (String.valueOf(value).length() > CHANGE_MIN_LEN) {
                    return String.valueOf(value);
                }
            }
            if (value instanceof Date) {
                Date date = (Date) value;
                return date.getTime();
            }
            // 脱敏处理
            try {
                Field field = object.getClass().getDeclaredField(name);
                Sensitive sensitive;
                if (String.class != field.getType() || (sensitive = field.getAnnotation(Sensitive.class)) == null) {
                    return value;
                }
                String valueStr = value.toString();
                SensitiveTypeEnum sensitiveTypeEnum = sensitive.type();
                switch (sensitiveTypeEnum) {
                    case CUSTOMER:
                        return DesensitizedUtils.desValue(valueStr, sensitive.prefixNoMaskLen(), sensitive.suffixNoMaskLen(), sensitive.symbol());
                    case NAME:
                        return DesensitizedUtils.chineseName(valueStr);
                    case ID_NUM:
                        return DesensitizedUtils.idCardNum(valueStr);
                    case PHONE_NUM:
                        return DesensitizedUtils.mobilePhone(valueStr);
                    default:
                        throw new IllegalArgumentException("unknown sensitive type enum " + sensitiveTypeEnum);
                }
            } catch (NoSuchFieldException e) {
                return value;
            }
        }
        return value;
    }
}
