export interface ExcelMonthInfo {
  month: string;
  rangeLabel: string;
}

const SALARY_MONTH_RE = /^(\d{4})-(0[1-9]|1[0-2])$/;

export function isSalaryMonth(value: string): boolean {
  return SALARY_MONTH_RE.test(value);
}

export function formatMonthRange(month: string): string {
  if (!isSalaryMonth(month)) {
    return "请选择核算月份";
  }

  const [yearText, monthText] = month.split("-");
  const year = Number(yearText);
  const monthIndex = Number(monthText) - 1;
  const start = new Date(year, monthIndex, 1);
  const end = new Date(year, monthIndex + 1, 0);
  return `${formatDate(start)} 至 ${formatDate(end)}`;
}

export function extractMonthFromExcelFilename(filename: string): ExcelMonthInfo | null {
  const compactDates = [...filename.matchAll(/((?:19|20)\d{2})(0[1-9]|1[0-2])([0-3]\d)/g)];
  if (compactDates.length >= 2) {
    const first = compactDates[0];
    const last = compactDates[compactDates.length - 1];
    const month = `${first[1]}-${first[2]}`;
    return {
      month,
      rangeLabel: `${first[1]}/${first[2]}/${first[3]} 至 ${last[1]}/${last[2]}/${last[3]}`,
    };
  }

  const dashedMonth = filename.match(/((?:19|20)\d{2})[-_/年](0[1-9]|1[0-2])/);
  if (dashedMonth) {
    const month = `${dashedMonth[1]}-${dashedMonth[2]}`;
    return {
      month,
      rangeLabel: formatMonthRange(month),
    };
  }

  return null;
}

function formatDate(value: Date): string {
  const year = value.getFullYear();
  const month = String(value.getMonth() + 1).padStart(2, "0");
  const day = String(value.getDate()).padStart(2, "0");
  return `${year}/${month}/${day}`;
}
