package com.muchinfo.mtp3common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.muchinfo.mtp3common.EncryptAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class SensitiveEncryptUtil {
    private static final Logger logger = LoggerFactory.getLogger(SensitiveEncryptUtil.class);
    public static Object sensitiveEncrypt(Object model, String key){
        try{
            Field[] fields = model.getClass().getDeclaredFields();

            for (Field field : fields) {
                if (field.isAnnotationPresent(EncryptAnnotation.class)) {
                    String name = field.getName();
                    String letter = name.substring(0, 1).toUpperCase() + name.substring(1);
                    //得到方法名getXxxx
                    String getter = "get" + letter;
                    Method method = model.getClass().getMethod(getter);
                    String value = (String) method.invoke(model);
                    if (value != null && StringUtils.isNotBlank(value.toString())) {
                        method = model.getClass().getMethod("set" + letter, String.class);
                        String v_ = EncryptionUtils.encryptByAES(value);
                        method.invoke(model, v_);
                    }
                }
            }
            return model;
        }catch (Exception e){
            logger.error("加入敏感词权限失败，失败信息："+model);
            return model;
        }
    }
}
