package com.jeequan.jeepay.db.config.dynamic;

import cn.hutool.crypto.symmetric.AES;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/***
 * DB配置信息对象
 * 全部属性来自 DruidDataSource （Extends因初始化导致启动失败）
 * @author terrfly
 * @date 2022/3/8 10:37
 */
@Data
@Slf4j
public class DBProp {

    /**
     * 加密对象
     **/
    private static final AES aes = new AES(CS.DB_PASSWD_DECRYPT_KEY.getBytes());

    /**
     * 是否加密账号
     **/
    private Boolean encryptAccount;

    private String url;
    private String username;
    private String password;
    private String driverClassName;
    private String dbType;
    private Integer initialSize;
    private Integer minIdle;
    private Integer maxActive;
    private Integer maxWait;
    private Boolean testWhileIdle;
    private Boolean testOnBorrow;
    private Boolean testOnReturn;
    private Integer timeBetweenEvictionRunsMillis;
    private Integer minEvictableIdleTimeMillis;
    private String validationQuery;
    private Boolean poolPreparedStatements;
    private Integer maxPoolPreparedStatementPerConnectionSize;
    private String filters;
    private String connectionProperties;


    public String getUsername() {

        // 需要解密
        if (encryptAccount != null && encryptAccount) {

            try {
                return aes.decryptStr(username);
            } catch (Exception e) {
                log.error("数据库[账号]解密失败，请检查加密数据或加密因子是否正确！", e);
                throw new BizException("数据库[账号]解密失败，请检查加密数据或加密因子是否正确！");
            }
        }

        return username;
    }

    public String getPassword() {

        // 需要解密
        if (encryptAccount != null && encryptAccount) {

            try {
                return aes.decryptStr(password);
            } catch (Exception e) {
                log.error("数据库[密码]解密失败，请检查加密数据或加密因子是否正确！", e);
                throw new BizException("数据库[密码]解密失败，请检查加密数据或加密因子是否正确！");
            }
        }

        return password;
    }


    public static void main(String[] args) {

        String text = "root";
        try {
            System.out.println("加密结果： " + text + " ==> " + aes.encryptHex(text));
        } catch (Exception e) {
            System.out.println("加密结果： " + text + " ==> 失败");
        }

        String entryText = "1fc401e3949581c60fef3f62d539b434";
        try {
            System.out.println("解密结果： " + entryText + " ==> " + aes.decryptStr(entryText));
        } catch (Exception e) {
            System.out.println("解密结果： " + entryText + " ==> 失败");
        }

    }


}
