/* eslint-disable  @typescript-eslint/no-explicit-any */

// 深拷贝
export function deepMerge(...objs: any[]): any {
    const result = Object.create(null)
    objs.forEach((obj) => {
        if (obj) {
            Object.keys(obj).forEach((key) => {
                const val = obj[key]
                if (isPlainObject(val)) {
                    // 递归
                    if (isPlainObject(result[key])) {
                        result[key] = deepMerge(result[key], val)
                    } else {
                        result[key] = deepMerge(val)
                    }
                } else {
                    result[key] = val
                }
            })
        }
    })
    return result
}

export const isPlainObject = (val: any) =>
    !!val && typeof val === 'object' && val.constructor === Object

//防抖
// fn 要执行的函数
// delay 执行函数
export const debounce = <T extends (...args: any[]) => ReturnType<T>>(
    callback: T,
    timeout: number
): ((...args: Parameters<T>) => void) => {
    let timer: ReturnType<typeof setTimeout>

    return (...args: Parameters<T>) => {
        clearTimeout(timer)
        timer = setTimeout(() => {
            callback(...args)
        }, timeout)
    }
}

//封装节流
// fn 要执行的函数
// delay 执行函数
export const throttle = <T extends (...args: any[]) => ReturnType<T>>(
    callback: T,
    timeout: number
): ((...args: Parameters<T>) => void) => {
    let valid = true
    let timer: ReturnType<typeof setTimeout>

    return (...args: Parameters<T>) => {
        if (!valid) {
            return false
        }
        valid = false

        clearTimeout(timer)
        timer = setTimeout(() => {
            callback(...args)
            valid = true
        }, timeout)
    }
}

export const getImg = (imgUrl:string) => {
    return new URL(imgUrl, import.meta.url).href;
}