import CryptoJS from 'crypto-js'

const key = 'b6967ee87b86d85a'

export function encrypt_aes(text: any, iv: string) {
    let plaintText = text
    if (typeof text == 'object') {
        plaintText = JSON.stringify(plaintText)
    }
    iv = CryptoJS.enc.Utf8.parse(iv)
    let pkey = CryptoJS.enc.Utf8.parse(key)
    plaintText = CryptoJS.enc.Utf8.parse(plaintText)
    const encryptedData = CryptoJS.AES.encrypt(plaintText, pkey, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding,
    })

    // // 需要读取encryptedData上的ciphertext.toString()才能拿到跟Java一样的密文

    const encryptedStr = encryptedData.ciphertext.toString(CryptoJS.enc.Base64)

    return encryptedStr
}

export function decrypt_aes(word: string, iv: string) {
    iv = CryptoJS.enc.Utf8.parse(iv)
    let pkey = CryptoJS.enc.Utf8.parse(key)
    const decrypt = CryptoJS.AES.decrypt(word, pkey, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding,
    })

    return decrypt.toString(CryptoJS.enc.Utf8)
}

export function generateRandomNumber(length: number) {
    // 生成一个指定长度的随机数字字符串
    let result = ''
    const characters = '0123456789'
    const charactersLength = characters.length
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength))
    }
    return result
}
