fill.ts 27.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
/**
 * 补齐流程:每一格按「表内原有 → 地址解析 → 接口缓存 →(可选)邻近地点 → 地图接口」取值。
 *
 * 地址优先是这件事省钱的来源:第三方件只给 5 列(案件号 / 出险地点 / 报案时间 / 经度 / 纬度),
 * 三个目标列全空,旧判据「列空即查」等于每一行都付费。实测 42,806 行里
 * 行政区有 42,802 行第 3 段就写着、街道 16,333 行、道路 22,393 行明写在地址文本里 ——
 * 先读文本再查坐标,需付费的唯一坐标从 33,288 降到 17,421。
 *
 * 但「读得出」不等于「读得准」:地址解析与主程序逐行对齐,读出错词短语是它口径的一部分。
 * 所以每一格先过 targets.ts 里的 distrust 判据,读出来像顺口一句话的不采用、留给坐标去问
 * (用户口径:凡是不确定的都调 API)。坐标本来就问不了接口的行才回写可疑读法并标注需复核。
 */
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseAddress, type ParsedAddress } from './address.ts';
import {
  Cache, QueryError, RequestCancelled, StopRun, text,
  type LookupClient, type ResultFields,
} from './client.ts';
import { insideSanityBox, normalizeCoordinates, toMicroDegrees, type Coords } from './coords.ts';
import { UserError } from './errors.ts';
import { createClient } from './key.ts';
import { NearbyIndex, type RefPoint } from './nearby.ts';
import { ADDRESS_ALIASES, COORDINATE_COLUMNS, NEARBY_COLUMN, SOURCES, TARGETS, type NearbyField, type SourceName } from './targets.ts';
import {
  LIST_KINDS, buildRows, classify, listHeader, listPath, readOnlyList, type ListRow,
} from './lists.ts';
import { loadVocab, type Vocab } from './vocab.ts';
import { atomicCsv, validatePaths } from './csv-store.ts';
import { permuteTable, readTable, writeTable } from './table-store.ts';

/** 词表随工具一起走,不需要配置项;换城市就是换这一份 JSON */
export const DEFAULT_VOCAB = path.resolve(
  path.dirname(fileURLToPath(import.meta.url)), '..', 'config', 'shenzhen-districts.json',
);

const LOG_HEADERS_FIXED = [
  '原始记录号(含表头)', '输出行号(含表头)', '经度', '纬度', '请求经度', '请求纬度', '处理状态',
  ...TARGETS.flatMap((target) => [target.column, `${target.column}来源`]),
  '地址行政区', '地址街道', '地址道路',
  '接口行政区', '接口街道', '接口道路', '接口道路来源', '接口道路距离(米)', '道路候选(JSON)',
  '门牌道路', '门牌距离(米)', '邻近参照距离(米)', '备注', '失败或缺失原因',
];
export const LOG_HEADERS = LOG_HEADERS_FIXED;

export type Report = {
  exit_code: number;
  rows: number;
  /** 只靠表内原值 + 地址解析就补齐三项、一次接口都没查的行数 */
  address_complete_rows: number;
  /** 缓存与邻近都补完之后,真正进队列查询的唯一坐标数(付费上限) */
  lookup_coordinates: number;
  cache_hits: number;
  requests: number;
  /** 由邻近参照点补上的行数(infer_nearby 关闭时恒为 0) */
  nearby_rows: number;
  /** 三个目标列按格统计的最终来源;界面用它说明哪些值是读出来的、哪些是查来的 */
  cells_by_source: Record<string, number>;
  /** 三个目标列里最终仍空白的格数 */
  blank_cells: number;
  statuses: Record<string, number>;
  /** 三份清单各自的行数;没有这类行就是 0,也不会生成文件 */
  list_rows: Record<string, number>;
  /** 三份清单的文件路径;只列出实际生成了的 */
  list_files: Record<string, string>;
  /** 「只跑清单里的行」本次匹配到的行数;没开这个开关时为 0 */
  only_list_rows: number;
  elapsed_seconds: number;
  stop_reason: string;
  output: string;
  log: string;
  cache: string;
};

/** 一件正在做的事;done/total 只在有明确进度可报时出现(调用接口那一档) */
export type Stage = { label: string; done?: number; total?: number };

/** 邻近推断半径覆盖(米);行政区不在这里,它一律不靠邻近补 */
export type NearbyRadii = { street?: number; road?: number };

export type RunOptions = {
  limit?: number | null;
  workers?: number;
  qps?: number;
  /** 用附近已知点的归属补空白;默认关闭,半径见 targets.ts */
  inferNearby?: boolean;
  /** 半径分档的临时改动,只为界面调参准备;不写就用 targets.ts 的分档 */
  nearbyMeters?: NearbyRadii;
  /** 三项仍有空白的记录整行排到末尾(在内存里定序,输出只写一次) */
  sortIncompleteLast?: boolean;
  /** 只跑清单里的行:这份清单之外的行本次不许问接口(给花费上锁,输出仍是完整表格) */
  onlyList?: string;
  /** 本轮的临时目录:处理日志与三份清单写在这里;不传就是源文件旁的 .temp */
  tempDir?: string;
  client?: LookupClient;
  /** 仅在确有待查坐标时调用;测试注入离线工厂以证明不访问网络。 */
  clientFactory?: (qps: number) => LookupClient | Promise<LookupClient>;
  progress?: (message: string) => void;
  /** 正在做哪一件事;图形界面用它显示进度,命令行不需要 */
  stage?: (stage: Stage) => void;
  signal?: AbortSignal;
  vocab?: Vocab;
};

type Plan = {
  status: string;
  reason: string;
  notes: string[];
  parsed: ParsedAddress;
  coords: Coords | null;
  /** 与 TARGETS 同下标;'' 表示这一格本次没有写入任何来源 */
  sources: (SourceName | '')[];
  /** 地址读出但不敢采用的格子,留给「坐标问不了接口」那类行兜底写入 */
  rejected: Array<{ index: number; value: string; reason: string }>;
  /** 本行坐标的接口/缓存答案,只为日志的「接口*」几列存在 */
  result: ResultFields | null;
  nearbyMeters: string;
  outputLine: number;
  /** 只跑清单里的行时,这一行不在清单上,本次没进队列 */
  skipped: boolean;
};

type Group = { coords: Coords; rows: number[] };

const EMPTY_PARSED: ParsedAddress = {
  district: '', street: '', road: '', rest: '', detail: '',
};

export async function runJob(input: string, output: string, cacheFile: string,
  options: RunOptions = {}): Promise<Report> {
  const limit = options.limit ?? null;
  const workers = options.workers ?? 20;
  const qps = options.qps ?? 100;
  const inferNearby = options.inferNearby ?? false;
  const radii = options.nearbyMeters ?? {};
  if (!Number.isInteger(workers) || workers <= 0) throw new UserError('workers 必须是正整数');
  if (limit !== null && (!Number.isInteger(limit) || limit <= 0)) throw new UserError('limit 必须是正整数');
  if (!Number.isFinite(qps) || qps < 0) throw new UserError('qps 必须是有限的非负数');
  for (const value of [radii.street, radii.road]) {
    if (value !== undefined && (!Number.isFinite(value) || value <= 0)) {
      throw new UserError('邻近半径必须是正数(米)');
    }
  }

  const vocab = options.vocab ?? loadVocab(DEFAULT_VOCAB);
  const source = path.resolve(input);
  const target = path.resolve(output);
  const cachePath = path.resolve(cacheFile);
  // 日志与清单是过程文件,统一进源文件旁的临时目录;输出目录只留正式表格
  const tempDir = path.resolve(options.tempDir
    ?? path.join(path.dirname(source), '.temp'));
  const logPath = validatePaths(source, target, cachePath, tempDir);
  options.stage?.({ label: '读取表格' });
  const table = readTable(source, limit);
  const { header, rows } = table;
  const column = new Map(header.map((name, position) => [name, position] as const));
  const at = (name: string): number => column.get(name) as number;
  const started = performance.now();
  if (table.appended.length > 0) {
    options.progress?.(`输入缺少 ${table.appended.join('、')} 列,已在末尾追加空列用于写入结果。`);
  }
  const addressColumn = ADDRESS_ALIASES.map((name) => column.get(name))
    .find((index) => index !== undefined);
  if (addressColumn === undefined) {
    options.progress?.(`输入没有「${ADDRESS_ALIASES[0]}」列,跳过地址解析,全部依赖坐标查询。`);
  }

  const plans: Plan[] = rows.map((_, position) => ({
    status: '未处理', reason: '', notes: [], parsed: EMPTY_PARSED, coords: null,
    sources: TARGETS.map(() => ''), rejected: [], result: null, nearbyMeters: '',
    outputLine: position + 2, skipped: false,
  }));
  const blanksOf = (position: number): number[] => TARGETS
    .map((_, index) => index)
    .filter((index) => text(rows[position][at(TARGETS[index].column)]) === '');

  // 只跑清单里的行:清单给的是行身份,不是新表 —— 仍然读原表、写完整表,只有清单内的行允许问接口
  // 留空是常态(不是「读当前目录」):先判空再 resolve
  const onlyGiven = (options.onlyList ?? '').trim();
  const onlyFile = onlyGiven === '' ? '' : path.resolve(onlyGiven);
  const only = onlyFile === '' ? null : readOnlyList(onlyFile);
  // 清单里有案件号、这份表里也有就按案件号匹配(重排过行也对得上),否则退回按原表行号
  const onlyColumn = only !== null && column.has(only.column) ? only.column : '原表行号';
  const onlyAt = only === null || onlyColumn === '原表行号' ? undefined : column.get(onlyColumn);
  const inList = (position: number): boolean => {
    if (only === null) return true;
    if (onlyColumn === '原表行号') return only.values.has(String(position + 2));
    return only.values.has(text(rows[position][onlyAt as number] ?? ''));
  };
  const onlyRows = only === null
    ? 0
    : rows.reduce((count, _, position) => count + (inList(position) ? 1 : 0), 0);
  if (only !== null && onlyRows === 0) {
    const pairing = `清单「${onlyFile}」里没有任何一行在这份表里找得到(按${onlyColumn}匹配)。`
      + '清单要与生成它的那份输入文件配对使用,表格被编辑过或换过文件就不要用它。';
    throw new UserError(limit === null ? pairing
      : `${pairing}这次还设了「只处理前几行」,表只读到第 ${limit} 行,清单里的行可能落在没读到的部分。`);
  }
  if (only !== null) {
    options.progress?.(`只跑清单里的行:按「${onlyColumn}」匹配到 ${onlyRows} 行,`
      + '其余行只用地址与缓存,不会再问接口。');
  }

  /** 只写空白格:已有值一律保留并记「表内原有」;写出来源,导入的人才知道哪些是免费的。 */
  const setCell = (position: number, index: number, value: string, from: SourceName): boolean => {
    if (text(rows[position][at(TARGETS[index].column)]) !== '') {
      if (plans[position].sources[index] === '') plans[position].sources[index] = SOURCES.original;
      return false;
    }
    if (value === '') return false;
    rows[position][at(TARGETS[index].column)] = value;
    plans[position].sources[index] = from;
    return true;
  };

  // 第一遍:表内原值 + 地址解析。坐标顺手规范化,完整行也留坐标 —— 邻近推断要拿它们当参照点
  options.stage?.({ label: '解析地址文本' });
  rows.forEach((row, position) => {
    const plan = plans[position];
    const addressText = addressColumn === undefined ? '' : text(row[addressColumn]);
    if (addressColumn !== undefined) plan.parsed = parseAddress(addressText, vocab);
    TARGETS.forEach((target_, index) => {
      setCell(position, index, text(row[at(target_.column)]), SOURCES.original);
      const fromText = target_.fromAddress(plan.parsed);
      if (fromText === '') return;
      // 读出来像顺口一句话的值不采用:这一格空着,让坐标去问接口(不确定的宁可花一次钱)
      const reason = target_.distrust?.(fromText, addressText, vocab) ?? '';
      if (reason === '') {
        setCell(position, index, fromText, SOURCES.address);
        return;
      }
      plan.rejected.push({ index, value: fromText, reason });
      plan.notes.push(`地址读出的${target_.column}「${fromText}」${reason},不采用,改用坐标查询`);
    });
    plan.coords = safeCoordinates(row[at(COORDINATE_COLUMNS[0])], row[at(COORDINATE_COLUMNS[1])]);
  });

  const groups = new Map<string, Group>();
  rows.forEach((_, position) => {
    if (blanksOf(position).length === 0) return;
    const coords = plans[position].coords;
    if (coords === null || !insideSanityBox(coords)) return; // 收尾时按无效坐标/域外坐标交代
    const key = `${coords[0]},${coords[1]}`;
    const group = groups.get(key);
    if (group === undefined) groups.set(key, { coords, rows: [position] });
    else group.rows.push(position);
  });

  const applyResult = (group: Group, result: ResultFields, from: SourceName): void => {
    for (const position of group.rows) {
      plans[position].result = result;
      TARGETS.forEach((target_, index) => {
        setCell(position, index, result[target_.api], from);
      });
    }
  };

  options.stage?.({ label: '查缓存' });
  const cache = new Cache(cachePath);
  let client = options.client;
  let stopped = false;
  let interrupted = false;
  let stopReason = '';
  let cachedGroups = 0;
  let nearbyRows = 0;
  let completed = 0;
  let queued: Group[] = [];
  try {
    const uncached: Group[] = [];
    for (const group of groups.values()) {
      const result = cache.get(group.coords);
      if (result === null) uncached.push(group);
      else {
        applyResult(group, result, SOURCES.cache);
        cachedGroups += 1;
      }
    }

    if (inferNearby && uncached.length > 0) {
      options.stage?.({ label: '邻近推断' });
      nearbyRows = fillFromNearby(rows, plans, cache, blanksOf, column, setCell, radii);
    }

    // 邻近补完仍缺格的坐标才进队列;开了「只跑清单里的行」时,清单内的行才有资格排队
    queued = uncached.filter((group) => group.rows.some((position) => {
      if (blanksOf(position).length === 0) return false;
      if (inList(position)) return true;
      plans[position].skipped = true;
      return false;
    }));

    // 原值 + 地址就凑齐三项的行数:这一档就是「一行钱都没花」的行数,与待查队列同口径
    const addressComplete = rows
      .reduce((count, _, position) => count + (blanksOf(position).length === 0 ? 1 : 0), 0);
    options.progress?.(`${table.sheet === null ? '' : `工作表 ${table.sheet.sheetName};`}`
      + `读取 ${rows.length} 行;原值与地址即完整 ${addressComplete} 行;`
      + `待查唯一坐标 ${queued.length};缓存命中 ${cachedGroups};邻近补全 ${nearbyRows} 行;`
      + `并发 ${workers};QPS ${qps === 0 ? '不限' : qps}`);
    if (queued.length > 0 && client === undefined) {
      // 先让人看见这一趟要问多少次,再去要 Key —— 付费的门槛前不能只写一句「请输入」
      options.stage?.({ label: '准备调用接口', total: queued.length });
      client = await (options.clientFactory ?? createClient)(qps);
    }
    if (queued.length > 0 && client !== undefined) {
      options.stage?.({ label: '调用地图接口', done: 0, total: queued.length });
      const active = client;
      const onAbort = (): void => {
        interrupted = true;
        stopped = true;
        stopReason = '用户中断';
        active.stopEvent.set();
      };
      if (options.signal !== undefined) {
        if (options.signal.aborted) onAbort();
        else options.signal.addEventListener('abort', onAbort, { once: true });
      }
      const queue = [...queued];
      const worker = async (): Promise<void> => {
        for (;;) {
          if (stopped) return;
          const group = queue.shift();
          if (group === undefined) return;
          try {
            const result = await active.lookup(group.coords[0], group.coords[1]);
            cache.put(group.coords, result);
            applyResult(group, result, SOURCES.api);
          } catch (exc) {
            if (exc instanceof RequestCancelled) {
              // 运行已停止:保留已完成结果,该行留给收尾定成未处理。
            } else if (exc instanceof StopRun) {
              stopped = true;
              stopReason = exc.message;
              active.stopEvent.set();
              for (const position of group.rows) {
                plans[position].status = '请求失败';
                plans[position].reason = stopReason;
              }
            } else if (exc instanceof QueryError) {
              for (const position of group.rows) {
                plans[position].status = '请求失败';
                plans[position].reason = exc.message;
              }
            } else {
              throw exc;
            }
          }
          completed += 1;
          const drained = queue.length === 0;
          if (completed % 10 === 0 || drained) {
            options.stage?.({ label: '调用地图接口', done: completed, total: queued.length });
          }
          if (options.progress && (completed % 100 === 0 || drained)) {
            options.progress(`已处理唯一坐标 ${completed}/${queued.length},`
              + `耗时 ${((performance.now() - started) / 1000).toFixed(1)} 秒`);
          }
        }
      };
      try {
        await Promise.all(Array.from({ length: Math.min(workers, queued.length) }, () => worker()));
      } finally {
        options.signal?.removeEventListener('abort', onAbort);
      }
    }

    // 坐标问不了接口的行(无效坐标、域外坐标),可疑的文本读法仍比空白有用 ——
    // 写回去,但备注必须说清这一格没被接口复核过
    rows.forEach((_, position) => {
      const plan = plans[position];
      if (plan.rejected.length === 0) return;
      if (plan.coords !== null && insideSanityBox(plan.coords)) return;
      for (const item of plan.rejected) {
        const name = TARGETS[item.index].column;
        if (!setCell(position, item.index, item.value, SOURCES.address)) continue;
        plan.notes = plan.notes.filter((note) => !note.startsWith(`地址读出的${name}「${item.value}」`));
        plan.notes.push(`${name}「${item.value}」是可疑读法,但这一行的坐标问不了接口,先按地址写入,需复核`);
      }
    });

    rows.forEach((_, position) => {
      conclude(plans[position], blanksOf(position), stopReason);
      annotate(plans[position], TARGETS.map((t) => text(rows[position][at(t.column)])), vocab);
    });

    const logPositions = rows.map((_, position) => position);
    if (options.sortIncompleteLast === true) {
      // 稳定排序:完整段与未完整段各自保持原顺序,整行一起搬;
      // 日志与输出行序一致(第 N 行对第 N 行),原始位置看「原始记录号」列
      logPositions.sort((a, b) => Number(blanksOf(a).length > 0) - Number(blanksOf(b).length > 0));
      logPositions.forEach((position, index) => { plans[position].outputLine = index + 2; });
      permuteTable(table, logPositions);
    }
    const logRows = logPositions.map((position) => logRow(rows[position], position, plans[position], column));
    options.stage?.({ label: '写出表格', total: rows.length });
    writeTable(target, table);
    options.stage?.({ label: '写出处理日志', total: rows.length });
    atomicCsv(logPath, LOG_HEADERS, logRows);

    // 三份清单:按处理状态、空白格数、备注分档,同一行只会进一份(限流优先,重跑就能解决的先说)
    const buckets = new Map<string, ListRow[]>();
    rows.forEach((_, position) => {
      const plan = plans[position];
      const blanks = blanksOf(position);
      const kind = classify(plan.status, blanks.length, plan.notes.length);
      if (kind === '') return;
      const list = buckets.get(kind) ?? [];
      list.push({
        values: rows[position], sourceLine: position + 2, outputLine: plan.outputLine,
        missing: blanks.map((index) => TARGETS[index].column).join('、'),
        status: plan.status, reason: plan.reason, notes: plan.notes.join(';'),
      });
      buckets.set(kind, list);
    });
    const listRows: Record<string, number> = {};
    const listFiles: Record<string, string> = {};
    for (const info of LIST_KINDS) listRows[info.title] = (buckets.get(info.kind) ?? []).length;
    const kinds = LIST_KINDS.filter((info) => (buckets.get(info.kind) ?? []).length > 0);
    if (kinds.length > 0) options.stage?.({ label: '写出本次清单', total: kinds.length });
    for (const info of kinds) {
      const list = buckets.get(info.kind) as ListRow[];
      const file = listPath(target, info, tempDir);
      atomicCsv(file, listHeader(header), buildRows(info, list));
      listFiles[info.title] = file;
    }

    const statuses: Record<string, number> = {};
    for (const plan of plans) statuses[plan.status] = (statuses[plan.status] ?? 0) + 1;
    const cellsBySource: Record<string, number> = {};
    let blankCells = 0;
    for (const plan of plans) {
      for (const source of plan.sources) {
        if (source === '') {
          blankCells += 1;
          continue;
        }
        cellsBySource[source] = (cellsBySource[source] ?? 0) + 1;
      }
    }
    const complete = plans.every((plan) => plan.status === '完整');
    return {
      exit_code: interrupted ? 130 : complete && !stopped ? 0 : 2,
      rows: rows.length,
      address_complete_rows: addressComplete,
      lookup_coordinates: queued.length,
      cache_hits: cachedGroups,
      requests: client?.requests ?? 0,
      nearby_rows: nearbyRows,
      cells_by_source: cellsBySource,
      blank_cells: blankCells,
      statuses,
      list_rows: listRows,
      list_files: listFiles,
      only_list_rows: onlyRows,
      elapsed_seconds: (performance.now() - started) / 1000,
      stop_reason: stopReason,
      output: target,
      log: logPath,
      cache: cachePath,
    };
  } finally {
    if (client !== undefined) client.stopEvent.set();
    cache.close();
  }
}

function safeCoordinates(lngRaw: string, latRaw: string): Coords | null {
  try {
    return normalizeCoordinates(lngRaw, latRaw);
  } catch {
    return null;
  }
}

/** 收尾定状态。顺序讲究:已经付过钱失败的行,不能被后面的「坐标缺失」抢走说法。 */
function conclude(plan: Plan, blanks: number[], stopReason: string): void {
  const missing = blanks.map((index) => TARGETS[index].column).join('、');
  if (plan.status === '请求失败') {
    if (missing !== '') plan.notes.push(`仍缺 ${missing}`);
    return;
  }
  if (blanks.length === 0) {
    plan.status = '完整';
    plan.reason = '';
    return;
  }
  if (plan.coords === null) {
    plan.status = '无效坐标';
    plan.reason = `${COORDINATE_COLUMNS.join('/')} 缺失、非数值、格式非法或越界`;
    return;
  }
  if (!insideSanityBox(plan.coords)) {
    plan.status = '域外坐标';
    plan.reason = '坐标不在深圳合理范围内(主程序导入时同样会拒收),未查询';
    return;
  }
  if (plan.result !== null) {
    plan.status = '部分缺失';
    plan.reason = `接口未返回:${missing}`;
    return;
  }
  plan.status = '未处理';
  if (plan.skipped) {
    plan.reason = '不在本次清单里,这一行没问接口;去掉「只跑清单里的行」再跑就会查';
    return;
  }
  plan.reason = stopReason === '' ? '尚未查询,重跑可继续' : `${stopReason};重跑可继续`;
}

/**
 * 值得复核、但不改动取值的事实写进备注:导入的人会照着备注抽样核对,而不是照着状态猜。
 * 邻市的结果照实写进列(业务要看真名),所以这里只补一句「不在深圳辖区名单内」。
 */
function annotate(plan: Plan, values: string[], vocab: Vocab): void {
  const [district, street] = values;
  if (district !== '' && !vocab.shenzhen.has(district)) {
    plan.notes.push(`行政区「${district}」不在深圳辖区名单内`);
  }
  const owner = street === '' ? undefined : vocab.districtOfStreet.get(street);
  if (owner !== undefined && district !== '' && owner !== district) {
    plan.notes.push(`街道「${street}」属${owner},与行政区「${district}」不一致`);
  }
}

/** 参照点一:本批里三项都已定、坐标可用的行;参照点二:缓存里已查过的坐标。 */
function buildRefs(
  rows: string[][],
  plans: Plan[],
  blanksOf: (position: number) => number[],
  column: Map<string, number>,
  cache: Cache,
): RefPoint[] {
  const refs: RefPoint[] = [];
  rows.forEach((_, position) => {
    const plan = plans[position];
    if (plan.coords === null || blanksOf(position).length > 0) return;
    if (!insideSanityBox(plan.coords)) return;
    const value = (field: NearbyField): string =>
      text(rows[position][column.get(NEARBY_COLUMN[field]) as number]);
    refs.push({
      lng: toMicroDegrees(plan.coords[0]), lat: toMicroDegrees(plan.coords[1]),
      district: value('district'), street: value('street'), road: value('road'),
    });
  });
  for (const point of cache.points()) {
    refs.push({
      lng: point.lng, lat: point.lat,
      district: point.district, street: point.township, road: point.road,
    });
  }
  return refs;
}

/**
 * 邻近推断:半径按字段分档(见 targets.ts),参照点的区与本行已知的区不一致时不用 ——
 * 邻近只回答「这一带归哪个街道」,不能把案件记到隔壁区头上。
 */
function fillFromNearby(
  rows: string[][],
  plans: Plan[],
  cache: Cache,
  blanksOf: (position: number) => number[],
  column: Map<string, number>,
  setCell: (position: number, index: number, value: string, from: SourceName) => boolean,
  radii: NearbyRadii,
): number {
  const index = new NearbyIndex(buildRefs(rows, plans, blanksOf, column, cache));
  let filledRows = 0;
  rows.forEach((_, position) => {
    const plan = plans[position];
    if (plan.coords === null) return;
    const blanks = blanksOf(position);
    if (blanks.length === 0) return;
    const lng = toMicroDegrees(plan.coords[0]);
    const lat = toMicroDegrees(plan.coords[1]);
    const knownDistrict = text(rows[position][column.get(NEARBY_COLUMN.district) as number]);
    let meters = 0;
    for (const target_ of blanks) {
      const field = TARGETS[target_].nearby;
      // 行政区这一档没有半径可改:邻近点跨区太容易,界面上也不给这一栏
      const radius = field === 'district' ? 0 : radii[field] ?? TARGETS[target_].inferMeters;
      if (radius <= 0) continue;
      const hit = index.nearest(lng, lat, radius, (point) => {
        if (point[field] === '') return false;
        return knownDistrict === '' || point.district === '' || point.district === knownDistrict;
      });
      if (hit === null) continue;
      if (setCell(position, target_, hit.point[field], SOURCES.nearby)) {
        meters = Math.max(meters, Math.round(hit.meters));
      }
    }
    if (meters > 0) {
      plan.nearbyMeters = String(meters);
      filledRows += 1;
    }
  });
  return filledRows;
}

function logRow(row: string[], position: number, plan: Plan, column: Map<string, number>): string[] {
  const result = plan.result;
  const value = (index: number): string => row[column.get(TARGETS[index].column) as number];
  return [
    String(position + 2), String(plan.outputLine),
    row[column.get(COORDINATE_COLUMNS[0]) as number], row[column.get(COORDINATE_COLUMNS[1]) as number],
    plan.coords === null ? '' : plan.coords[0], plan.coords === null ? '' : plan.coords[1],
    plan.status,
    ...TARGETS.flatMap((_, index) => [value(index), plan.sources[index]]),
    plan.parsed.district, plan.parsed.street, plan.parsed.road,
    result?.district ?? '', result?.township ?? '', result?.road ?? '',
    result?.road_source ?? '', result?.road_distance ?? '',
    JSON.stringify(result?.candidates ?? []),
    result?.street_road ?? '', result?.street_distance ?? '',
    plan.nearbyMeters, plan.notes.join(';'), plan.reason,
  ];
}