export function debounce(fn: Function, delay = 200, immediate = false) {
    let timer: ReturnType<typeof setTimeout>;
    return function (...args: any) {
        const context = globalThis;
        let result: unknown;
        args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        if (immediate && !timer) {
            result = fn.apply(context, args);
        }
        timer = setTimeout(() => {
            result = fn.apply(context, args);
        }, delay);

        return result;
    };
}

export const phoneConvert = (number: string) => {
    if (!number) return "";
    let pat = /(\d{3})\d*(\d{3})/;
    return number.replace(pat, "$1****$2");
};

/**
 * @description  根据语言获取时区
 */
const language = ["pt-BR", "zh-CN", "en-US"];
function getLang(utc: string) {
    let reg = new RegExp(utc, "i");
    const i = language.findIndex((n, index) => {
        if (reg.test(n)) {
            return index;
        }
    });
    let n = i < 0 ? 0 : i;
    return language[n];
}
export const timeFormat = (time: number, lang = "en", delimiter?: undefined | string): string => {
    if (!time) return "";
    const len = (time + "").length;
    if (len === 10) {
        time = time * 1000;
    }
    lang = getLang(lang);

    if (delimiter) {
        return new Date(time).toLocaleString(lang).replaceAll("/", delimiter);
    }
    return new Date(time).toLocaleString(lang);
};

/**
 * @description 复制文本
 */
export let copyText = function (text: string) {
    if (navigator.clipboard) {
        copyText = (text: string) => {
            navigator.clipboard.writeText(text);
        };
    } else {
        copyText = (text) => {
            const input = document.createElement("input");
            input.setAttribute("value", text);
            document.body.appendChild(input);
            input.select();
            document.execCommand("copy");
            document.body.removeChild(input);
        };
    }
    copyText(text);
};

/**
 * @description 两个数值计算百分比
 */
export const percentage = (current: number, source: number) => {
    console.log(`🚀🚀🚀🚀🚀-> in index.ts on 80`, current, source);
    return (current * 100) / source;
};
