import timerUtil, { TimeoutTimerNames } from '@/utils/timer/timerUtil';
/**
 * 防抖(debounce)
 * @param fn 需要防抖的函数
 * @param wait 毫秒，防抖期限值
 * @returns
 */
export function debounce(fn: () => void, wait: number, timer: keyof TimeoutTimerNames = 'debounce'): void {
    return (function () {
        timerUtil.clearTimeout(timer);
        timerUtil.setTimeout(fn, wait, timer);
    })();
}

/**
 * 生成UUID
 */
export function getUUID(): string {
    const len = 32; // 32长度
    let radix = 16; // 16进制
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    const uuid = [];
    radix = radix || chars.length;
    if (len) {
        for (let i = 0; i < len; i++) {
            uuid[i] = chars[0 | (Math.random() * radix)];
        }
    } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (let j = 0; j < 36; j++) {
            if (!uuid[j]) {
                r = 0 | (Math.random() * 16);
                uuid[j] = chars[j === 19 ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}

/**
 * 更换数字单位
 * @param value
 * @param decimals
 * @returns
 */
export function changeUnit(value: number, decimals = 3): string {
    let base = 1000;
    const newValue = ['', '', ''];
    let num = 3;
    while (value / base >= 1) {
        base *= 10;
        num += 1;
    }
    if (num <= 4) {
        newValue[1] = '千';
        newValue[0] = parseInt((value / 1000).toFixed(decimals)) + '';
    } else if (num <= 8) {
        // 万
        const text1 = parseInt((num - 4).toFixed(decimals)) / 3 > 1 ? '千万' : '万';
        const fm = '万' === text1 ? 10000 : 10000000;
        newValue[1] = text1;
        newValue[0] = value / fm + '';
    } else if (num <= 16) {
        // 亿
        let text1 = (num - 8) / 3 > 1 ? '千亿' : '亿';
        text1 = (num - 8) / 4 > 1 ? '万亿' : text1;
        text1 = (num - 8) / 7 > 1 ? '千万亿' : text1;
        let fm = 1;
        if ('亿' === text1) {
            fm = 100000000;
        } else if ('千亿' === text1) {
            fm = 100000000000;
        } else if ('万亿' === text1) {
            fm = 1000000000000;
        } else if ('千万亿' === text1) {
            fm = 1000000000000000;
        }
        newValue[1] = text1;
        newValue[0] = (value / fm).toFixed(decimals) + '';
    }
    if (value < 1000) {
        newValue[1] = '';
        newValue[0] = value + '';
    }
    return newValue.join('');
}
