package cn.quantgroup.xyqb.entity.converter;

import cn.quantgroup.security.AESEncryption;
import cn.quantgroup.security.CipherUtil;
import cn.quantgroup.xyqb.util.ApplicationContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * 通用字段加解密转换器
 *
 **/
@Slf4j
@Converter
public class EncryptConverter implements AttributeConverter<String, String> {

    @Override
    public String convertToDatabaseColumn(String entityAttribute) {

        if (StringUtils.isBlank(entityAttribute)) {
            return entityAttribute;
        }

        /* 加密 */
        AESEncryption aesEncryption = ApplicationContextHolder.getBean(AESEncryption.class);
        return aesEncryption.encryptBase64(entityAttribute);
    }

    @Override
    public String convertToEntityAttribute(String databaseColumn) {

        if (StringUtils.isBlank(databaseColumn)) {
            return databaseColumn;
        }

        /* 解密(兼容数据库字段未执行全部加密前的查询) */
        AESEncryption aesEncryption = ApplicationContextHolder.getBean(AESEncryption.class);
        if (CipherUtil.isCipherBase64(databaseColumn)) {
            return aesEncryption.decryptBase64(databaseColumn);
        }
        return databaseColumn;
    }
}
