/*
 * @Author: Billy
 * @Date: 2020-09-20 01:12:40
 * @LastEditors: Billy
 * @LastEditTime: 2022-04-16 16:27:29
 * @Description: 工具函数库
 */

const crypto = require("crypto");

// function ramdomStrEng(length = 10) {
//     let s = '';
//     for (let i = 0; i < length; i++)
//         s += (Math.random() * 36 | 0).toString(36);
//     return s;
// }

/**
 * 生成uuid/guid
 * @see https://stackoverflow.com/questions/105034/how-to-create-guid-uuid
 * @returns {string} uuid 字符串
 */
function uuidv4() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == "x" ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

/**
 * 把字符串单向加密
 * @param {string} str 需要加密的字符串
 * @returns {string} 加密后的字符串
 */
function createHmac(str) {
    const secret = "qwertyuiop";
    return crypto.createHmac("sha256", secret).update(str).digest("hex");
}

/**
 * 生成一个随机的n位字符串(位数越长，越不可能重复)
 * @param {number} n 位数
 * @returns {string} 随机字符串
 */
function ramdomStr(n) {
    if (n <= 50) {
        let full = createHmac(String(Date.now()));
        return full.slice(0, n);
    } else {
        throw new Error("位数n不能大于50");
    }
}

module.exports = {
    uuidv4,
    createHmac,
    ramdomStr
};