import type {
  ProductScheduleCardViewModel,
  ScheduleTimelineBar,
  ScheduleTimelineRow,
} from '../../types';

/**
 * 文件职责：时段时间轴与时间段计算。
 */

function tryParseTimeMinutes(value: string): null | number {
  const matched = /^([01]\d|2[0-3]):([0-5]\d)$/.exec((value || '').trim());
  if (!matched) return null;

  const hour = Number(matched[1]);
  const minute = Number(matched[2]);
  return hour * 60 + minute;
}

function toPercent(minutes: number) {
  return Number(((minutes / 1440) * 100).toFixed(4));
}

function toHourLabel(value: string, trimLeadingZero = false) {
  const hour = value.slice(0, 2);
  if (!trimLeadingZero) return hour;
  return String(Number(hour));
}

/** 校验时间文本。 */
export function isValidTimeText(value: string) {
  return tryParseTimeMinutes(value) !== null;
}

/** 是否跨天时段。 */
export function isCrossDay(startTime: string, endTime: string) {
  const start = tryParseTimeMinutes(startTime);
  const end = tryParseTimeMinutes(endTime);
  if (start === null || end === null) return false;
  return end <= start;
}

/** 卡片显示时间文本。 */
export function formatTimeRangeText(startTime: string, endTime: string) {
  const suffix = isCrossDay(startTime, endTime) ? ' (次日)' : '';
  return `${startTime} ~ ${endTime}${suffix}`;
}

/** 计算时间条段（支持跨天拆分）。 */
export function buildTimeSegments(startTime: string, endTime: string) {
  const start = tryParseTimeMinutes(startTime);
  const end = tryParseTimeMinutes(endTime);
  if (start === null || end === null || start === end) {
    return [] as ScheduleTimelineBar[];
  }

  if (end > start) {
    return [
      {
        left: toPercent(start),
        width: toPercent(end - start),
        label: `${toHourLabel(startTime)}~${toHourLabel(endTime)}`,
      },
    ];
  }

  return [
    {
      left: toPercent(start),
      width: toPercent(1440 - start),
      label: `${toHourLabel(startTime)}~24`,
    },
    {
      left: 0,
      width: toPercent(end),
      label: `0~${toHourLabel(endTime, true)}`,
    },
  ];
}

/** 今日星期（1-7）。 */
export function getTodayWeekDay() {
  const day = new Date().getDay();
  return day === 0 ? 7 : day;
}

/** 构造今日时间轴行。 */
export function buildTimelineRow(
  item: ProductScheduleCardViewModel,
  color: string,
): ScheduleTimelineRow {
  return {
    id: item.id,
    name: item.name,
    status: item.status,
    color,
    bars: buildTimeSegments(item.startTime, item.endTime),
  };
}
