export const RELATIVE_DATE_VALUE = '@relativeDate';

export type RelativeDateAnchor = 'currentDate' | 'currentTime';
export type RelativeDateUnit = 'day' | 'hour' | 'minute' | 'month' | 'week' | 'year';

export interface RelativeDateConfig {
  anchor: RelativeDateAnchor;
  offset: number;
  unit: RelativeDateUnit;
}

const relativeDatePattern = /^@relativeDate:(currentDate|currentTime):(-?\d+):(minute|hour|day|week|month|year)$/;

const dateUnits = [
  { id: 'day', fullName: '天' },
  { id: 'week', fullName: '周' },
  { id: 'month', fullName: '月' },
  { id: 'year', fullName: '年' },
];
const timeUnits = [
  { id: 'minute', fullName: '分钟' },
  { id: 'hour', fullName: '小时' },
];

function isTimeField(jnpfKey: string) {
  return jnpfKey === 'timePicker';
}

export function isRelativeDateValue(value: unknown): value is string {
  return typeof value === 'string' && relativeDatePattern.test(value);
}

export function getRelativeDateConfig(value: unknown, jnpfKey: string): RelativeDateConfig {
  const match = typeof value === 'string' ? value.match(relativeDatePattern) : null;
  if (match) {
    return {
      anchor: match[1] as RelativeDateAnchor,
      offset: Number(match[2]),
      unit: match[3] as RelativeDateUnit,
    };
  }
  return {
    anchor: isTimeField(jnpfKey) ? 'currentTime' : 'currentDate',
    offset: 1,
    unit: isTimeField(jnpfKey) ? 'hour' : 'day',
  };
}

export function createRelativeDateValue(config: RelativeDateConfig) {
  return `${RELATIVE_DATE_VALUE}:${config.anchor}:${config.offset}:${config.unit}`;
}

export function getRelativeDateUnits(jnpfKey: string) {
  return isTimeField(jnpfKey) ? timeUnits : dateUnits;
}

export function getRelativeDateAnchorOptions(jnpfKey: string) {
  return isTimeField(jnpfKey) ? [{ id: 'currentTime', fullName: '当前时间' }] : [{ id: 'currentDate', fullName: '当前日期' }];
}

export function getDateSystemValue(value: unknown) {
  return value === RELATIVE_DATE_VALUE || isRelativeDateValue(value) ? RELATIVE_DATE_VALUE : value;
}

export function getRelativeDateLabel(value: unknown, jnpfKey: string) {
  const { anchor, offset, unit } = getRelativeDateConfig(value, jnpfKey);
  const unitName = getRelativeDateUnits(jnpfKey).find((item) => item.id === unit)?.fullName || unit;
  if (offset === 0) return anchor === 'currentTime' ? '当前时间' : '当前日期';
  return `${anchor === 'currentTime' ? '当前时间' : '当前日期'}${offset > 0 ? '后' : '前'}${Math.abs(offset)}${unitName}`;
}
