import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import isToday from 'dayjs/plugin/isToday';
import isYesterday from 'dayjs/plugin/isYesterday';
import weekday from 'dayjs/plugin/weekday';

// 加载插件
dayjs.extend(relativeTime);
dayjs.extend(isToday);
dayjs.extend(isYesterday);
dayjs.extend(weekday);

function handleTime(timestamp) {
  const msgDate = dayjs(timestamp);
  const now = dayjs();

  // 获取当前时区的零点时间戳
  const todayStart = now.startOf('day');
  const yesterdayStart = todayStart.subtract(1, 'day');
  const lastWeekStart = todayStart.subtract(7, 'day');

  if (msgDate.isToday()) {
    // 今天：上午/下午 + 小时分钟
    const hour = msgDate.hour();
    let period = '凌晨';
    if (hour >= 6 && hour < 12) {
      period = '上午';
    } else if (hour >= 12 && hour < 18) {
      period = '下午';
    } else if (hour >= 18 || hour < 6) {
      period = '晚上';
    }
    return `${period}${msgDate.format('HH:mm')}`;
  }

  if (msgDate.isYesterday()) {
    // 昨天：昨天 + 小时分钟
    return `昨天 ${msgDate.format('HH:mm')}`;
  }

  if (msgDate.isAfter(lastWeekStart)) {
    // 本周内（非今天、非昨天）：星期几 + 小时分钟
    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const day = weekDays[msgDate.day()];
    return `${day} ${msgDate.format('HH:mm')}`;
  }

  if (msgDate.year() === now.year()) {
    // 同一年，不同周：月/日 + 小时分钟
    return msgDate.format('MM/DD HH:mm');
  }

  // 跨年：年/月/日 + 小时分钟
  return msgDate.format('YYYY/MM/DD HH:mm');
}


export { handleTime }