import { ref, onMounted, onBeforeUnmount } from 'vue';

/**
 * 格式化日期时间
 * @param date 日期对象或时间戳
 * @param format 格式字符串，默认 'YYYY-MM-DD HH:mm:ss'
 * @returns 格式化后的时间字符串
 */
export function formatDateTime(date: Date | number | string, format = 'YYYY-MM-DD HH:mm:ss'): string {
  const d = new Date(date);
  
  if (isNaN(d.getTime())) {
    return '';
  }

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');

  return format
    .replace('YYYY', String(year))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
}

/**
 * 获取当前时间字符串
 * @param format 格式字符串
 * @returns 当前时间字符串
 */
export function getCurrentTime(format = 'YYYY-MM-DD HH:mm:ss'): string {
  return formatDateTime(new Date(), format);
}

/**
 * 获取实时时间（用于显示）
 * @param format 格式字符串
 * @returns 响应式时间字符串
 */
export function useRealTime(format = 'YYYY-MM-DD HH:mm:ss') {
  const currentTime = ref(getCurrentTime(format));
  let timer: NodeJS.Timeout | null = null;

  const startTimer = () => {
    timer = setInterval(() => {
      currentTime.value = getCurrentTime(format);
    }, 1000);
  };

  const stopTimer = () => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };

  onMounted(startTimer);
  onBeforeUnmount(stopTimer);

  return {
    currentTime,
    startTimer,
    stopTimer
  };
}