package com.changhu.support.fastjson2.filter;

import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson2.filter.ValueFilter;
import com.changhu.common.annotation.Desensitized;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * author: luozhun
 * desc: 数据加敏过滤器
 * createTime: 2023/9/13 16:44
 */
@Slf4j
public class DesensitizedFilter implements ValueFilter {

    public static final DesensitizedFilter instance = new DesensitizedFilter();

    private final Map<String, DesensitizedUtil.DesensitizedType> cache = new ConcurrentHashMap<>();

    private DesensitizedFilter() {
    }

    @Override
    public Object apply(Object object, String name, Object value) {
        //只针对string类型生效
        if (value instanceof String strValue && !strValue.isEmpty()) {
            try {
                String path = object.getClass().getName() + "$$" + name;
                //先看是否有缓存
                if (cache.containsKey(path)) {
                    return DesensitizedUtil.desensitized(strValue, cache.get(path));
                }
                Class<?> aClass = object.getClass();
                Field declaredField = aClass.getDeclaredField(name);
                Desensitized annotation = declaredField.getAnnotation(Desensitized.class);
                if (annotation == null) {
                    return value;
                }
                //加入缓存
                cache.put(path, annotation.value());
                return DesensitizedUtil.desensitized(strValue, annotation.value());
            } catch (NoSuchFieldException e) {
                return value;
            } catch (SecurityException e) {
                log.error("字段：{} 安全异常: {}", name, e.getMessage());
                return null;
            } catch (Exception e) {
                log.error("数据脱敏失败:{}", e.getMessage());
                return null;
            }
        } else {
            return value;
        }
    }

}