package com.izouma.jmrh.converter;

import cn.licoy.encryptbody.config.EncryptBodyConfig;
import cn.licoy.encryptbody.util.AESEncryptUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

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

@Converter
@Slf4j
public class EncryptConverter implements AttributeConverter<String, String> {

    @Value("${encrypt.body.aes-key}")
    private String key;

    @Value("${encrypt.enable}")
    private boolean enableEncrypt;

    @Override
    public String convertToDatabaseColumn(String s) {
        if (StringUtils.isNotBlank(s) && enableEncrypt) {
            try {
                return AESEncryptUtil.encrypt(s, key);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return s;
    }

    @Override
    public String convertToEntityAttribute(String s) {
        if (StringUtils.isNotBlank(s) && enableEncrypt) {
            try {
                return AESEncryptUtil.decrypt(s, key);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return s;
    }
}
