
import * as crypto from 'crypto';
import { getInterfaceByInterfaceName } from '../data/interface/cronJob';
import { BizError } from '../util/bizError';

/**
 * 加密
 * @param text 要加密的明文
 * @param key 密码
 * @param iv 偏移量
 * key和iv都应为16字节长
 * @returns 
 */
export function encrypt(text, key, iv) {
    let cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    let encrypted = cipher.update(text, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    return encrypted;
}



/**
 * 解密
 * @param encrypted 要解密的密文
 * @param key 密码
 * @param iv 偏移量
 * key和iv都应为16字节长
 * @returns 
 */
export function decrypt(encrypted, key, iv) {
    let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    let decrypted = decipher.update(encrypted, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}


export async function getToken() {
    let appId = "sec_dt_platform";
    let plaintext = appId + new Date().valueOf();
    let key = 'b81d56b0071dc916';
    let iv = 'b81d56b0071dc916';
    let signature = encrypt(plaintext, key, iv);
    let data = await getInterfaceByInterfaceName("获取token接口", {appId, signature});
    let token = "";
    if (!data) throw new BizError("获取token失败");
    let {success, message, code, timestamp, result, requestId} = data;
    if (success) {
        token = result;
    } else {
        throw new BizError(`${code} ${message} 获取token失败`)
    }

    return token;
}