import timerUtil, { TimeoutTimerNames } from '@/utils/timer/timerUtil';
import moment, { DurationInputArg1, Moment, unitOfTime } from "moment";

/**
 * 获取number类型时间戳
 * @returns
 */
export function getTimeValue(): number {
    return moment().valueOf()
}

type Time = string | Moment | Date
/**
 * 获取两个时间范围内的所有时间
 * @param val1 时间1
 * @param val2 时间2
 * @param type 时间格式化类型
 * @param unit 时间单位
 * @param amount 时间区间间隔数
 * @returns string[]类型
 */
export function getRangeTime(val1: Time, val2: Time, type = 'YYYYMMDD', unit: unitOfTime.DurationConstructor = 'd', amount: DurationInputArg1 = 1): string[] {
    const fn = (val: Moment) => val.format(type);
    // 处理开始时间和结束时间
    let startTime = moment(val1);
    let endTime = moment(val2);

    const result: string[] = [];
    const isSame = () => startTime.isSame(endTime, unit);

    if (isSame()) {
        return [fn(startTime), fn(startTime)];
    } else {
        if (startTime.isAfter(endTime)) {
            [startTime, endTime] = [endTime, startTime]
        }
        while (!isSame()) {
            result.push(fn(startTime));
            startTime = startTime.add(amount, unit);
        }
        result.push(fn(endTime));
        return result;
    }
}

/**
 * ------------------------------------------------------------------待优化后期废除
 * 防抖(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);
    })();
}

/**
 * 时间排序
 * @param arr
 * @param key
 * @param isUp true: 升序，false: 倒序
 * @returns
 */
export function sortTime<T extends object>(arr: T[], key: keyof T, isUp = true) {
    const result = arr.sort((a, b) => {
        const time1 = new Date((a[key] as unknown) as string).getTime();
        const time2 = new Date((b[key] as unknown) as string).getTime();
        return isUp ? time1 - time2 : time2 - time1;
    });
    return result;
}

/**
 * 函数防抖(等待触发)
 * @param callback 回调函数
 * @param delay 延迟毫秒数，默认100毫秒
 * @returns 
 */
export function debounce<T extends unknown[]>(callback: (...param: T) => void, delay = 100) {
    let timer = 0;
    return function (...args: T) {
        clearTimeout(timer);
        timer = window.setTimeout(() => {
            callback(...args);
        }, delay);
    }
}

/**
 * 函数节流(间隔触发)
 * @param callback 回调函数
 * @param delay 延迟毫秒数，默认100毫秒
 * @returns 
 */
export function throttle<T extends unknown[]>(callback: (...param: T) => void, delay = 100) {
    let timer = 0;
    return function (...args: T) {
        if (timer) return;
        timer = window.setTimeout(() => {
            timer = 0;
            callback(...args);
        }, delay);
    }
}