package cn.quantgroup.xyqb.entity.converter;

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

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

/**
 * 手机号字段加解密转换器
 * <b>此处只对有效手机号处理</b>
 *
 * @author killer
 * @date 2022年01月04日
 **/
@Slf4j
@Converter
public class PhoneEncryptConverter implements AttributeConverter<String, String> {

    @Override
    public String convertToDatabaseColumn(String entityAttribute) {
        /* 非手机号原样保存 */
        if (!ValidationUtil.validatePhoneNo(entityAttribute)) {
            return entityAttribute;
        }
        /* 加密 */
        AESEncryption aesEncryption = ApplicationContextHolder.getBean(AESEncryption.class);
        return aesEncryption.encryptBase64(entityAttribute);
    }

    @Override
    public String convertToEntityAttribute(String databaseColumn) {
        /* 明文手机号或者空原样返回 */
        if (ValidationUtil.validatePhoneNo(databaseColumn) || StringUtils.isBlank(databaseColumn)) {
            return databaseColumn;
        }
        /* 解密 */
        AESEncryption aesEncryption = ApplicationContextHolder.getBean(AESEncryption.class);
        try {
            return aesEncryption.decryptBase64(databaseColumn);
        } catch (IllegalArgumentException e) {
            log.warn("手机号解密失败, 数据存在问题, 原样返回数据:{}", databaseColumn);
        }
        return databaseColumn;
    }
}
