import { Injectable, Pipe, PipeTransform } from '@angular/core';
import { formatDate } from '@angular/common';
import { registerLocaleData } from '@angular/common';
import localeZh from '@angular/common/locales/zh';

registerLocaleData(localeZh);

@Pipe({
  name: 'showDate'
})
@Injectable()
export class ShowDatePipe implements PipeTransform {
  transform(date: Date, locale: string = 'zh-CN'): string {
    if (!date) {
      return '';
    }
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    const beforeYesterday = new Date(yesterday);
    beforeYesterday.setDate(beforeYesterday.getDate() - 1);

    const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate());

    if (dateOnly.toISOString() === today.toISOString()) {
      return formatDate(date, 'HH:mm', locale);
    } else if (dateOnly.toISOString() === yesterday.toISOString()) {
      return `昨天 ${formatDate(date, 'HH:mm', locale)}`;
    } else if (dateOnly.toISOString() === beforeYesterday.toISOString()) {
      return `前天 ${formatDate(date, 'HH:mm', locale)}`;
    } else {
      return formatDate(date, 'yyyy-MM-dd HH:mm', locale);
    }
  }
}