package com.ltgk.common.config.desensitive;

import com.alibaba.fastjson.serializer.ValueFilter;

import java.lang.reflect.Field;

/**
 * 脱敏数据转换过滤器
 */
public class DesensitizeValueFilter implements ValueFilter {

    @Override
    public Object process(Object object, String name, Object value) {
        try {
            Field field = object.getClass().getDeclaredField(name);
            Desensitive desensitive = field.getAnnotation(Desensitive.class);
            if (desensitive == null) {
                return value;
            }
            if (value instanceof Long) {
                return String.valueOf(DesensitizedUtil.userId());
            }
            if (!(value instanceof String) || ((String) value).length() == 0) {
                return value;
            }
            String valueStr = String.valueOf(value);
            DesensitizedType strategy = desensitive.strategy();
            switch (strategy) {
                case CHINESE_NAME:
                    return DesensitizedUtil.chineseName(valueStr);
                case ID_CARD:
                    return DesensitizedUtil.idCardNum(valueStr, 6, 2);
                case FIXED_PHONE:
                    return DesensitizedUtil.fixedPhone(valueStr);
                case MOBILE_PHONE:
                    return DesensitizedUtil.mobilePhone(valueStr);
                case ADDRESS:
                    return DesensitizedUtil.address(valueStr, 8);
                case EMAIL:
                    return DesensitizedUtil.email(valueStr);
                case PASSWORD:
                    return DesensitizedUtil.password(valueStr);
                case CAR_LICENSE:
                    return DesensitizedUtil.carLicense(valueStr);
                case BANK_CARD:
                    return DesensitizedUtil.bankCard(valueStr);
                case NONE:
                    return value;
                default:
            }
        } catch (NoSuchFieldException e) {
            return value;
        }
        return value;
    }
}