/**
 * 兼容多格式的时间格式化工具
 * 统一输出格式：YYYY-MM-DD HH:mm:ss
 */

export function formatDateTimeCompat(input) {
  if (input === null || input === undefined || input === '') return '';
  let d;
  if (typeof input === 'number') {
    d = new Date(input);
  } else if (input instanceof Date) {
    d = input;
  } else if (typeof input === 'string') {
    const s = input.trim();
    // 1) 完整 ISO / yyyy-MM-dd HH:mm:ss
    // 先把中间空格替换成 'T'，再统一成能被 Date 解析的格式
    const isoLike = s.replace(' ', 'T');
    d = new Date(isoLike);
    // 2) 简写格式如 "1/15 00:45" 或 "01/15 00:45:12"
    if (isNaN(d.getTime())) {
      const m = s.match(/^(\d{1,2})[\/-](\d{1,2})\s+(\d{1,2}):(\d{2})(?::(\d{2}))?$/);
      if (m) {
        const now = new Date();
        const year = now.getFullYear();
        const month = Number(m[1]) - 1;
        const day = Number(m[2]);
        const hh = Number(m[3]);
        const mm = Number(m[4]);
        const ss = m[5] ? Number(m[5]) : 0;
        d = new Date(year, month, day, hh, mm, ss);
      }
    }
    // 3) 兜底：把 '-' 换成 '/' 以兼容 iOS
    if (isNaN(d.getTime())) d = new Date(s.replace(/-/g, '/'));
  } else {
    d = new Date(input);
  }
  if (isNaN(d.getTime())) return '';
  const pad = n => (n < 10 ? '0' + n : '' + n);
  const y = d.getFullYear();
  const m = pad(d.getMonth() + 1);
  const day = pad(d.getDate());
  const hh = pad(d.getHours());
  const mm = pad(d.getMinutes());
  const ss = pad(d.getSeconds());
  return `${y}-${m}-${day} ${hh}:${mm}:${ss}`;
}

// 从一条记录中提取更新时间，支持多种字段名
export function pickUpdatedAt(row) {
  return row?.updatedAt ?? row?.updateTime ?? row?.updated_time ?? row?.updated_at ?? row?.updated ?? '';
}

// 保持向后兼容
export const formatDateTime = formatDateTimeCompat;
