import { normalizePddDate } from './parseReport'; import { humanPauseMs, sleep } from './domInteract'; import { switchToSingleDay } from './switchReportDate'; /** 单次自动逐日最多天数(含起止) */ export const MAX_AUTO_COLLECT_DAYS = 31; export function listDatesInclusive(startIso: string, endIso: string): string[] { const start = normalizePddDate(startIso) ?? startIso; const end = normalizePddDate(endIso) ?? endIso; if (!/^\d{4}-\d{2}-\d{2}$/.test(start) || !/^\d{4}-\d{2}-\d{2}$/.test(end)) { throw new Error('起止日期格式无效'); } if (start > end) { throw new Error('开始日期不能晚于结束日期'); } const dates: string[] = []; const cursor = new Date(`${start}T00:00:00`); const endDate = new Date(`${end}T00:00:00`); while (cursor <= endDate) { const y = cursor.getFullYear(); const m = String(cursor.getMonth() + 1).padStart(2, '0'); const d = String(cursor.getDate()).padStart(2, '0'); dates.push(`${y}-${m}-${d}`); if (dates.length > MAX_AUTO_COLLECT_DAYS) { throw new Error(`单次最多 ${MAX_AUTO_COLLECT_DAYS} 天,请缩小范围`); } cursor.setDate(cursor.getDate() + 1); } return dates; } export interface AutoCollectProgress { index: number; total: number; date: string; phase: 'switch' | 'read' | 'pause' | 'done' | 'skip'; message: string; } export interface AutoCollectOptions { startDate: string; endDate: string; /** 已累计过的日期,默认跳过 */ skipDates?: Set | string[]; signal?: AbortSignal; onProgress?: (p: AutoCollectProgress) => void; /** 切到该日后执行读取;返回是否成功(无数据也可 true) */ readDay: (date: string) => Promise; } /** * 按日拟人切换并读取。日间有随机停顿,避免过快连点。 */ export async function runAutoCollectByDates(options: AutoCollectOptions): Promise { const dates = listDatesInclusive(options.startDate, options.endDate); const skip = new Set( [...(options.skipDates ?? [])].map((d) => normalizePddDate(d) ?? d), ); for (let i = 0; i < dates.length; i++) { if (options.signal?.aborted) { throw new DOMException('已取消自动读取', 'AbortError'); } const date = dates[i]!; if (skip.has(date)) { options.onProgress?.({ index: i + 1, total: dates.length, date, phase: 'skip', message: `跳过已读 ${date}(${i + 1}/${dates.length})`, }); continue; } options.onProgress?.({ index: i + 1, total: dates.length, date, phase: 'switch', message: `切换日期 ${date}(${i + 1}/${dates.length})…`, }); await switchToSingleDay(date, { signal: options.signal }); options.onProgress?.({ index: i + 1, total: dates.length, date, phase: 'read', message: `读取 ${date}(${i + 1}/${dates.length})…`, }); await options.readDay(date); if (i < dates.length - 1) { const pause = humanPauseMs('betweenDays'); options.onProgress?.({ index: i + 1, total: dates.length, date, phase: 'pause', message: `已读 ${date},停顿 ${(pause / 1000).toFixed(1)}s 后继续…`, }); await sleep(pause); } } options.onProgress?.({ index: dates.length, total: dates.length, date: dates[dates.length - 1] ?? '', phase: 'done', message: `自动读取完成(${dates.length} 天)`, }); }