import { Inject, InjectionToken, NgModule, Pipe, PipeTransform } from '@angular/core';
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';

dayjs.extend(utc);
dayjs.extend(timezone);

export function transformTime(
  value: string | number | Date,
  format: string = 'YYYY/MM/DD',
  timezone: string = 'Asia/Shanghai'
) {
  // const cValue = value.toString().endsWith('.000Z') ? value : value.toString() + '.000Z';
  return dayjs(value).tz(timezone).format(format);
}

@Pipe({ name: 'time' })
export class TimePipe implements PipeTransform {
  constructor(@Inject(TIME_PIPE_CONFIG_TOKEN) private config: TimePipeConfig) {}
  transform(value: string | number | Date, format: string = 'YYYY/MM/DD'): string {
    return transformTime(value, format, this.config.timezone);
  }
}

export interface TimePipeConfig {
  timezone: string;
}
export const TIME_PIPE_CONFIG_TOKEN = new InjectionToken<TimePipeConfig>('TimePipeConfig');

@NgModule({
  declarations: [TimePipe],
  exports: [TimePipe],
})
export class TimePipeModule {}
