convert-excel-template-to-schema.py 55.2 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 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file 将门店工作汇报 Excel 填写表单 sheet 转为动态表单 schema。
依据行样式:删除线=剔除;紫色 rgb(242,199,255)=按 Excel 重解析;无标记=沿用 baseline fixture。
用法:
  python packageDynamicForm/scripts/convert-excel-template-to-schema.py --sheet staff --format js
  python packageDynamicForm/scripts/convert-excel-template-to-schema.py --sheet store --format js
  python packageDynamicForm/scripts/convert-excel-template-to-schema.py --sheet staff --env production --format js
"""
from __future__ import annotations

import argparse
import copy
import json
import re
import subprocess
import sys
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path

PKG_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_XLSX = Path(r'c:/Users/admin/Downloads/门店工作汇报模板-V2.1.1.xlsx')
PURPLE_RGB = (242, 199, 255)
NS = {'m': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}

BASE_SCENE_CODE = {
    '1.1': 100101,
    '1.2': 100102,
    '1.3': 100103,
    '2.1.1': 110101,
    '2.1.2': 110102,
    '2.3.1': 110201,
    '2.3.2': 110202,
    '6.1': 120101,
}

BRAND_ENV_MAPS_PATH = PKG_ROOT / 'fixtures/brand-id-env-maps.json'

BRAND_NAME_TO_ID: dict[str, int] = {}
FILTER_BRAND_IDS: list[int] = []
FIVE_REALM_IDS: list[int] = []


def load_brand_env_maps() -> dict:
    """读取 fixtures/brand-id-env-maps.json(与 brand-id-env-maps.mjs 数值一致)。"""
    return json.loads(BRAND_ENV_MAPS_PATH.read_text(encoding='utf-8'))


def apply_brand_env(env: str = 'daily') -> None:
    """按环境切换全局 brandId 映射,供 parse_brand_restriction 使用。"""
    global BRAND_NAME_TO_ID, FILTER_BRAND_IDS, FIVE_REALM_IDS
    maps = load_brand_env_maps()
    if env not in maps:
        raise ValueError(f'unknown brand env: {env}')
    name_to_id = maps[env]
    BRAND_NAME_TO_ID = dict(name_to_id)
    FIVE_REALM_IDS = [
        name_to_id['问界'],
        name_to_id['享界'],
        name_to_id['智界'],
        name_to_id['尚界'],
        name_to_id['尊界'],
    ]
    FILTER_BRAND_IDS = FIVE_REALM_IDS + [name_to_id['岚图']]


def build_file_header_comment(env: str = 'daily') -> str:
    """生成 JS fixture 文件头 brandIdMap 注释块。"""
    name_to_id = load_brand_env_maps()[env]
    lines = [
        '// const baseSceneCode = {',
        "//   '1.1': 100101, //精品升级",
        "//   '1.2': 100102, //次新车升配",
        "//   '1.3': 100103, //售后众筹",
        "//   '2.1.1': 110101, //售前会员权益升级",
        "//   '2.1.2': 110102, //售后会员权益升级",
        "//   '2.3.1': 110201, //售前延保",
        "//   '2.3.2': 110202, //售后延保",
        "//   '6.1': 120101, //二手车收车",
        '// }',
        '// const sceneType = {',
        "//   '延保': 0,",
        "//   '权益': 0,",
        "//   '轻改': 1,",
        "//   '二手车': 7,",
        '// }',
        '// const brandIdMap = {',
    ]
    for name, brand_id in name_to_id.items():
        lines.append(f"//   '{name}': {brand_id},")
    lines.append('// }')
    return '\n'.join(lines)


apply_brand_env('daily')

SHEET_CONFIG = {
    'staff': {
        'sheet_filter': '驻店日报',
        'baseline': PKG_ROOT / 'fixtures/schema-staff-daily-full.js',
        'output': PKG_ROOT / 'fixtures/schema-staff-daily-v2.1.1.js',
        'form_code': 'staff_daily_report',
        'attendance_key': 'F1-1',
    },
    'store': {
        'sheet_filter': '门店日报',
        'baseline': PKG_ROOT / 'fixtures/schema-store-daily-full.js',
        'output': PKG_ROOT / 'fixtures/schema-store-daily-v2.1.1.js',
        'form_code': 'store_daily_report',
        'attendance_key': None,
    },
}

V230_STORE_CONFIG = {
    'sheet_filter': '输入-门店日报',
    'exact_sheet': True,
    'classify_styles': False,
    'baseline': None,
    'output': PKG_ROOT / 'fixtures/schema-store-daily-v2.3.0.js',
    'form_code': 'store_daily_report',
    'attendance_key': None,
    'version': '2.3.0',
    'title': '门店日报 V2.3.0',
    'min_root_number': 101,
    'expected_record_count': 25,
    'expected_top_keys': [
        'F2-101',
        'F2-102',
        'F2-103',
        'F2-104',
        'F2-105',
        'F2-106',
        'F2-107',
    ],
    'expected_child_keys': [f'F2-107-{index}' for index in range(1, 19)],
}

V231_STORE_CONFIG = {
    **V230_STORE_CONFIG,
    'output': PKG_ROOT / 'fixtures/schema-store-daily-v2.3.1.js',
    'version': '2.3.1',
    'title': '门店日报 V2.3.1',
    'expected_record_count': 28,
    'expected_top_keys': [
        'F2-101',
        'F2-102',
        'F2-103',
        'F2-104',
        'F2-105',
        'F2-106',
        'F2-107',
        'F2-108',
        'F2-109',
        'F2-110',
    ],
}

STRICT_STORE_CONFIGS = {
    '2.3.0': V230_STORE_CONFIG,
    '2.3.1': V231_STORE_CONFIG,
}
STRICT_STORE_VERSIONS = set(STRICT_STORE_CONFIGS)


def resolve_sheet_config(sheet: str, version: str = '2.1.1') -> dict:
    """按版本返回独立配置,避免 CLI 调整污染全局默认值。"""
    if version in STRICT_STORE_CONFIGS:
        if sheet != 'store':
            raise ValueError(f'V{version} currently supports --sheet store only')
        return copy.deepcopy(STRICT_STORE_CONFIGS[version])
    if version != '2.1.1':
        raise ValueError(f'unsupported schema version: {version}')
    cfg = copy.deepcopy(SHEET_CONFIG[sheet])
    cfg.update({
        'exact_sheet': False,
        'classify_styles': True,
        'version': '2.1.1',
        'title': f"{'驻店' if sheet == 'staff' else '门店'}日报 V2.1.1",
    })
    return cfg

TYPE_MAP = {
    '单选框': 'radio',
    '数值输入框': 'numberInput',
    '多行文本输入框': 'textarea',
    '分组': 'group',
    '子表单': 'subform',
    '分割线': 'divider',
    '选择器': 'select',
    '单行文本输入框': 'input',
    '日期时间': 'date',
    '级联选择': 'carBrandSelect',
}


def load_baseline_js(path: Path) -> dict[str, dict]:
    """从 indexed JS fixture 扁平化 key → field(含嵌套子字段)。"""
    code = f"""
    const m = require({json.dumps(str(path).replace(chr(92), '/'))});
    const list = Object.keys(m).sort((a,b)=>+a-+b).map(k=>m[k]);
    function walk(field, out) {{
      if (!field || !field.key) return;
      out[field.key] = field;
      if (Array.isArray(field.children)) {{
        for (const ch of field.children) {{
          if (Array.isArray(ch)) {{
            for (const c of ch) walk(c, out);
          }} else {{
            walk(ch, out);
          }}
        }}
      }}
    }}
    const map = {{}};
    for (const f of list) walk(f, map);
    console.log(JSON.stringify(map));
    """
    result = subprocess.run(
        ['node', '-e', code],
        capture_output=True,
        text=True,
        encoding='utf-8',
        cwd=str(PKG_ROOT.parent),
    )
    if result.returncode != 0:
        raise RuntimeError(result.stderr or 'baseline load failed')
    return json.loads(result.stdout)


def col_index(ref: str) -> int:
    col = ''.join(ch for ch in ref if ch.isalpha())
    num = 0
    for ch in col:
        num = num * 26 + ord(ch) - 64
    return num - 1


def parse_styles(z: zipfile.ZipFile):
    styles = ET.fromstring(z.read('xl/styles.xml'))
    fills = []
    for fill in styles.findall('.//m:fills/m:fill', NS):
        pattern = fill.find('m:patternFill', NS)
        if pattern is None:
            fills.append(None)
            continue
        fg = pattern.find('m:fgColor', NS)
        rgb = None
        if fg is not None and fg.get('rgb'):
            h = fg.get('rgb')
            if len(h) == 8:
                h = h[2:]
            rgb = tuple(int(h[i : i + 2], 16) for i in (0, 2, 4))
        fills.append(rgb)

    fonts = [{'strike': f.find('m:strike', NS) is not None} for f in styles.findall('.//m:fonts/m:font', NS)]
    xfs = [
        (int(xf.get('fontId', 0)), int(xf.get('fillId', 0)))
        for xf in styles.findall('.//m:cellXfs/m:xf', NS)
    ]
    return fills, fonts, xfs


def read_shared_strings(z: zipfile.ZipFile) -> list[str]:
    if 'xl/sharedStrings.xml' not in z.namelist():
        return []
    ss = ET.fromstring(z.read('xl/sharedStrings.xml'))
    out = []
    for si in ss.findall('.//m:si', NS):
        texts = [(t.text or '') for t in si.findall('.//m:t', NS)]
        out.append(''.join(texts))
    return out


def cell_text(cell, shared: list[str]) -> str:
    t = cell.get('t')
    v = cell.find('m:v', NS)
    if v is None:
        return ''
    if t == 's':
        return shared[int(v.text)]
    return v.text or ''


def classify_row(row, xfs, fonts, fills, shared: list[str]) -> tuple[str | None, str]:
    key = ''
    classes = set()
    for cell in row.findall('m:c', NS):
        ref = cell.get('r', '')
        if ref.startswith('A'):
            key = cell_text(cell, shared)
        style_id = cell.get('s')
        if style_id is None:
            classes.add('normal')
            continue
        font_id, fill_id = xfs[int(style_id)]
        if fonts[font_id]['strike']:
            classes.add('strike')
        elif fills[fill_id] == PURPLE_RGB:
            classes.add('purple')
        else:
            classes.add('normal')
    if not key.startswith('F'):
        return None, key
    if 'strike' in classes:
        return 'remove', key
    if 'purple' in classes:
        return 'purple', key
    return 'keep', key


def infer_base_scene_from_scene_text(scene_text: str) -> list[int]:
    """显隐列为空时,从业务大类列推断 baseSceneCode。"""
    codes: list[int] = []
    text = scene_text or ''
    if '延保' in text:
        codes.extend([110201, 110202])
    if '权益' in text:
        codes.extend([110101, 110102])
    if '轻改' in text:
        codes.extend([100101, 100102, 100103])
    if '二手车' in text:
        codes.append(120101)
    return sorted(set(codes))


def read_sheet_rows(
    xlsx: Path,
    sheet_filter: str,
    exact_sheet: bool = False,
    classify_styles: bool = True,
) -> tuple[list[str], list[dict]]:
    with zipfile.ZipFile(xlsx) as z:
        if classify_styles:
            fills, fonts, xfs = parse_styles(z)
        else:
            fills, fonts, xfs = [], [], []
        shared_strings = read_shared_strings(z)
        wb = ET.fromstring(z.read('xl/workbook.xml'))
        sheets = [
            (
                s.get('name'),
                s.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id'),
            )
            for s in wb.findall('.//m:sheet', NS)
        ]
        rels = ET.fromstring(z.read('xl/_rels/workbook.xml.rels'))
        rid_map = {r.get('Id'): r.get('Target') for r in rels}

        for name, rid in sheets:
            matches = name == sheet_filter if exact_sheet else sheet_filter in name
            if not matches:
                continue
            target = rid_map[rid]
            if not target.startswith('xl/'):
                target = 'xl/' + target
            sh = ET.fromstring(z.read(target))
            header: list[str] = []
            records: list[dict] = []
            for row in sh.findall('.//m:sheetData/m:row', NS):
                cells: dict[int, str] = {}
                for cell in row.findall('m:c', NS):
                    cells[col_index(cell.get('r', 'A1'))] = cell_text(cell, shared_strings)
                if not cells:
                    continue
                max_col = max(cells)
                values = [cells.get(i, '') for i in range(max_col + 1)]
                if not header:
                    header = values
                    continue
                record = {
                    header[i]: values[i] if i < len(values) else ''
                    for i in range(len(header))
                }
                if classify_styles:
                    row_type, key = classify_row(row, xfs, fonts, fills, shared_strings)
                else:
                    key = (record.get('编号') or '').strip()
                    row_type = 'keep' if key.startswith('F') else None
                if row_type is None:
                    continue
                record['_rowType'] = row_type
                record['_key'] = key
                records.append(record)
            return header, records
    raise ValueError(f'sheet not found: {sheet_filter}')


def select_v230_records(records: list[dict], min_root_number: int = 101) -> list[dict]:
    """仅保留 F2-101 起且状态为“在用”的新版记录。"""
    selected: list[dict] = []
    for record in records:
        key = (record.get('_key') or record.get('编号') or '').strip()
        match = re.fullmatch(r'F2-(\d+)(?:-\d+)?', key)
        if not match or int(match.group(1)) < min_root_number:
            continue
        status = (
            record.get('状态')
            or record.get('使用状态')
            or record.get('是否启用')
            or ''
        ).strip()
        if status != '在用':
            continue
        current = copy.deepcopy(record)
        current['_key'] = key
        # V2.3.0 不依赖行样式,所有入选行都重新解析。
        current['_rowType'] = 'purple'
        selected.append(current)
    return selected


def parse_scene_type(text: str) -> list[int]:
    text = (text or '').strip()
    if not text or text == '不限':
        return []
    parts = [p.strip() for p in re.split(r'[,,]', text) if p.strip()]
    result: list[int] = []
    for p in parts:
        if p in ('延保', '权益'):
            result.append(0)
        elif p == '轻改':
            result.append(1)
        elif p == '二手车':
            result.append(7)
    return sorted(set(result))


def parse_brand_restriction(text: str) -> tuple[list[int], list[int]]:
    """返回 (brandId, filterBrandId)。

    「岚图,其他品牌」为 OR 语义:brandId 留空,filterBrandId 仅含五界;
    运行时 brandSpec 在经营品牌全部落在五界内时隐藏,岚图或其它品牌任一即可显示。
    """
    text = (text or '').strip()
    if not text or text == '不限':
        return [], []
    parts = [p.strip() for p in re.split(r'[,,]', text) if p.strip()]
    has_other = '其他品牌' in parts
    named = [p for p in parts if p in BRAND_NAME_TO_ID]
    brand_ids = [BRAND_NAME_TO_ID[p] for p in named]

    if has_other and not named:
        return [], list(FILTER_BRAND_IDS)
    if has_other and named:
        # 岚图 or 其他品牌:OR 语义,仅用 filterBrandId 隐藏纯五界门店
        return [], list(FIVE_REALM_IDS)
    return brand_ids, []


def extract_scene_codes(visibility: str) -> list[int]:
    """从显隐文案提取 baseSceneCode;token 按长度降序 + 边界匹配,避免 2.1.1 误命中 1.1。"""
    codes: list[int] = []
    for token in sorted(BASE_SCENE_CODE.keys(), key=len, reverse=True):
        pattern = r'(?<![\d.])' + re.escape(token) + r'(?![\d.])'
        if re.search(pattern, visibility):
            codes.append(BASE_SCENE_CODE[token])
    return sorted(set(codes))


def parse_visibility(visibility: str, attendance_key: str | None) -> tuple[list[int], dict]:
    visibility = (visibility or '').strip()
    rules: dict = {}
    base_scene: list[int] = []

    if not visibility or visibility == '-':
        return base_scene, rules

    if '场景' in visibility:
        base_scene = extract_scene_codes(visibility)

    if attendance_key and ('今日出勤=在岗' in visibility or '今日出勤 = 在岗' in visibility):
        rules['keys'] = [attendance_key]
        rules['result'] = 'val1 == "在岗"'

    return base_scene, rules


def parse_other_rules(text: str, field: dict) -> None:
    text = (text or '').strip()
    if not text or text == '-':
        return
    rules = field.setdefault('rules', {})
    if '大于等于0的整数' in text or '非负整数' in text:
        rules['min'] = 0
        rules['integer'] = True
    elif '大于等于0的数值' in text:
        rules['min'] = 0
        rules['decimal'] = True
    max_length = re.search(r'(?:不超过|最多|最大)\s*(\d+)\s*(?:字|位)', text)
    if max_length:
        rules['maxLength'] = int(max_length.group(1))
    if '11位数字' in text or '11位手机号' in text:
        field['type'] = 'phoneInput'
        rules['maxLength'] = 11
    if field.get('type') == 'select' and '多选' in text:
        field['type'] = 'multipleSelect'
    if field.get('type') == 'date' and any(
        token in text
        for token in ('当天及以前', '今天及以前', '当前及过去日期')
    ):
        rules['maxDate'] = 'today'
        rules['format'] = 'date'
    if field.get('type') == 'carBrandSelect' and any(
        token in text for token in ('4层', '4级', '四级')
    ):
        rules['level'] = 4
    if '扫描' in text or '识别按钮' in text:
        field['prefixComponent'] = 'scan'
    if '后置单位"%"' in text or '后置显示文字"%"' in text or '单位"%"' in text:
        field['unit'] = '%'
    if '后置显示文字"元"' in text or '单位"元"' in text:
        field['unit'] = '元'
    comparison = re.search(
        r'若数值大于\s*[\[【]?\s*(F\d+(?:-\d+)*)[^\]】]*[\]】]?\s*则提示[“"]([^”"]+)[”"]',
        text,
    )
    if comparison:
        message = comparison.group(2).replace('不可不大于', '不可大于')
        rules.setdefault('comparisons', []).append({
            'operator': 'lte',
            'fieldKey': comparison.group(1),
            'message': message,
        })


def parse_options(
    options_text: str,
    field: dict,
    dynamic_store_multiple: bool = True,
) -> None:
    text = (options_text or '').strip()
    if not text or text == '-':
        return
    if re.match(r'^固定值(?:\s*[::]|\s*[\r\n])', text):
        raw = re.sub(r'^固定值(?:\s*[::])?', '', text, count=1).strip()
        option_items: list[dict] = []
        for item in re.split(r'[\r\n,,]+', raw):
            item = item.strip()
            if not item:
                continue
            item = re.sub(r'^[-–—]\s*', '', item)
            item = re.sub(r'^选项\s*\d+\s*[::]\s*', '', item)
            annotated = re.match(r'^(.+?)\s*[\((](.+)[\))]\s*$', item)
            if annotated:
                item = annotated.group(1).strip()
            option = {'label': item, 'value': item}
            option_items.append(option)
        field['options'] = option_items
    if '当前门店驻店人员' in text:
        field['optionsKey'] = 'storeStaffList'
        field['type'] = 'multipleSelect' if dynamic_store_multiple else 'select'
        field['options'] = []
    if '当前门店4S店成员' in text:
        field['optionsKey'] = '4sStaffList'
        field['type'] = 'select'
        field['options'] = []


def parse_required(text: str) -> bool:
    return '☑' in (text or '') or text.strip().upper() == 'Y'


def parse_default_value(text: str, field_type: str):
    text = (text or '').strip()
    if text == '-' or text == '':
        return None
    if field_type == 'numberInput':
        try:
            if '.' in text:
                return float(text)
            return int(text)
        except ValueError:
            return 0
    return text


def is_source_default_rule(text: str) -> bool:
    text = (text or '').strip()
    return any(
        token in text
        for token in ('每月首日', '最近一次提交', '当前用户')
    )


def is_container_row(key: str, comp_type: str) -> bool:
    return comp_type in ('group', 'subform') and key.count('-') == 1


def parent_key(key: str) -> str | None:
    parts = key.split('-')
    if len(parts) <= 2:
        return None
    return '-'.join(parts[:2])


def row_to_field(
    record: dict,
    sheet_kind: str,
    attendance_key: str | None,
    version: str = '2.1.1',
) -> dict:
    if sheet_kind == 'staff':
        scene_text = record.get('业务大类限制', '')
        brand_text = record.get('门店经营品牌限制', '')
        visibility = record.get('显隐条件', '')
        options_text = record.get('选项数据', '')
        other_rules = record.get('其他规则', '')
    else:
        scene_text = record.get('业务大类限制', '')
        brand_text = record.get('门店经营品牌限制', '')
        visibility = record.get('显隐条件', '')
        options_text = record.get('选项数据', '')
        other_rules = record.get('其他规则', '')

    key = record['_key']
    comp_name = record.get('表单组件名称', '')
    comp_type_raw = record.get('表单组件类型', '')
    field_type = TYPE_MAP.get(comp_type_raw, 'numberInput')

  # 选择器默认 select,options 解析可能改为 multipleSelect
    field: dict = {
        'label': comp_name,
        'sortNum': str(record.get('排序', '')).strip(),
        'key': key,
        'type': field_type,
        'required': parse_required(record.get('必填', '')),
        'sceneType': parse_scene_type(scene_text),
        'brandId': [],
        'baseSceneCode': [],
        'rules': {},
    }

    brand_id, filter_brand = parse_brand_restriction(brand_text)
    field['brandId'] = brand_id
    if filter_brand:
        field['filterBrandId'] = filter_brand

    base_scene, vis_rules = parse_visibility(visibility, attendance_key)
    if not base_scene:
        base_scene = infer_base_scene_from_scene_text(scene_text)
    field['baseSceneCode'] = base_scene
    if vis_rules:
        field['rules'].update(vis_rules)

    parse_options(
        options_text,
        field,
        dynamic_store_multiple=version not in STRICT_STORE_VERSIONS,
    )
    parse_other_rules(other_rules, field)

    default_text = record.get('默认值', '')
    source_default = version in STRICT_STORE_VERSIONS and is_source_default_rule(default_text)
    default_val = None if source_default else parse_default_value(default_text, field['type'])
    if default_val is not None:
        field['value'] = default_val
    elif not source_default and field['type'] == 'numberInput' and 'value' not in field:
        field['value'] = 0
    elif field['type'] == 'textarea':
        field.setdefault('value', '')

    # divider 硬编码(与 V2.0 引擎契约一致)
    if field['type'] == 'divider':
        field['rules'] = {}
        if key == 'F2-94':
            field['sceneType'] = [0, 0]
            field['ybCode'] = [110201, 110202]
            field['qyCode'] = [110101, 110102]
        elif key == 'F2-91':
            field['isYB'] = True
            field['ybCode'] = [110201, 110202]
            field['qyCode'] = [110101, 110102]
        elif key == 'F2-92':
            field['isQY'] = True
            field['ybCode'] = [110201, 110202]
            field['qyCode'] = [110101, 110102]
        elif key == 'F2-93':
            field['qgCode'] = [100101, 100102, 100103]

    # F2-1 / F2-2 若从 Excel 解析需补全(keep 行走 baseline)
    if key == 'F2-1':
        field['completeFun'] = {'key': 'F2-2', 'result': '(list.length)'}
    if key == 'F2-2':
        field['disabledFun'] = {'keys': ['F2-1'], 'result': 'val1 != null'}

    return field


def build_children_rules(children: list[dict]) -> dict:
    rules_map: dict = {}
    for child in children:
        if child.get('type') != 'numberInput':
            continue
        child_rules = {'min': 0}
        if child.get('unit') == '元' or child.get('rules', {}).get('decimal'):
            child_rules['decimal'] = True
        else:
            child_rules['integer'] = True
        rules_map[child['key']] = child_rules
    return rules_map


V230_STORE_CHILD_SHOW_RULES = {
    'F2-107-12': {
        'keys': ['F2-107-7'],
        'result': "val1 && Array.isArray(val1) && (val1.includes('1') || val1.includes('3'))",
    },
    'F2-107-13': {
        'keys': ['F2-107-7'],
        'result': "val1 && Array.isArray(val1) && val1.includes('3')",
    },
    'F2-107-14': {
        'keys': ['F2-107-13'],
        'result': "val1 == '否'",
    },
    'F2-107-15': {
        'keys': ['F2-107-7'],
        'result': "val1 && Array.isArray(val1) && val1.includes('1')",
    },
    'F2-107-16': {
        'keys': ['F2-107-15'],
        'result': "val1 == '否'",
    },
    'F2-107-17': {
        'keys': ['F2-107-7'],
        'result': "!Array.isArray(val1) || (val1 && !val1.includes('1'))",
    },
    'F2-107-18': {
        'keys': ['F2-107-7'],
        'result': "val1 && Array.isArray(val1) && val1.includes('1')",
    },
}

V230_SHOW_RULE_CONTEXT_KEYS = {'$sceneCodes', '$brandIds'}
OPTION_VISIBILITY_KEYS = {'baseSceneCode', 'brandId', 'filterBrandId'}
V230_CUSTOMER_SOURCE_VALUE_BY_LABEL = {
    '销售端引流-售前': '0',
    '交付端引流-售前': '3',
    '门店引流-售前': '0',
    '门店引流-售后': '1',
}
V230_CUSTOMER_TAG_VALUE_BY_LABEL = {
    '已触客': '1',
    '已拉群': '2',
    '已交付引荐': '3',
    '首保维保客户': '4',
    '事故车客户': '5',
}


def _includes_any(value_name: str, values: list[int]) -> str:
    return ' || '.join(
        f"{value_name}.includes('{value}')"
        for value in values
    )


def build_v230_delivery_date_show_rule() -> dict:
    """按当前 env 品牌映射生成场景×品牌×客户来源三参数显隐规则。"""
    boutique_scenes = [100101, 100102, 100103]
    warranty_equity_scenes = [110101, 110102, 110201, 110202]
    boutique_expr = f"({_includes_any('val1', boutique_scenes)})"
    warranty_equity_expr = f"({_includes_any('val1', warranty_equity_scenes)})"
    five_realm_expr = f"({_includes_any('val2', FIVE_REALM_IDS)})"
    result = (
        "val1 && Array.isArray(val1) && val2 && Array.isArray(val2) && "
        f"(({boutique_expr} && {five_realm_expr} && "
        "val3 == '3') || "
        f"({boutique_expr} && !{five_realm_expr} && "
        "(val3 == '0' || val3 == '3')) || "
        f"({warranty_equity_expr} && val3 == '0'))"
    )
    return {
        'keys': ['$sceneCodes', '$brandIds', 'F2-107-3'],
        'result': result,
    }


def build_v230_store_child_show_rules() -> dict:
    rules = copy.deepcopy(V230_STORE_CHILD_SHOW_RULES)
    return {
        'F2-107-4': build_v230_delivery_date_show_rule(),
        **rules,
    }


def apply_v230_customer_tag_option_visibility(options: list[dict]) -> None:
    """给 F2-107-7 选项写入声明式场景×主营品牌显隐配置。"""
    light_scenes = [100101, 100102, 100103]
    five_realm_labels = {'已拉群', '首保维保客户', '事故车客户'}
    for option in options:
        label = option.get('label')
        mapped_value = V230_CUSTOMER_TAG_VALUE_BY_LABEL.get(label)
        if mapped_value is not None:
            option.pop('id', None)
            option['value'] = mapped_value
        if label in five_realm_labels:
            option['baseSceneCode'] = light_scenes.copy()
            option['brandId'] = FIVE_REALM_IDS.copy()
        elif label == '已交付引荐':
            option['baseSceneCode'] = light_scenes.copy()
            option['filterBrandId'] = FIVE_REALM_IDS.copy()
            option['matchEffect'] = 'exclude'


def apply_v230_customer_source_values(options: list[dict]) -> None:
    """客户来源按 App 协议保存数字 value,不输出 id。"""
    for option in options:
        label = option.get('label')
        mapped_value = V230_CUSTOMER_SOURCE_VALUE_BY_LABEL.get(label)
        if mapped_value is None:
            continue
        option.pop('id', None)
        option['value'] = mapped_value
        if label in {'销售端引流-售前', '交付端引流-售前'}:
            option['baseSceneCode'] = [100101, 100102, 100103]
        elif label == '门店引流-售前':
            option['baseSceneCode'] = [110101, 110102, 110201, 110202]


def build_v230_children_rules(children: list[dict]) -> dict:
    """为 subform 生成引擎现有的父级子字段校验索引。"""
    allowed = {'min', 'integer', 'decimal', 'maxLength', 'maxDate', 'format', 'level'}
    result: dict = {}
    for child in children:
        child_rules = {
            key: value
            for key, value in (child.get('rules') or {}).items()
            if key in allowed
        }
        if child_rules.get('maxDate') == 'today':
            child_rules['maxDate'] = 'new Date()'
        if child_rules:
            result[child['key']] = child_rules
    return result


def assemble_v230_list(records: list[dict], sheet_cfg: dict) -> list[dict]:
    """不使用 baseline,将 V2.3.x 入选行组装为顶层字段与 subform。"""
    selected = select_v230_records(records, sheet_cfg.get('min_root_number', 101))
    flat: dict[str, dict] = {}
    for record in selected:
        key = record['_key']
        if key in flat:
            raise ValueError(f'duplicate V2.3.0 key: {key}')
        component_type = (record.get('表单组件类型') or '').strip()
        if component_type not in TYPE_MAP:
            raise ValueError(f'unknown component type for {key}: {component_type}')
        field = row_to_field(
            record,
            'store',
            sheet_cfg.get('attendance_key'),
            version=sheet_cfg['version'],
        )
        if component_type == '选择器':
            mode_text = (record.get('其他规则') or '').strip()
            has_single = '单选' in mode_text
            has_multiple = '多选' in mode_text
            if has_single == has_multiple:
                raise ValueError(
                    f'{key} selector mode must be exactly one of 单选/多选: '
                    f'{mode_text or "<empty>"}'
                )
            expected_type = 'multipleSelect' if has_multiple else 'select'
            if field.get('type') != expected_type:
                raise ValueError(
                    f'{key} selector mode {mode_text} resolved to {field.get("type")}'
                )
            options_key = field.get('optionsKey')
            options = field.get('options')
            has_static_options = isinstance(options, list) and bool(options)
            has_dynamic_options = options_key in {'storeStaffList', '4sStaffList'}
            if not has_static_options and not has_dynamic_options:
                raise ValueError(
                    f'{key} selector options could not be resolved: '
                    f'{record.get("选项数据") or "<empty>"}'
                )
        flat[key] = field

    top_fields: list[dict] = []
    for key, field in list(flat.items()):
        pk = parent_key(key)
        if pk is None:
            top_fields.append(field)
            continue
        parent = flat.get(pk)
        if parent is None:
            raise ValueError(f'child {key} missing container {pk}')
        if parent.get('type') != 'subform':
            raise ValueError(f'child {key} parent {pk} is not a subform')

    for parent in top_fields:
        if parent.get('type') != 'subform':
            continue
        children = [
            field
            for key, field in flat.items()
            if parent_key(key) == parent['key']
        ]
        children.sort(key=lambda child: int(child.get('sortNum') or 0))
        customer_tags = next(
            (child for child in children if child.get('key') == 'F2-107-7'),
            None,
        )
        if customer_tags is not None:
            customer_tags['optionsKey'] = 'options'
            apply_v230_customer_tag_option_visibility(customer_tags.get('options') or [])
        customer_source = next(
            (child for child in children if child.get('key') == 'F2-107-3'),
            None,
        )
        if customer_source is not None:
            apply_v230_customer_source_values(customer_source.get('options') or [])
        product_categories = next(
            (child for child in children if child.get('key') == 'F2-107-12'),
            None,
        )
        if product_categories is not None:
            product_categories['optionsKey'] = 'options'
        parent['children'] = [children]
        parent['childrenRules'] = build_v230_children_rules(children)
        child_keys = {child['key'] for child in children}
        child_show_rules = build_v230_store_child_show_rules()
        parent['childrenShowRules'] = {
            key: copy.deepcopy(rule)
            for key, rule in child_show_rules.items()
            if key in child_keys
        }
        if parent.get('key') == 'F2-107':
            parent['validateDuplicates'] = ['F2-107-2']

    top_fields.sort(key=lambda field: int(field.get('sortNum') or 0))
    return top_fields


def validate_v230_shape(records: list[dict], fields: list[dict], sheet_cfg: dict) -> None:
    expected_count = sheet_cfg.get('expected_record_count')
    if expected_count is not None and len(records) != expected_count:
        raise ValueError(
            f"{sheet_cfg['sheet_filter']} expected {expected_count} active records "
            f'from F2-{sheet_cfg.get("min_root_number", 101)}, got {len(records)}'
        )
    expected_top_keys = sheet_cfg.get('expected_top_keys') or []
    actual_top_keys = [field['key'] for field in fields]
    if expected_top_keys and actual_top_keys != expected_top_keys:
        raise ValueError(
            f"{sheet_cfg['sheet_filter']} top-level keys mismatch: {actual_top_keys}"
        )
    all_keys = actual_top_keys[:]
    for field in fields:
        for row in field.get('children') or []:
            if isinstance(row, list):
                all_keys.extend(child['key'] for child in row)
    if len(all_keys) != len(set(all_keys)):
        raise ValueError(f"{sheet_cfg['sheet_filter']} contains duplicate generated keys")

    expected_child_keys = sheet_cfg.get('expected_child_keys') or []
    subform = next((field for field in fields if field.get('key') == 'F2-107'), None)
    actual_child_keys = []
    if subform:
        for row in subform.get('children') or []:
            if isinstance(row, list):
                actual_child_keys.extend(child.get('key') for child in row)
    if expected_child_keys and actual_child_keys != expected_child_keys:
        raise ValueError(
            f"{sheet_cfg['sheet_filter']} child keys mismatch: {actual_child_keys}"
        )

    child_key_set = set(actual_child_keys)
    duplicate_keys = (subform or {}).get('validateDuplicates') or []
    if not isinstance(duplicate_keys, list):
        raise ValueError('validateDuplicates must be a list for F2-107')
    for duplicate_key in duplicate_keys:
        if duplicate_key not in child_key_set:
            raise ValueError(
                f'validateDuplicates key missing from F2-107: {duplicate_key}'
            )
    for target, rule in (subform or {}).get('childrenShowRules', {}).items():
        if target not in child_key_set:
            raise ValueError(f'childrenShowRules target missing from F2-107: {target}')
        for dependency in rule.get('keys') or []:
            if (
                dependency not in child_key_set
                and dependency not in V230_SHOW_RULE_CONTEXT_KEYS
            ):
                raise ValueError(
                    f'childrenShowRules dependency missing from F2-107: {dependency}'
                )

    for child in (
        child
        for row in (subform or {}).get('children') or []
        if isinstance(row, list)
        for child in row
    ):
        for option in child.get('options') or []:
            if not isinstance(option, dict):
                continue
            for prop in OPTION_VISIBILITY_KEYS:
                if prop in option and not isinstance(option[prop], list):
                    raise ValueError(
                        f'option visibility {prop} must be a list for {child.get("key")}'
                    )
            if 'matchEffect' not in option:
                continue
            if option['matchEffect'] not in {'include', 'exclude'}:
                raise ValueError(
                    f'option visibility matchEffect unsupported for {child.get("key")}'
                )
            if not any(
                isinstance(option.get(prop), list) and option[prop]
                for prop in OPTION_VISIBILITY_KEYS
            ):
                raise ValueError(
                    f'option visibility matchEffect requires conditions '
                    f'for {child.get("key")}'
                )


def assemble_list(records: list[dict], baseline_map: dict[str, dict], sheet_cfg: dict) -> list[dict]:
    attendance_key = sheet_cfg.get('attendance_key')
    sheet_kind = 'staff' if 'staff' in sheet_cfg['form_code'] else 'store'

    flat: dict[str, dict] = {}
    remove_keys: set[str] = set()

    for record in records:
        key = record['_key']
        row_type = record['_rowType']
        if row_type == 'remove':
            remove_keys.add(key)
            continue
        if row_type == 'keep':
            if key not in baseline_map:
                raise KeyError(f'keep row {key} missing in baseline')
            flat[key] = copy.deepcopy(baseline_map[key])
            continue
        flat[key] = row_to_field(record, sheet_kind, attendance_key)

    # 剔除嵌套在 baseline 拷贝里但已删除的子 key
    for key in list(flat.keys()):
        field = flat[key]
        if field.get('type') == 'group' and isinstance(field.get('children'), list):
            field['children'] = [
                ch for ch in field['children']
                if ch.get('key') not in remove_keys
            ]
            field['childrenRules'] = {
                k: v for k, v in (field.get('childrenRules') or {}).items()
                if k not in remove_keys
            }
        if field.get('type') == 'subform' and isinstance(field.get('children'), list):
            new_rows = []
            for row in field['children']:
                if not isinstance(row, list):
                    continue
                new_rows.append([c for c in row if c.get('key') not in remove_keys])
            field['children'] = new_rows
            field['childrenRules'] = {
                k: v for k, v in (field.get('childrenRules') or {}).items()
                if k not in remove_keys
            }

    # 将紫色解析的叶子字段合并进容器
    for key, field in list(flat.items()):
        pk = parent_key(key)
        if pk is None or pk == key:
            continue
        if pk not in flat:
            continue
        parent = flat[pk]
        if parent.get('type') == 'group':
            children = parent.setdefault('children', [])
            replaced = False
            for i, ch in enumerate(children):
                if ch.get('key') == key:
                    children[i] = field
                    replaced = True
                    break
            if not replaced:
                children.append(field)
            del flat[key]
        elif parent.get('type') == 'subform':
            children = parent.setdefault('children', [[]])
            if not children:
                children.append([])
            row = children[0]
            replaced = False
            for i, ch in enumerate(row):
                if ch.get('key') == key:
                    row[i] = field
                    replaced = True
                    break
            if not replaced:
                row.append(field)
            del flat[key]

    # 顶层 list:仅保留无 parent 或 parent 不在 flat 的字段
    top_keys = [k for k in flat if parent_key(k) is None or parent_key(k) not in flat]

    for key in top_keys:
        field = flat[key]
        if field.get('type') == 'group' and field.get('children'):
            field['children'] = sorted(field['children'], key=lambda c: int(c.get('sortNum', 0)))
            field['childrenRules'] = build_children_rules(field['children'])
        if field.get('type') == 'subform' and field.get('children'):
            for row in field['children']:
                if isinstance(row, list):
                    row.sort(key=lambda c: int(c.get('sortNum', 0)))
            field['childrenRules'] = build_children_rules(
                [c for row in field['children'] if isinstance(row, list) for c in row]
            )

    top_fields = [flat[k] for k in top_keys]
    top_fields.sort(key=lambda f: int(f.get('sortNum', 0)))
    return top_fields


def build_visibility_map(records: list[dict]) -> dict[str, str]:
    """Excel 显隐条件列,供新增字段生成行内备注。"""
    out: dict[str, str] = {}
    for record in records:
        if record.get('_rowType') == 'remove':
            continue
        vis = (record.get('显隐条件') or '').strip()
        if vis and vis != '-':
            out[record['_key']] = vis
    return out


def load_comment_sidecar() -> dict:
    path = PKG_ROOT / 'fixtures/template-field-comments.json'
    return json.loads(path.read_text(encoding='utf-8'))


def visibility_to_inline_comment(text: str) -> str:
    text = (text or '').strip()
    if not text or text == '-':
        return ''
    return '\n'.join(f'//{line}' for line in text.splitlines())


COMMENTS_JSON = PKG_ROOT / 'fixtures/template-field-comments.json'

# 字段属性输出顺序(对齐 V2.0 业务配置粘贴格式)
FIELD_PROP_ORDER = [
    'label', 'sortNum', 'key', 'type', 'required', 'sceneType', 'brandId',
    'baseSceneCode', 'options',
    'optionsKey', 'value', 'prefixComponent',
    'unit', 'rules',
    'filterBrandId', 'completeFun', 'disabledFun', 'isYB', 'isQY',
    'ybCode', 'qyCode', 'qgCode', 'childrenRules', 'childrenShowRules',
    'validateDuplicates', 'children',
]

DIVIDER_PROP_ORDER = [
    'label', 'sortNum', 'key', 'type', 'required', 'sceneType', 'brandId',
    'baseSceneCode', 'isYB', 'isQY', 'ybCode', 'qyCode', 'qgCode', 'rules',
]


def _js_str(value: str) -> str:
    escaped = (
        value.replace('\\', '\\\\')
        .replace("'", "\\'")
        .replace('\r', '\\r')
        .replace('\n', '\\n')
        .replace('\t', '\\t')
        .replace('\u2028', '\\u2028')
        .replace('\u2029', '\\u2029')
    )
    return "'" + escaped + "'"


def _js_double_str(value: str) -> str:
    escaped = (
        value.replace('\\', '\\\\')
        .replace('"', '\\"')
        .replace('\r', '\\r')
        .replace('\n', '\\n')
        .replace('\t', '\\t')
        .replace('\u2028', '\\u2028')
        .replace('\u2029', '\\u2029')
    )
    return '"' + escaped + '"'


def _js_value(value, indent: int, inline_comment: str = '') -> str:
    pad = ' ' * indent
    suffix = f' {inline_comment}' if inline_comment else ''
    if isinstance(value, str):
        if value == '(list.length)':
            return f'"(list.length)"{suffix}'
        return f'{_js_str(value)}{suffix}'
    if isinstance(value, bool):
        return f'{str(value).lower()}{suffix}'
    if isinstance(value, int):
        return f'{value}{suffix}'
    if isinstance(value, float):
        if value == int(value):
            return f'{int(value)}{suffix}'
        return f'{value}{suffix}'
    if value is None:
        return f'null{suffix}'
    if isinstance(value, list):
        if not value:
            return f'[]{suffix}'
        inner = ', '.join(_js_value(v, indent, '') for v in value)
        return f'[{inner}]{suffix}'
    if isinstance(value, dict):
        return _js_object(value, indent, {}, {}) + (f' {inline_comment}' if inline_comment else '')
    return f'{json.dumps(value, ensure_ascii=False)}{suffix}'


def _ordered_field_items(field: dict, omit: set[str]) -> list[tuple[str, object]]:
    prop_order = DIVIDER_PROP_ORDER if field.get('type') == 'divider' else FIELD_PROP_ORDER
    seen = set()
    items: list[tuple[str, object]] = []
    for key in prop_order:
        if key in field and key not in omit:
            items.append((key, field[key]))
            seen.add(key)
    for key, val in field.items():
        if key not in seen and key not in omit:
            items.append((key, val))
    return items


def _emit_comment_line(inner_pad: str, text: str) -> str:
    return f'{inner_pad}{text.rstrip(",")}'


def _append_indented_comment(lines: list[str], inner_pad: str, text: str) -> None:
    lines.extend(f'{inner_pad}{line}' for line in text.splitlines())


def _js_object(
    obj: dict,
    indent: int,
    field_comments: dict,
    visibility_map: dict[str, str],
    field_key: str | None = None,
) -> str:
    pad = ' ' * indent
    inner_pad = ' ' * (indent + 4)
    omit = set(field_comments.get('omitProps', []))
    prop_before: dict = field_comments.get('propBefore', {})
    prop_inline: dict = field_comments.get('propInline', {})
    prop_before_rules: list = field_comments.get('propBeforeRules', [])

    lines: list[str] = []
    visibility_used = False
    for prop, val in _ordered_field_items(obj, omit):
        for comment_line in prop_before.get(prop, []):
            lines.append(_emit_comment_line(inner_pad, comment_line) + ',')
        if prop == 'rules' and prop_before_rules:
            for comment_line in prop_before_rules:
                lines.append(_emit_comment_line(inner_pad, comment_line) + ',')

        sidecar_inline = prop_inline.get(prop, '')
        inline = sidecar_inline
        if not inline and field_key and not visibility_used:
            vis = visibility_map.get(field_key, '')
            if vis:
                if prop == 'baseSceneCode' and '场景' in vis:
                    inline = visibility_to_inline_comment(vis)
                    visibility_used = True
                elif prop == 'filterBrandId' and '门店经营品牌' in vis:
                    inline = visibility_to_inline_comment(vis)
                    visibility_used = True
                elif prop == 'brandId' and '门店经营品牌' in vis and 'filterBrandId' not in obj:
                    inline = visibility_to_inline_comment(vis)
                    visibility_used = True
                elif prop == 'rules' and ('今日出勤' in vis or 'F2-1' in vis):
                    inline = visibility_to_inline_comment(vis)
                    visibility_used = True

        if prop == 'children':
            lines.append(f'{inner_pad}children: {_js_children(val, indent + 4, visibility_map)},')
            continue
        if prop == 'childrenRules':
            lines.append(f'{inner_pad}childrenRules: {_js_children_rules(val, indent + 4)},')
            continue
        if prop == 'childrenShowRules':
            lines.append(
                f'{inner_pad}childrenShowRules: '
                f'{_js_children_show_rules(val, indent + 4)},'
            )
            continue
        if prop in ('completeFun', 'disabledFun') and isinstance(val, dict):
            lines.append(f'{inner_pad}{prop}: {_js_fun_obj(val, indent + 4)},')
            continue
        if prop == 'rules' and isinstance(val, dict):
            lines.append(f'{inner_pad}rules: {_js_rules(val, indent + 4)},')
            if inline:
                _append_indented_comment(lines, inner_pad, inline)
            continue
        if prop == 'options' and isinstance(val, list) and val and isinstance(val[0], dict):
            lines.append(f'{inner_pad}options: {_js_options(val, indent + 4)},')
            continue

        core = _js_value(val, indent + 4, '')
        if sidecar_inline:
            lines.append(f'{inner_pad}{prop}: {core}, {sidecar_inline},')
        else:
            lines.append(f'{inner_pad}{prop}: {core},')
            if inline:
                _append_indented_comment(lines, inner_pad, inline)

    return '{\n' + '\n'.join(lines) + f'\n{pad}}}'


def _js_fun_obj(obj: dict, indent: int, *, double_quote_result: bool = False) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    parts = []
    for k, v in obj.items():
        if k == 'result':
            if v == '(list.length)':
                parts.append(f'{inner}result: "(list.length)"')
            else:
                result = _js_double_str(v) if double_quote_result else _js_str(v)
                parts.append(f'{inner}result: {result}')
        else:
            parts.append(f'{inner}{k}: {_js_value(v, indent + 4)}')
    return '{\n' + ',\n'.join(parts) + f'\n{pad}}}'


def _js_rules(rules: dict, indent: int) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    order = ['min', 'integer', 'decimal', 'maxLength', 'keys', 'result']
    lines = []
    for k in order:
        if k not in rules:
            continue
        val = rules[k]
        if k == 'result':
            lines.append(f'{inner}result: {_js_str(val)},')
        elif k == 'keys':
            lines.append(f'{inner}keys: [{", ".join(_js_str(x) for x in val)}],')
        else:
            lines.append(f'{inner}{k}: {_js_value(val, indent + 4)},')
    for k, val in rules.items():
        if k in order:
            continue
        lines.append(f'{inner}{k}: {_js_value(val, indent + 4)},')
    if lines:
        lines[-1] = lines[-1].rstrip(',')
    if not lines:
        return '{}'
    return '{\n' + '\n'.join(lines) + f'\n{pad}}}'


def _js_options(options: list, indent: int) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    items = []
    for opt in options:
        props = []
        for key in (
            'label',
            'value',
            'baseSceneCode',
            'brandId',
            'filterBrandId',
            'matchEffect',
        ):
            if key not in opt:
                continue
            props.append(f'{inner}    {key}: {_js_value(opt[key], indent + 8)}')
        items.append(f'{inner}{{\n' + ',\n'.join(props) + f'\n{inner}}}')
    return '[\n' + ',\n'.join(items) + f'\n{pad}]'


def _js_children_show_rules(rules: dict, indent: int) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    lines = []
    for key, rule in rules.items():
        lines.append(
            f'{inner}{_js_str(key)}: '
            f'{_js_fun_obj(rule, indent + 4, double_quote_result=True)}'
        )
    if not lines:
        return '{}'
    return '{\n' + ',\n'.join(lines) + f'\n{pad}}}'


def _js_children_rules(rules: dict, indent: int) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    lines = []
    for k in sorted(rules.keys()):
        r = rules[k]
        if set(r).issubset({'min', 'integer', 'decimal'}):
            r_parts = [f'min: {r.get("min", 0)}']
            if r.get('decimal'):
                r_parts.append('decimal: true')
            else:
                r_parts.append('integer: true')
            rendered = f"{{ {', '.join(r_parts)} }}"
        else:
            rendered = _js_rules(r, indent + 4)
        lines.append(f"{inner}{_js_str(k)}: {rendered}")
    return '{\n' + ',\n'.join(lines) + f'\n{pad}}}'


def _js_children(children, indent: int, visibility_map: dict[str, str]) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    if not children:
        return '[]'
    # group: [child, child]; subform: [[child, ...]]
    if children and isinstance(children[0], list):
        row = children[0]
        row_lines = []
        for ch in row:
            fc = load_comment_sidecar()['fields'].get(ch.get('key', ''), {})
            row_lines.append(
                f'{inner}{_js_field(ch, indent + 4, fc, visibility_map)}'
            )
        return '[\n' + f'{inner}[\n' + ',\n\n'.join(row_lines) + f'\n{inner}]\n{pad}]'
    child_lines = []
    for ch in children:
        fc = load_comment_sidecar()['fields'].get(ch.get('key', ''), {})
        child_lines.append(f'{inner}{_js_field(ch, indent + 4, fc, visibility_map)}')
    return '[\n' + ',\n\n'.join(child_lines) + f'\n{pad}]'


def _js_field(field: dict, indent: int, field_comments: dict, visibility_map: dict[str, str]) -> str:
    pad = ' ' * indent
    key = field.get('key', '')
    vis_inline = ''
    if key and key not in field_comments.get('propInline', {}):
        vis = visibility_map.get(key, '')
        if vis and '场景' in vis and 'baseSceneCode' not in field_comments.get('omitProps', []):
            pass  # baseSceneCode 行内备注在 _js_object 处理
    body = _js_object(field, indent, field_comments, visibility_map, field_key=key)
    return body


def emit_js_array(
    fields: list[dict],
    visibility_map: dict[str, str],
    sidecar: dict,
) -> str:
    header = sidecar.get('fileHeader', '')
    jsdoc = sidecar.get('jsDoc', '')
    field_comment_map = sidecar.get('fields', {})

    parts = [header, jsdoc, '[{']
    field_strs = []
    for i, field in enumerate(fields):
        fc = field_comment_map.get(field.get('key', ''), {})
        field_strs.append(_js_field(field, 4, fc, visibility_map))
    parts[2] = '[\n' + ',\n\n'.join('    ' + s for s in field_strs) + '\n]'
    return '\n'.join(parts) + '\n'


def convert(
    sheet: str,
    xlsx: Path,
    version: str = '2.1.1',
) -> tuple[list[dict], dict[str, str]]:
    cfg = resolve_sheet_config(sheet, version)
    _header, records = read_sheet_rows(
        xlsx,
        cfg['sheet_filter'],
        exact_sheet=cfg.get('exact_sheet', False),
        classify_styles=cfg.get('classify_styles', True),
    )
    if version in STRICT_STORE_VERSIONS:
        selected = select_v230_records(records, cfg.get('min_root_number', 101))
        field_list = assemble_v230_list(selected, cfg)
        validate_v230_shape(selected, field_list, cfg)
        visibility_map = build_visibility_map(selected)
        return field_list, visibility_map

    baseline_map = load_baseline_js(cfg['baseline'])
    field_list = assemble_list(records, baseline_map, cfg)
    visibility_map = build_visibility_map(records)
    return field_list, visibility_map


def write_text_lf(path: Path, content: str) -> None:
    """以确定的 LF 换行写入生成产物,避免平台默认换行差异。"""
    with path.open('w', encoding='utf-8', newline='\n') as output_file:
        output_file.write(content)


def strip_trailing_whitespace(content: str) -> str:
    """清理生成文本的行尾空白,并将换行统一为 LF。"""
    had_final_newline = content.endswith(('\n', '\r'))
    normalized = '\n'.join(line.rstrip() for line in content.splitlines())
    return normalized + ('\n' if had_final_newline else '')


def main():
    parser = argparse.ArgumentParser(description='Excel 填写表单 → schema JSON/JS')
    parser.add_argument('--sheet', choices=['staff', 'store'], required=True)
    parser.add_argument(
        '--version',
        choices=['2.1.1', '2.3.0', '2.3.1'],
        default='2.1.1',
        help='schema 版本(默认保持 V2.1.1 行为)',
    )
    parser.add_argument('--input', type=Path, default=DEFAULT_XLSX)
    parser.add_argument('--output', type=Path, default=None)
    parser.add_argument('--format', choices=['js', 'json'], default='js')
    parser.add_argument(
        '--env',
        choices=['daily', 'production'],
        default='daily',
        help='brandId 环境:daily=测试,production=线上(默认输出 .prod 后缀)',
    )
    args = parser.parse_args()

    apply_brand_env(args.env)

    if not args.input.exists():
        print(f'input not found: {args.input}', file=sys.stderr)
        sys.exit(1)

    field_list, visibility_map = convert(args.sheet, args.input, args.version)
    cfg = resolve_sheet_config(args.sheet, args.version)
    out = args.output or cfg['output']
    if args.env == 'production' and args.output is None:
        out = out.with_name(out.stem + '.prod' + out.suffix)
    if args.format == 'json':
        if out.suffix != '.json':
            out = out.with_suffix('.json')
        schema = {
            'version': cfg['version'],
            'formCode': cfg['form_code'],
            'title': cfg['title'],
            'list': field_list,
        }
        out.parent.mkdir(parents=True, exist_ok=True)
        write_text_lf(out, json.dumps(schema, ensure_ascii=False, indent=2) + '\n')
    else:
        if out.suffix != '.js':
            out = out.with_suffix('.js')
        sidecar = load_comment_sidecar()
        if args.env == 'production':
            sidecar = {**sidecar, 'fileHeader': build_file_header_comment('production')}
        content = emit_js_array(field_list, visibility_map, sidecar)
        if cfg['version'] in STRICT_STORE_VERSIONS:
            content = strip_trailing_whitespace(content)
        out.parent.mkdir(parents=True, exist_ok=True)
        write_text_lf(out, content)

    print(f'written {out} ({len(field_list)} top-level fields, format={args.format}, env={args.env})')


if __name__ == '__main__':
    main()