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;
    }
}

/**
 * 时间排序
 * @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;
}