/**
 * 通用格式化工具函数
 */

const pad = (n: number) => (n < 10 ? `0${n}` : String(n));

/**
 * 格式化日期时间，模板支持 YYYY/MM/DD HH:mm:ss
 */
export const formatTime = (
    time: string | number | Date | undefined | null,
    template = 'YYYY/MM/DD HH:mm',
): string => {
    if (!time) return '';
    let d: Date;
    if (typeof time === 'string') {
        const fixed = time.includes('T') ? time : time.replace(/-/g, '/');
        d = new Date(fixed);
    } else {
        d = new Date(time);
    }
    if (isNaN(d.getTime())) return '';

    return template
        .replace('YYYY', String(d.getFullYear()))
        .replace('MM', pad(d.getMonth() + 1))
        .replace('DD', pad(d.getDate()))
        .replace('HH', pad(d.getHours()))
        .replace('mm', pad(d.getMinutes()))
        .replace('ss', pad(d.getSeconds()));
};

/**
 * 格式化耗时（毫秒）为 “1时2分3秒”
 */
export const formatCostTime = (ms: number): string => {
    const total = Math.floor((Number(ms) || 0) / 1000);
    const h = Math.floor(total / 3600);
    const m = Math.floor((total % 3600) / 60);
    const s = total % 60;
    if (h > 0) return `${h}时${m}分${s}秒`;
    if (m > 0) return `${m}分${s}秒`;
    return `${s}秒`;
};

/**
 * 格式化时长（秒）为 mm:ss / HH:mm:ss
 */
export const formatDuration = (sec: number): string => {
    const total = Math.max(0, Number(sec) || 0);
    const h = Math.floor(total / 3600);
    const m = Math.floor((total % 3600) / 60);
    const s = total % 60;
    if (h > 0) return `${h}:${pad(m)}:${pad(s)}`;
    return `${pad(m)}:${pad(s)}`;
};

/**
 * 简单延迟 promise
 */
export const sleep = (ms: number) =>
    new Promise<void>((resolve) => {
        const t = setTimeout(() => {
            resolve();
            clearTimeout(t);
        }, ms);
    });

/**
 * 简单 toast 包装
 */
export const showToast = (title: string, icon: 'none' | 'success' | 'error' | 'loading' = 'none') => {
    uni.showToast({ title, icon, duration: 2000 });
};
