baic_special_processor.py 113 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 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
# -*- coding: utf-8 -*-
"""
北汽专项 独立处理器
====================
对应 ORM 表:baic_special_month_data(明细,逐门店一行)
            baic_special_monthly_business(逐门店×业务:延保/权益;D+系统订单,本轮暂不落)
            baic_special_month_summary_metrics(汇总指标,单任务一行)

数据来源:北汽专项源数据表(Excel,线上运营手工上传 5 列)。

源文件结构(经核对,以实际附件为准):
  - 行1(主表头):门店名称 | 品牌 | 兜底门店 | 交车数核对 | 触客数核对
  - 行2(子表头):        |      |          | 一店一群   | 一店一群
  - 行3 起    :逐门店明细(每店一行,隔行为空占位)
  - 末尾汇总段:'北汽品牌汇总'(品牌标签) + 售后门店数 + 售后场景开通率
                (品牌级线上运营手工上传;A 列标签 / B 列数值。
                 售后场景开通率按百分数上传,如 22 表示 22% → 落库 0.22)
  即:col0=门店名称 col1=品牌 col2=兜底门店 col3=交车数核对(一店一群) col4=触客数核对(一店一群)

字段字典(字段取值说明)口径映射:
  - 门店名称            -> store_name
  - 品牌                -> brand(如:北汽极狐 / 北京越野)
  - 兜底门店            -> underwriting_rule(无兜底填「无」;有兜底填规则原文)
  - 交车数核对(一店一群) -> delivery_check_group_cnt(交车数核对-一店一群交车数,手工上传)
  - 触客数核对(一店一群) -> visit_check_group_cnt(触客数核对-一店一群触客数,手工上传)

评灯标准(优秀值/标准值/预警值)按品牌固定取值(用户 2026-09-21 明确,见 LIGHT_STANDARD_BY_BRAND):
  - 北汽极狐 -> 0.5 / 0.3 / 0.3 ;北京越野 -> 0.5 / 0.4 / 0.4
  落库 excellent_value / standard_value / warning_value;结果表 X/Y/Z 列(24/25/26);品牌未匹配留 NULL。

截止目前产值 / 达成率(用户 2026-09-21 明确,见 BAIC_OUTPUT_CURRENT_SQL / fetch_output_current):
  - 截止目前产值 output_current_wan = SUM(dj_car_life_pay_order.actual_money) / 10000(万元)
    条件:goods_order.deleted_flag='N' AND merchant_id=门店编码 AND scene_type=0 AND business_type=2 AND status=4
          AND pay_order.deleted_flag='N' AND pay_status=2 AND success_date ∈ [周期起, 周期止+1天)
  - 达成率 achievement_rate = 截止目前产值 ÷ 产值目标(同万元,比值为小数,模板 0.0% 格式)
  落库 output_current_wan / achievement_rate;结果表 L/M 列(12/13);无数据(如门店无支付成功单)留 NULL。

订单数(延保/权益,用户 2026-09-22 明确,见 BAIC_ORDER_COUNT_SQL / fetch_order_count):
  - 订单数 order_cnt = COUNT(0) FROM dj_car_life_goods_sub_order(LEFT JOIN goods_order / pay_order)
    条件:sub_order.deleted_flag='N' AND goods_order.deleted_flag='N' AND merchant_id=门店编码
          AND scene_type=0 AND business_type=2 AND status=4
          AND pay_order.deleted_flag='N' AND pay_status=2 AND success_date ∈ [周期起, 周期止+1天)
    映射:upgrade_secondary_goods_type_name='整车延保' → 延保(业务类型1);'原厂权益' → 权益(业务类型2);其余忽略。
  - 落库 baic_special_monthly_business(逐门店×业务,store_id 外键 + business_type + order_cnt,按 task 先删后插幂等);
    结果表 Q 列(17):延保行=整车延保订单数、权益行=原厂权益订单数;合计行 r4/r5 按业务类型求和。无数据留 NULL。

其余列中:
  - 触客率 P(16):系统计算(见上)。
  - 周度评灯 T/U/V/W(20/21/22/23):【已接入】按当月累计(延保+权益)订单数 ÷ 新车交付数得综合渗透,
    与 X/Y(优秀/标准值, 小数) 比较判灯色——>优秀值绿(#C6EFCE)/ >标准值黄(#FFEB9C)/ 否则红(#FFC7CE);
    W1/W2/W3 取「截止到当前周」累计订单数(实时查 D+),分母新车交付数取该周结束日快照
    (基础表 glsx_daily_deal_subtotal.delivery_cnt,见 fetch_delivery_snapshot_by_dates);
    截止目前节点分母仍用全月实时 new_delivery_cnt、上界=cutoff_date。
    快照缺失 → 该周渗透留空且不评灯。合计行(r4)写各节点聚合综合渗透(数值)。
  - 周趋势/品牌汇总等其余系统列:源文件不含 → 占位留 NULL(后续接入)。
广联报表来源(dj.glsx.com.cn 报表导出,见 fetch_glsx_report / _GLSX_BASE):
  - 产值目标 output_target_wan        <- 延保小计行 H(8月目标产值(万元))
  - 新车交付数 new_delivery_cnt        <- 非小计行 K(累计交付数(台)),同店多条取最大值
  - 触客数 visit_cnt                   <- '延保小计' 行 O(实际售前触客数,2026-11-04 起;原为非小计行取 max)
  - 交车数核对-产值表 delivery_check_output_cnt <- 延保小计行 K(累计交付数(台))
  - 触客数核对-产值表 visit_check_output_cnt    <- 延保小计行 O(实际售前触客数)
  报表取「通用品牌」一份(queryAllExcel 按 filename=报表月 过滤),门店名与源文件精确匹配;未匹配留 NULL。
触客率 visit_rate(用户 2026-09-21 明确,系统计算):
  - 触客率 = 触客数(visit_cnt) ÷ 新车交付数(new_delivery_cnt),无量纲小数(模板 0.0% 格式)
  - 任一侧为空或新车交付数为 0 → 留 NULL
  落库 visit_rate;结果表 P 列(16)。
核对结果表的「差异」列(AC/F 列,系统计算,任一侧为空则留空):
  - 交车数核对-差异 = 交车数核对-产值表(delivery_check_output_cnt) - 交车数核对-一店一群(delivery_check_group_cnt)
  - 触客数核对-差异 = 触客数核对-产值表(visit_check_output_cnt)    - 触客数核对-一店一群(visit_check_group_cnt)
  注:触客数(系统,O列)=单人max,触客数核对-产值表=门店合计,两者语义本就不同(用户 2026-09-21 确认)。

D+ 系统来源(dj_smartcarlife,见 fetch_baic_store_info / BAIC_STORE_INFO_SQL):
  - 门店编码 store_code   <- pg_group_store_rel.merchant_id(北汽项目组)
  - 区域     region       <- dj_car_life_service_merchant.province_name
  - 驻店类型 store_type    <- dj_car_life_yqmerchant_config.partner_merchant_id=44206988 ? 直营 : 服务商
  - 业务开展 business_start_date <- dj_car_life_goods_order MIN(order_time)(scene_type=0)
  - 运营     operator_name <- dj_car_life_shop_merchant_director_config.director_name(director_type=9)
  按「门店名称」与源文件精确匹配;未匹配则上述字段留空。

SCRM 来源(scrm_account,见 fetch_resident_staff / RESIDENT_STAFF_SQL):
  - 驻店人员 resident_staff <- platform_merchant_staff.staff_name(角色 role_name='驻店人员',多人「/」分隔)
  ⚠ 该角色在 D+ 里配在**园区店**商户上,不在品牌门店商户上:须先用门店在
    dj_car_life_scene_merchant_ref 的 sub_merchant_id(type 6/8, scene=0)换算出园区店编码,
    再到 scrm_account 按 platform_merchant.merchantNo 查询。直接拿品牌门店编码查会全部为空。

落库:按 task_id 先逻辑删除(旧行置 is_deleted=1)后插入新行(is_deleted=0),幂等。
结果表生成:复制用户模板(exporttemplete/baic_special_report_template.xlsx),按 store_name 用
DB 源值覆盖 5 列 + 品牌汇总本月段项目/品牌/门店数;系统列保留模板原样。生成后上传 OSS 并回填
result_file_url。
"""
import io
import logging
import os
import re
import tempfile
import requests
from calendar import monthrange
from copy import copy
from datetime import datetime, date, timedelta
from decimal import Decimal, InvalidOperation

import openpyxl
from openpyxl.styles import PatternFill, Font, Alignment, Border
from openpyxl.utils import get_column_letter
from sqlalchemy import create_engine, text, bindparam
from config import Config
from report_utils import (
    mark_task_failed, cleanup_tmp_dir, download_all_files,
)
from oss_utils import upload_file
from models import (
    DataProcessTask, db,
    BaicSpecialMonthData, BaicSpecialMonthlyBusiness, BaicSpecialMonthSummaryMetrics,
    GlsxDailyDealSubtotal,
)

# 结果表生成模板(由用户提供的「北汽专项-展示表字段取值说明(模板版)」复制而来,作为布局基线)
BAIC_TEMPLATE_PATH = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    'exporttemplete', 'baic_special_report_template.xlsx')

# 附件上传模板(用户下载后填数据上传;门店名称系统预填,其余清空)
BAIC_ATTACH_TEMPLATE_PATH = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    'exporttemplete', '北汽专项-门店数据模板.xlsx')

logger = logging.getLogger('BaicSpecialProcessor')

BAIC_TYPE = 'baic_special'

# 源文件明细行列索引(0-based)
SRC_STORE_NAME = 0
SRC_BRAND = 1
SRC_UNDERWRITING = 2
SRC_DELIVERY_GROUP = 3
SRC_VISIT_GROUP = 4

# 源文件末尾汇总段(品牌级,A 列标签 / B 列数值)
BRAND_SUMMARY_LABEL = '北汽品牌汇总'
SUMMARY_LABELS = {
    '售后门店数': 'after_sale_store_cnt',
    '售后场景开通率': 'after_sale_scene_open_rate',
    '售后订单数': 'after_sale_order_cnt',
}
# 需按百分数归一为小数比率的汇总字段(源文件以「22」表示 22%)
RATE_SUMMARY_ATTRS = {'after_sale_scene_open_rate'}

# ---------- 评灯标准(优秀值/标准值/预警值)----------
# 源文件与系统均未提供,按品牌固定取值(用户 2026-09-21 明确):
#   北汽极狐 -> 0.5 / 0.3 / 0.3 ; 北京越野 -> 0.5 / 0.4 / 0.4
# 落库 excellent_value / standard_value / warning_value;结果表 X/Y/Z 列(24/25/26);品牌未匹配留 NULL。
# 注意:评灯标准「显示是小数、非百分比」(如 0.5 即 50%),与综合渗透(同为小数比率)直接比较,
#       **切勿**把综合渗透 ×100 再比,也**切勿**把标准值当百分数 ÷100。
LIGHT_STANDARD_BY_BRAND = {
    '北汽极狐': (0.5, 0.3, 0.3),
    '北京越野': (0.5, 0.4, 0.4),
}

# ---------- 周度评灯底色(绿/黄/红)与结果表列位 ----------
# 结果表「门店等级」六列:T(20)=截止目前(灯)、U(21)=W1、V(22)=W2、W(23)=W3、X(24)=W4、Y(25)=W5
# 单元格显示灯色文字(绿/黄/红)+ 对应浅色底;列顺序与 compute_baic_week_ends 返回的节点顺序一致。
BAIC_LIGHT_FILL = {
    '绿': 'C6EFCE',   # 综合渗透 > 优秀值
    '黄': 'FFEB9C',   # 综合渗透 > 标准值(且 ≤ 优秀值)
    '红': 'FFC7CE',   # 综合渗透 ≤ 标准值
}
BAIC_LIGHT_COLS = [20, 21, 22, 23, 24, 25]   # [截止目前, W1, W2, W3, W4, W5] 对应 T~Y

# ---------- 业务类型编码(对应 baic_special_monthly_business.business_type)----------
# 1=延保(整车延保)/ 2=权益(原厂权益)
BAIC_BIZ_EXT_WARRANTY = 1
BAIC_BIZ_RIGHTS = 2
# 订单数 SQL:goods_type_name -> 业务类型编码(其余类型忽略)
ORDER_CNT_TYPE_MAP = {
    '整车延保': BAIC_BIZ_EXT_WARRANTY,
    '原厂权益': BAIC_BIZ_RIGHTS,
}
BIZ_TYPE_LABEL = {BAIC_BIZ_EXT_WARRANTY: '延保', BAIC_BIZ_RIGHTS: '权益'}


def _light_standard(brand):
    """按品牌返回评灯标准 (优秀值, 标准值, 预警值);品牌未匹配返回 (None, None, None)。"""
    return LIGHT_STANDARD_BY_BRAND.get((brand or '').strip(), (None, None, None))


def _task_period(task):
    """取任务的统计周期 (start_date, end_date),两端均含当天。

    优先用任务的 period_start / period_end;缺失时按 month(YYYY-MM)推算整月,
    用于「截止目前产值」按 success_date 区间汇总(SQL 上界取 end_date + 1 天)。
    """
    ps = getattr(task, 'period_start', None)
    pe = getattr(task, 'period_end', None)
    if ps and pe:
        return ps, pe
    month = (getattr(task, 'month', None) or '')
    if len(month) >= 7 and month[4] == '-':
        try:
            y, m = int(month[:4]), int(month[5:7])
            return date(y, m, 1), date(y, m, monthrange(y, m)[1])
        except (ValueError, IndexError):
            logger.warning(f"[北汽] 任务月份无法解析为周期: {month!r}")
    return ps, pe

# ---------- D+ 系统(dj_smartcarlife)门店基础信息 ----------
BAIC_GROUP_NAME = '北汽'          # pg_group_info.group_name
DIRECT_SALE_PARTNER_ID = 44206988  # partner_merchant_id 等于该值 -> 直营,否则 服务商

_BIZ_ENGINE = None


def _get_biz_engine():
    """业务系统 SQL 引擎(嘀加 dj_smartcarlife),懒加载单例。"""
    global _BIZ_ENGINE
    if _BIZ_ENGINE is None:
        _BIZ_ENGINE = create_engine(Config.BIZ_SQL_DATABASE_URL, echo=False, pool_pre_ping=True)
    return _BIZ_ENGINE


# ---------- SCRM 系统(scrm_account)驻店人员 ----------
_SCRM_ENGINE = None


def _get_scrm_engine():
    """SCRM 账号库(scrm_account)引擎,懒加载单例。"""
    global _SCRM_ENGINE
    if _SCRM_ENGINE is None:
        _SCRM_ENGINE = create_engine(Config.SCRM_DATABASE_URL, echo=False, pool_pre_ping=True)
    return _SCRM_ENGINE


# 驻店人员:按「园区店编码」(platform_merchant.merchantNo) 查角色 role_name='驻店人员' 的员工姓名
# 注意:D+ 的「驻店人员」配在**园区店**商户上(店面配置-人员管理),
#      不是品牌门店商户本身;故须先用门店关联的 sub_merchant_id 换算出园区店编码再查本表。
RESIDENT_STAFF_SQL = """
SELECT pm.merchantNo AS merchant_no, st.staff_name AS staff_name
FROM platform_merchant_staff st
LEFT JOIN platform_merchant_role_staff_relation pr
       ON st.id = pr.staff_id AND pr.del_flag = 0
LEFT JOIN platform_merchant_role ro
       ON pr.role_id = ro.id AND ro.del_flag = 0
LEFT JOIN platform_merchant pm
       ON st.merchant_id = pm.id AND pm.del_flag = 0
WHERE st.del_flag = 0
  AND ro.role_name = '驻店人员'
  AND pm.merchantNo IN :park_codes
"""


def fetch_resident_staff(park_codes):
    """按园区店编码批量查询驻店人员(scrm_account 单次查询)。

    park_codes: 园区店编码可迭代对象(platform_merchant.merchantNo)
    返回 {园区店编码(str): ['张三','李四', ...]};查询失败/无数据返回 {}(不致命)。
    """
    codes = tuple({str(c).strip() for c in (park_codes or []) if c not in (None, '')})
    if not codes:
        return {}
    engine = _get_scrm_engine()
    result = {}
    try:
        with engine.connect() as conn:
            rows = conn.execute(text(RESIDENT_STAFF_SQL), {'park_codes': codes}).fetchall()
    except Exception as e:
        logger.warning(f"[北汽] SCRM 驻店人员查询失败: {e}")
        return {}

    for no, name in rows:
        key = str(no).strip() if no is not None else ''
        val = str(name).strip() if name not in (None, '') else ''
        if not key or not val:
            continue
        bucket = result.setdefault(key, [])
        if val not in bucket:
            bucket.append(val)
    logger.info(f"[北汽] SCRM 驻店人员:{len(codes)} 个园区店编码 → 命中 {len(result)} 个、共 "
                f"{sum(len(v) for v in result.values())} 人次")
    return result


# ===================================================================
# 广联报表(dj.glsx.com.cn)延保+权益门店产值及个人成交排名
#   第1步:queryAllExcel?filename={stat_month}&... 取 list 中 filename 含 '通用品牌' 的 key
#   第2步:download?key={key} 取 data.list[0].url
#   第3步:GET 该 url 下载 xlsx,解析 Sheet1
#          - 表头行(col0=='业务类型')定位;门店名在 col2(C列),业务类型标签在 col0(A列)
#          - 每个门店分段:业务类型行(如 '2.3延保', C=门店名, H/K/O 带值)
#                          → 多条人员行(仅 O 有值, C 空) → '延保小计'/'权益小计' 小计行
#                            (A 标签, H/K/O 带值, C 可能空 → 门店名从上一业务行向前携带)
#   取值(按门店名称匹配):
#     - output_target_wan        : '延保小计' 行 H 列(8月目标产值(万元))
#     - new_delivery_cnt         : 非小计行 K 列(累计交付数(台)),同一门店多条取最大值
#     - visit_cnt                : '延保小计' 行 O 列(实际售前触客数,2026-11-04 起改为小计行口径;原为非小计行取 max)
#     - delivery_check_output_cnt: '延保小计' 行 K 列(累计交付数(台))
#     - visit_check_output_cnt   : '延保小计' 行 O 列(实际售前触客数)
#   失败返回 {}(不致命,仅告警留空)。
# ===================================================================
_GLSX_BASE = 'https://dj.glsx.com.cn/reportExport'
_GLSX_TIMEOUT = (30, 120)


def _norm_glsx_header(s):
    """报表表头单元格归一:去空格/换行,便于按列名定位(如 '8月目标产值\n(万元)'→'8月目标产值(万元)')"""
    return ''.join(str(s).split()) if s is not None else ''


def _glsx_to_int(v):
    """单元格转 int:空/非数字 → None(用于交付/触客计数聚合与取值)"""
    if v is None or v == '':
        return None
    s = str(v).strip().replace(',', '')
    if s in ('-', 'None'):
        return None
    try:
        return int(Decimal(s))
    except (InvalidOperation, ValueError):
        return None


def _diff(a, b):
    """差异 = 产值表 - 一店一群:任一侧为空则差异为空(NULL)。用于交车数核对/触客数核对差异列。"""
    if a is None or b is None:
        return None
    return a - b


def _ratio(a, b):
    """比率 = a ÷ b:任一侧为空或分母为 0 则留空(NULL)。返回无量纲小数(模板 0.0% 格式)。"""
    if a is None or b in (None, 0):
        return None
    return Decimal(str(a)) / Decimal(str(b))


def _penetration(order_cnt, delivery):
    """渗透率 = 订单数(order_cnt) ÷ 新车交付数(delivery)。

    - 分母 delivery 为空 / 0 / 非数字 → 留空(NULL,无法计算);
    - 分子 order_cnt 缺失(None)→ 按 0 参与计算(门店未售该业务即渗透 0)。
    返回无量纲小数(模板百分比格式)。
    """
    if delivery is None:
        return None
    try:
        dv = float(delivery)
    except (TypeError, ValueError):
        return None
    if dv <= 0:
        return None
    oc = order_cnt if order_cnt is not None else 0
    try:
        oc = float(oc)
    except (TypeError, ValueError):
        return None
    return oc / dv


def fetch_glsx_report(stat_month):
    """从广联报表导出接口获取各门店的 产值目标/新车交付数/触客数系统/交车数核对-产值表/触客数核对-产值表。

    返回 {门店名称: {'output_target_wan','new_delivery_cnt','visit_cnt',
                     'delivery_check_output_cnt','visit_check_output_cnt'}};
    任何失败返回空 dict(不致命)。
    """
    if not stat_month:
        logger.warning('[北汽] 广联报表:stat_month 为空,跳过获取')
        return {}
    try:
        # 第1步:列出报表,定位 通用品牌
        resp = requests.get(_GLSX_BASE + '/queryAllExcel', params={
            'pageSize': 10, 'currentPage': 1, 'filename': stat_month,
            'business_type': 'yanbao', 'report_type': 'yanbaoMerAndPerRanking', 'key': '',
        }, timeout=_GLSX_TIMEOUT)
        resp.raise_for_status()
        items = (resp.json().get('data') or {}).get('list') or []
        target = next((x for x in items if '通用品牌' in (x.get('filename') or '')), None)
        if not target:
            logger.warning(f'[北汽] 广联报表:未找到 通用品牌 报表(filename={stat_month})')
            return {}
        key = target['key']
        # 第2步:获取下载 url
        dl = requests.get(_GLSX_BASE + '/download', params={'key': key}, timeout=_GLSX_TIMEOUT)
        dl.raise_for_status()
        dlist = (dl.json().get('data') or {}).get('list') or []
        if not dlist or not dlist[0].get('url'):
            logger.warning('[北汽] 广联报表:download 未返回有效文件 url')
            return {}
        file_url = dlist[0]['url']
        # 第3步:下载并解析 xlsx
        x = requests.get(file_url, timeout=_GLSX_TIMEOUT)
        x.raise_for_status()
        wb = openpyxl.load_workbook(io.BytesIO(x.content), data_only=True)
        ws = wb[wb.sheetnames[0]]
        rows = list(ws.iter_rows(values_only=True))
        hidx = next((i for i, row in enumerate(rows)
                     if row and _norm_glsx_header(row[0]) == '业务类型'), None)
        if hidx is None:
            logger.warning('[北汽] 广联报表:未找到表头行(业务类型)')
            return {}
        SUB = ('延保小计', '权益小计')
        stores = {}
        cur = None  # 向前携带的当前门店名(人员行 C 为空)
        for row in rows[hidx + 1:]:
            a = _norm_glsx_header(row[0]) if row and row[0] is not None else ''
            c = str(row[2]).strip() if len(row) > 2 and row[2] is not None else ''
            h = row[7] if len(row) > 7 else None   # H 8月目标产值(万元)
            k = row[10] if len(row) > 10 else None  # K 累计交付数(台)
            o = row[14] if len(row) > 14 else None  # O 实际售前触客数
            if not a and not c:
                continue
            if c:
                cur = c
            if not cur:
                continue
            s = stores.setdefault(cur, {'h': None, 'kl': [], 'ol': [], 'ek': None, 'eo': None})
            if a in SUB:
                if a == '延保小计':
                    if h not in (None, ''):
                        s['h'] = _to_dec(h)
                    kv = _glsx_to_int(k)
                    if kv is not None:
                        s['ek'] = kv
                    ov = _glsx_to_int(o)
                    if ov is not None:
                        s['eo'] = ov
            else:
                kv = _glsx_to_int(k)
                if kv is not None:
                    s['kl'].append(kv)
                ov = _glsx_to_int(o)
                if ov is not None:
                    s['ol'].append(ov)
        result = {}
        for name, s in stores.items():
            result[name] = {
                'output_target_wan': s['h'],
                'new_delivery_cnt': max(s['kl']) if s['kl'] else None,
                'visit_cnt': s['eo'],
                'delivery_check_output_cnt': s['ek'],
                'visit_check_output_cnt': s['eo'],
            }
        logger.info(f'[北汽] 广联报表:解析到 {len(result)} 个门店的产值/交付/触客数据')
        return result
    except Exception as e:
        logger.warning(f'[北汽] 广联报表获取失败(stat_month={stat_month}): {e}')
        return {}


# 北汽项目组门店基础信息:门店编码 / 门店名称 / 区域(省) / 驻店类型 / 业务开展 / 区域运营 / 关联园区店
# 注意:
#  1) 「区域运营」须按 a.merchant_id 关联(原 SQL 硬编码单个 merchant_id 会让所有门店返回同一人);
#  2) 不用 DATE_FORMAT('%Y-%m-%d')——SQLAlchemy 参数化语句下 '%' 会与驱动绑定冲突,
#     改为取 MIN(order_time) 原值,在 Python 侧用 _to_date() 格式化;
#  3) park_merchant_ids 为门店关联的园区店商户编码(type 6/8, scene=0),供 SCRM 查「驻店人员」用。
BAIC_STORE_INFO_SQL = """
SELECT
    a.merchant_id   AS merchant_id,
    a.merchant_name AS merchant_name,
    c.province_name AS province_name,
    IF(e.partner_merchant_id = :direct_partner_id, '直营', '服务商') AS store_type,
    (
        SELECT MIN(o.order_time)
          FROM dj_car_life_goods_order o
         WHERE o.deleted_flag = 'N'
           AND o.scene_type = 0
           AND o.merchant_id = a.merchant_id
    ) AS business_start_date,
    (
        SELECT GROUP_CONCAT(DISTINCT director_name)
          FROM dj_car_life_shop_merchant_director_config
         WHERE deleted_flag = 'N'
           AND merchant_id = a.merchant_id
           AND director_type = 9
    ) AS operator_name,
    (
        SELECT GROUP_CONCAT(DISTINCT d.sub_merchant_id)
          FROM dj_car_life_scene_merchant_ref d
         WHERE d.deleted_flag = 'N'
           AND d.main_merchant_id = a.merchant_id
           AND d.main_merchant_type = 2
           AND d.sub_merchant_type IN (6, 8)
           AND d.scene = 0
    ) AS park_merchant_ids
FROM pg_group_store_rel a
LEFT JOIN pg_group_info b
       ON b.id = a.group_id AND b.deleted_flag = 'N'
LEFT JOIN dj_car_life_service_merchant c
       ON c.merchant_id = a.merchant_id AND c.deleted_flag = 'N'
LEFT JOIN dj_car_life_scene_merchant_ref d
       ON d.main_merchant_id = a.merchant_id AND d.deleted_flag = 'N'
      AND d.main_merchant_type = 2 AND d.sub_merchant_type IN (6, 8) AND d.scene = 0
LEFT JOIN dj_car_life_yqmerchant_config e
       ON d.sub_merchant_id = e.merchant_id AND e.deleted_flag = 'N'
WHERE a.deleted_flag = 'N'
  AND b.group_name = :group_name
"""

# 已关店记录(dj_smartcarlife.sale_close_store_record,口径与 common_equity_processor 一致):
#   status=3 已关店 / status=1 待关店;已关店查全部历史记录(status=3 不会回退,任一记录即视为已闭店)。
# 附件模板预填门店时排除已闭店门店(用户 2026-11-04)。
BAIC_CLOSED_STORE_SQL = """
SELECT DISTINCT shop_merchant_id
FROM sale_close_store_record
WHERE deleted_flag = 'N'
  AND status = 3
"""


def fetch_baic_store_info(group_name=BAIC_GROUP_NAME):
    """查询北汽项目组下门店的 D+ 基础信息(dj_smartcarlife 单次查询)。

    返回 {merchant_name: {'store_code','region','store_type','business_start_date',
                          'operator_name','resident_staff'}};
    其中驻店人员由关联园区店编码到 scrm_account 二次查询(见 fetch_resident_staff),
    多人以「/」分隔(字段字典口径)。
    查询失败/无数据返回 {}(不致命,调用方仅告警)。
    """
    engine = _get_biz_engine()
    result = {}
    try:
        with engine.connect() as conn:
            rows = conn.execute(
                text(BAIC_STORE_INFO_SQL),
                {'direct_partner_id': DIRECT_SALE_PARTNER_ID,
                 'group_name': group_name},
            ).fetchall()
    except Exception as e:
        logger.warning(f"[北汽] D+ 门店基础信息查询失败: {e}")
        return result

    for r in rows:
        mid, name, province, stype, start_date, operator, park_ids = (
            r[0], r[1], r[2], r[3], r[4], r[5], r[6])
        name = (str(name).strip() if name not in (None, '') else '')
        if not name:
            continue
        item = result.setdefault(name, {
            'store_code': str(mid) if mid is not None else None,
            'region': (str(province).strip() if province not in (None, '') else None),
            'store_type': (str(stype).strip() if stype not in (None, '') else None),
            'business_start_date': _to_date(start_date),
            'operator_name': (str(operator).strip() if operator not in (None, '') else None),
            'park_merchant_ids': [],
            'resident_staff': None,
        })
        # 同一门店可能关联多个园区店(join 出多行)→ 合并去重
        for code in str(park_ids or '').split(','):
            code = code.strip()
            if code and code not in item['park_merchant_ids']:
                item['park_merchant_ids'].append(code)

    # ---- 按园区店编码到 SCRM 查「驻店人员」(跨库二次查询)----
    all_codes = {c for v in result.values() for c in v['park_merchant_ids']}
    staff_map = fetch_resident_staff(all_codes)
    for v in result.values():
        names = []
        for code in v['park_merchant_ids']:
            for nm in staff_map.get(code, []):
                if nm not in names:
                    names.append(nm)
        v['resident_staff'] = ('/'.join(names))[:255] if names else None
        v.pop('park_merchant_ids', None)

    logger.info(f"[北汽] D+ 门店基础信息:北汽组查询到 {len(result)} 家门店(group_name={group_name})"
                f",其中 {sum(1 for v in result.values() if v['resident_staff'])} 家有驻店人员")
    return result


def fetch_baic_closed_store_codes():
    """查询 D+ 已关店门店编码集合(sale_close_store_record,status=3 已关店)。

    返回 {shop_merchant_id(str)};查询失败返回 set()(不致命,调用方回退为全量预填)。
    """
    engine = _get_biz_engine()
    try:
        with engine.connect() as conn:
            rows = conn.execute(text(BAIC_CLOSED_STORE_SQL)).fetchall()
    except Exception as e:
        logger.warning(f"[北汽] 已闭店门店查询失败(回退为全量预填): {e}")
        return set()
    return {str(r[0]).strip() for r in rows if r[0] not in (None, '')}


# ---------- D+ 系统:截止目前产值(dj_smartcarlife) ----------
# 口径(用户 2026-11-04 修订):状态为已支付/已完成/已退款(status IN (4,6,12))、
#   订单类型排除「内部结算」(dj_order_type=6)的订单中,去掉已退款金额后的合计值
#   = SUM(支付成功金额) - SUM(已退款金额)。
#   merchant_id  <- 门店 D+ 编码(即 store_code,来自 pg_group_store_rel.merchant_id)
#   success_date <- 任务周期([period_start, period_end + 1 天))
# 注意:actual_money 单位为「元」,写入「截止目前产值(万)」需 /10000。
# 实现与用户原稿的两处差异(修正,口径不变):
#   1) 退款金额先按 order_code 聚合成子查询再关联——退款明细直接 LEFT JOIN 时,
#      一单多笔退款会把支付金额按退款笔数扇出放大(SUM(actual_money) 虚高);
#   2) dj_order_type != 6 改为 OR IS NULL 兜底——NULL 行在 != 比较下会被整行漏掉。
BAIC_OUTPUT_CURRENT_SQL = """
SELECT a.merchant_id AS merchant_id,
       SUM(b.actual_money) - SUM(IFNULL(c.refund_amount, 0)) AS output_amount
FROM dj_car_life_goods_order a
LEFT JOIN dj_car_life_pay_order b
       ON b.order_code = a.order_code
      AND b.deleted_flag = 'N'
      AND b.pay_status = 2
LEFT JOIN (
    SELECT order_code, SUM(refund_amount) AS refund_amount
    FROM dj_car_life_goods_order_refund_details
    WHERE deleted_flag = 'N'
    GROUP BY order_code
) c ON c.order_code = a.order_code
WHERE a.deleted_flag = 'N'
  AND a.merchant_id IN :merchant_ids
  AND a.scene_type = 0
  AND a.business_type = 2
  AND a.status IN (4, 6, 12)
  AND (a.dj_order_type != 6 OR a.dj_order_type IS NULL)
  AND b.success_date >= :date_from
  AND b.success_date < :date_to
GROUP BY a.merchant_id
"""


def fetch_output_current(period_start, period_end, merchant_ids):
    """查询各门店「截止目前产值」(dj_smartcarlife,单次分组查询)。

    :param period_start: 周期开始日期(date)
    :param period_end:   周期结束日期(date,含当天 → 查询上界取次日)
    :param merchant_ids: 门店 D+ 编码集合(store_code)
    :return: {merchant_id(str): 截止目前产值(万元, Decimal 4 位)};失败/无数据返回 {}(不致命)。
    """
    result = {}
    ids = [int(c) for c in {str(c).strip() for c in merchant_ids if c not in (None, '')}
           if str(c).strip().isdigit()]
    if not ids or not period_start or not period_end:
        return result
    date_from = period_start.strftime('%Y-%m-%d')
    date_to = (period_end + timedelta(days=1)).strftime('%Y-%m-%d')
    engine = _get_biz_engine()
    try:
        with engine.connect() as conn:
            stmt = text(BAIC_OUTPUT_CURRENT_SQL).bindparams(
                bindparam('merchant_ids', expanding=True))
            rows = conn.execute(
                stmt,
                {'merchant_ids': ids, 'date_from': date_from, 'date_to': date_to},
            ).fetchall()
    except Exception as e:
        logger.warning(f"[北汽] 截止目前产值查询失败: {e}")
        return result
    for r in rows:
        mid, amt = r[0], r[1]
        if mid is None or amt is None:
            continue
        # 元 -> 万元(对齐 output_current_wan DECIMAL(18,4))
        result[str(mid)] = (Decimal(str(amt)) / Decimal('10000')).quantize(Decimal('0.0001'))
    logger.info(f"[北汽] 截止目前产值:周期 [{date_from}, {date_to}) 命中 {len(result)}/{len(ids)} 家门店")
    return result


# 订单数统计(用户 2026-09-22 明确,见 fetch_order_count):按门店 + 业务类型(延保/权益)分组。
# 口径:sub_order.deleted_flag='N' AND goods_order.deleted_flag='N' AND merchant_id=门店编码
#      AND scene_type=0 AND business_type=2 AND status=4
#      AND pay_order.deleted_flag='N' AND pay_status=2 AND success_date ∈ [周期起, 周期止+1天)
# 映射:upgrade_secondary_goods_type_name='整车延保' -> 延保(1);'原厂权益' -> 权益(2);其余忽略。
BAIC_ORDER_COUNT_SQL = """
SELECT a.merchant_id AS merchant_id,
       gso.upgrade_secondary_goods_type_name AS goods_type_name,
       COUNT(0) AS order_cnt
FROM dj_car_life_goods_sub_order gso
LEFT JOIN dj_car_life_goods_order a
       ON a.order_code = gso.order_code AND a.deleted_flag = 'N'
LEFT JOIN dj_car_life_pay_order b
       ON b.order_code = a.order_code AND b.deleted_flag = 'N' AND b.pay_status = 2
WHERE gso.deleted_flag = 'N'
  AND a.merchant_id IN :merchant_ids
  AND a.scene_type = 0
  AND a.business_type = 2
  AND a.status = 4
  AND b.success_date >= :date_from
  AND b.success_date < :date_to
GROUP BY a.merchant_id, gso.upgrade_secondary_goods_type_name
"""


def fetch_order_count(period_start, period_end, merchant_ids):
    """查询各门店「延保/权益订单数」(dj_smartcarlife,按门店+业务类型分组一次查全)。

    :param period_start: 周期开始日期(date)
    :param period_end:   周期结束日期(date,含当天 → 查询上界取次日)
    :param merchant_ids: 门店 D+ 编码集合(store_code)
    :return: {merchant_id(str): {业务类型编码(int): 订单数(int)}};失败/无数据返回 {}(不致命)。
    """
    result = {}
    ids = [int(c) for c in {str(c).strip() for c in merchant_ids if c not in (None, '')}
           if str(c).strip().isdigit()]
    if not ids or not period_start or not period_end:
        return result
    date_from = period_start.strftime('%Y-%m-%d')
    date_to = (period_end + timedelta(days=1)).strftime('%Y-%m-%d')
    engine = _get_biz_engine()
    try:
        with engine.connect() as conn:
            stmt = text(BAIC_ORDER_COUNT_SQL).bindparams(
                bindparam('merchant_ids', expanding=True))
            rows = conn.execute(
                stmt,
                {'merchant_ids': ids, 'date_from': date_from, 'date_to': date_to},
            ).fetchall()
    except Exception as e:
        logger.warning(f"[北汽] 订单数查询失败: {e}")
        return result
    for r in rows:
        mid, gtn, cnt = r[0], (r[1] or '').strip(), r[2]
        if mid is None or cnt is None:
            continue
        biz = ORDER_CNT_TYPE_MAP.get(gtn)
        if biz is None:
            continue
        result.setdefault(str(mid), {})[biz] = int(cnt)
    logger.info(f"[北汽] 订单数:周期 [{date_from}, {date_to}) 命中 {len(result)}/{len(ids)} 家门店"
                f"(仅统计整车延保/原厂权益)")
    return result


def fetch_order_count_window(period_start, period_end, merchant_ids):
    """查询各门店『截止 period_end(含当天)累计』的延保/权益订单数。

    与 fetch_order_count 同口径(同样的 BAIC_ORDER_COUNT_SQL 谓词),仅成功日期上界不同,
    用于周度评灯 / 截止目前 的「截止到当前周累计」订单数:
      success_date ∈ [period_start, period_end + 1 天)
    返回 {merchant_id(str): {业务类型编码(int): 订单数(int)}};失败/无数据返回 {}(不致命)。
    """
    result = {}
    ids = [int(c) for c in {str(c).strip() for c in merchant_ids if c not in (None, '')}
           if str(c).strip().isdigit()]
    if not ids or not period_start or not period_end:
        return result
    date_from = period_start.strftime('%Y-%m-%d')
    date_to = (period_end + timedelta(days=1)).strftime('%Y-%m-%d')
    engine = _get_biz_engine()
    try:
        with engine.connect() as conn:
            stmt = text(BAIC_ORDER_COUNT_SQL).bindparams(
                bindparam('merchant_ids', expanding=True))
            rows = conn.execute(
                stmt,
                {'merchant_ids': ids, 'date_from': date_from, 'date_to': date_to},
            ).fetchall()
    except Exception as e:
        logger.warning(f"[北汽] 累计订单数查询失败(窗口 {date_from}~{date_to}): {e}")
        return result
    for r in rows:
        mid, gtn, cnt = r[0], (r[1] or '').strip(), r[2]
        if mid is None or cnt is None:
            continue
        biz = ORDER_CNT_TYPE_MAP.get(gtn)
        if biz is None:
            continue
        result.setdefault(str(mid), {})[biz] = int(cnt)
    logger.info(f"[北汽] 累计订单数(窗口 {date_from}~{date_to}) 命中 {len(result)}/{len(ids)} 家门店")
    return result


def _month_last_day(d):
    """返回 d 所在月份的最后一天(date)。"""
    if d is None:
        return None
    if d.month == 12:
        return date(d.year + 1, 1, 1) - timedelta(days=1)
    return date(d.year, d.month + 1, 1) - timedelta(days=1)


# 售后订单数(用户 2026-10-16 指定口径;2026-11-04 修订):主订单 a + 支付单 b(pay_status=2)
# + 客户单 c(sales_type=1),按商户 GROUP BY COUNT(0),得到「延保+权益」合并总数(不分拆)。
# 2026-11-04 修订:status IN (4,6,12)(已支付/已完成/已退款)、排除内部结算(dj_order_type=6)、
#   退款过滤——订单无退款记录,或存在 refund_type 为 NULL/2 的退款记录时才计数
#   (等价于用户原稿「(r.refund_type is null or r.refund_type=2)」的逐行过滤语义)。
# 实现与用户原稿的差异(修正,口径不变):
#   1) 退款表原稿与客户单同用别名 c(MySQL 报 Not unique table/alias),改用 EXISTS 子查询;
#   2) 退款明细直接 LEFT JOIN 时一单多笔退款会把 COUNT(0) 按退款笔数扇出放大,
#      EXISTS 存在性判断无扇出,计数恒为 1 行/客户单。
BAIC_AFTER_SALE_ORDER_SQL = """
SELECT a.merchant_id, COUNT(0) AS order_cnt
FROM dj_car_life_goods_order a
LEFT JOIN dj_car_life_pay_order b
       ON b.order_code = a.order_code AND b.deleted_flag='N' AND b.pay_status=2
LEFT JOIN dj_car_life_goods_order_customer c
       ON c.order_code = a.order_code AND c.deleted_flag='N'
WHERE a.deleted_flag='N'
  AND a.merchant_id IN :merchant_ids
  AND a.scene_type=0 AND a.business_type=2
  AND a.status IN (4, 6, 12)
  AND (a.dj_order_type != 6 OR a.dj_order_type IS NULL)
  AND (
      NOT EXISTS (SELECT 1 FROM dj_car_life_goods_order_refund_details r
                  WHERE r.order_code = a.order_code AND r.deleted_flag = 'N')
      OR EXISTS (SELECT 1 FROM dj_car_life_goods_order_refund_details r
                 WHERE r.order_code = a.order_code AND r.deleted_flag = 'N'
                   AND (r.refund_type IS NULL OR r.refund_type = 2))
  )
  AND b.success_date >= :date_from
  AND b.success_date <  :date_to
  AND c.sales_type=1
GROUP BY a.merchant_id
"""


def fetch_after_sale_order_count(period_start, period_end, merchant_ids):
    """查询各门店「售后订单数」(延保+权益合并,dj_smartcarlife)。

    用户 2026-10-16 指定口径:主订单 a LEFT JOIN 支付单 b(pay_status=2)
    LEFT JOIN 客户单 c(sales_type=1),按商户分组 COUNT(0)。
    其余谓词(scene_type=0 / business_type=2 / status=4 / deleted_flag / sales_type=1)固定。
    :param period_start: 周期开始日期(date,含当天)
    :param period_end:   周期结束日期(date,含当天 → 查询上界取次日)
    :param merchant_ids: 门店 D+ 编码集合(store_code)
    :return: {merchant_id(str): 订单数(int)};失败/无数据返回 {}(不致命)。
    """
    result = {}
    ids = [int(c) for c in {str(c).strip() for c in merchant_ids if c not in (None, '')}
           if str(c).strip().isdigit()]
    if not ids or not period_start or not period_end:
        return result
    date_from = period_start.strftime('%Y-%m-%d')
    date_to = (period_end + timedelta(days=1)).strftime('%Y-%m-%d')
    engine = _get_biz_engine()
    try:
        with engine.connect() as conn:
            stmt = text(BAIC_AFTER_SALE_ORDER_SQL).bindparams(
                bindparam('merchant_ids', expanding=True))
            rows = conn.execute(
                stmt,
                {'merchant_ids': ids, 'date_from': date_from, 'date_to': date_to},
            ).fetchall()
    except Exception as e:
        logger.warning(f"[北汽] 售后订单数查询失败: {e}")
        return result
    for r in rows:
        mid, cnt = r[0], r[1]
        if mid is None or cnt is None:
            continue
        result[str(mid)] = int(cnt)
    logger.info(f"[北汽] 售后订单数:周期 [{date_from}, {date_to}) 命中 {len(result)}/{len(ids)} 家门店")
    return result


def compute_baic_week_ends(month, cutoff_date):
    """计算北汽报表周度评灯节点的结束日期(**独立规则,勿与通用+权益混用**)。

    规则:当月第一个周一为 W1 起始日,每周周一~周日。
      W1 结束 = 第一个周一 + 6 天;W2 = +13;W3 = +20;W4 = +27;W5 = +34。
    最后一周统计周期不超过当月最后一天:结束日 > 月末时 clamp 到月末;
    该周起始日(前一周结束+1)已超出月末 → 该周不存在,返回 None(结果表留空)。
      W4 存在条件:第一个周一 + 21 ≤ 月末(恒成立,W4 结束 = min(+27, 月末));
      W5 存在条件:第一个周一 + 28 ≤ 月末。
    返回 [(label, end_date), ...],列顺序固定为 [截止目前, W1, W2, W3, W4, W5],
    对应结果表 T~Y 六列(BAIC_LIGHT_COLS)。
    end_date 为 date;month 非法时 W1~W5 返回 None。

    注:2026-10 起通用+权益报表的周口径已改为「每周都从当月 1 号起算的累计制」
    (见 common_equity_processor._weekly_ranges / app.compute_week_period),
    北汽报表仍是「第一个周一 + 7 天倍数」的老规则,两者不再同源。此处保持
    北汽既有行为不变(固定 6 列的交付物),只是不要再拿它当同规则参照。
    """
    w1 = w2 = w3 = w4 = w5 = None
    if len(month) >= 7 and month[4] == '-':
        try:
            y, m = int(month[:4]), int(month[5:7])
            first = date(y, m, 1)
            month_last = date(y, m, monthrange(y, m)[1])
            offset = (7 - first.weekday()) % 7      # 周一=0 → offset 0;周六=5 → +2 天到周一
            first_monday = first + timedelta(days=offset)
            w1 = first_monday + timedelta(days=6)
            w2 = first_monday + timedelta(days=13)
            w3 = first_monday + timedelta(days=20)
            if first_monday + timedelta(days=21) <= month_last:
                w4 = min(first_monday + timedelta(days=27), month_last)
            if first_monday + timedelta(days=28) <= month_last:
                w5 = min(first_monday + timedelta(days=34), month_last)
        except (ValueError, IndexError):
            w1 = w2 = w3 = w4 = w5 = None
    return [
        ('截止目前', cutoff_date),
        ('W1', w1),
        ('W2', w2),
        ('W3', w3),
        ('W4', w4),
        ('W5', w5),
    ]


def fetch_delivery_snapshot_by_dates(stat_dates):
    """从基础表 glsx_daily_deal_subtotal 批量取各门店的「累计交付数(delivery_cnt)」快照。

    背景(用户 2026-09-24 明确):北汽结果表 W1/W2/W3 的综合渗透公式中,
      分子「订单数」实时查 D+;分母「新车交付数(累计交付数)」改从本基础表按
      **该周结束日的 stat_date** 取(日快照,由 GlsxDailyScheduler 每日产出)。

    :param stat_dates: 可迭代的 date 集合(各周结束日);None/空 → 返回 {}
    :return: {stat_date(date): {store_name: delivery_cnt}};
             缺失的日期不出现在返回 dict 中(调用方据此判「无快照 → 无法评估」)。
             任何异常返回 {}(不致命,仅告警),保证结果表生成不因缺快照而失败。
    """
    ds = [d for d in (stat_dates or []) if d]
    if not ds:
        return {}
    try:
        rows = (GlsxDailyDealSubtotal.query
                .filter(GlsxDailyDealSubtotal.stat_date.in_(ds),
                        GlsxDailyDealSubtotal.is_deleted == 0)
                .all())
        out = {}
        for r in rows:
            if r.stat_date is None:
                continue
            out.setdefault(r.stat_date, {})[r.store_name] = r.delivery_cnt
        logger.info(f'[北汽] 周度交付数快照:查询 {len(ds)} 个日期,命中 '
                    f'{len(out)} 个({ {str(k): len(v) for k, v in out.items()} })')
        return out
    except Exception as e:
        logger.warning(f'[北汽] 读取 glsx_daily_deal_subtotal 交付数快照失败: {e}')
        return {}


def _baic_light(penetration, excellent, standard):
    """按综合渗透与评灯标准判定门店等级灯色。

    :param penetration: 综合渗透小数(如 0.4363)或 None(无法计算)
    :param excellent:   优秀值小数(X 列)或 None(品牌未匹配)
    :param standard:    标准值小数(Y 列)或 None(品牌未匹配)
    :return: (灯色文字, 底色 hex) ;无法计算(渗透率为 None 或无标准值)返回 (None, None)
    规则:综合渗透 > 优秀值 → 绿;> 标准值 → 黄;否则 → 红。
    注意:渗透率为小数、标准值亦为小数,直接比较(勿 ×100 / 勿 ÷100)。
    """
    if penetration is None or standard is None:
        return None, None
    try:
        p = float(penetration)
        std = float(standard)
        exc = float(excellent) if excellent is not None else None
    except (TypeError, ValueError):
        return None, None
    if exc is not None and p > exc:
        return '绿', BAIC_LIGHT_FILL['绿']
    if p > std:
        return '黄', BAIC_LIGHT_FILL['黄']
    return '红', BAIC_LIGHT_FILL['红']


def _to_int(v):
    if v is None:
        return None
    s = str(v).strip().replace(',', '')
    if s == '':
        return None
    try:
        return int(Decimal(s))
    except (InvalidOperation, ValueError):
        logger.warning(f"[北汽] 非整数值被置空: {v!r}")
        return None


def _to_dec(v):
    if v is None:
        return None
    s = str(v).strip().replace(',', '')
    if s == '':
        return None
    try:
        return Decimal(s)
    except (InvalidOperation, ValueError):
        logger.warning(f"[北汽] 非小数值被置空: {v!r}")
        return None


def _to_rate(v):
    """比率值归一为小数比率。

    源文件汇总段的「售后场景开通率」由线上运营以**百分数**形式上传
    (如 22 表示 22%),而结果模板该列为 0.0% 格式、DB 列为 DECIMAL 小数,
    故 |v| > 1 时按百分数 ÷100;已是小数(|v| <= 1)则原样返回。
    """
    d = _to_dec(v)
    if d is None:
        return None
    try:
        return (d / Decimal(100)) if abs(d) > 1 else d
    except (InvalidOperation, TypeError):
        return None


def _safe_div(a, b):
    """安全除法:None/0 作 0;b 为 0 时返回 0"""
    a = a if a is not None else 0
    b = b if b is not None else 0
    try:
        return (a / b) if b != 0 else 0
    except (InvalidOperation, ZeroDivisionError, TypeError):
        return 0


def _safe_sub(a, b):
    """安全减法:任一为 None -> None;否则 a - b(转 float)"""
    if a is None or b is None:
        return None
    try:
        return float(a) - float(b)
    except (InvalidOperation, TypeError, ValueError):
        return None


def _prev_month_str(ym):
    """'2026-07' -> '2026-06'(跨年 2026-01 -> 2025-12);非法输入 -> None"""
    if not isinstance(ym, str) or '-' not in ym:
        return None
    try:
        y, m = ym.split('-')[:2]
        y, m = int(y), int(m)
    except (ValueError, TypeError):
        return None
    if m == 1:
        return f"{y - 1}-12"
    return f"{y}-{m - 1:02d}"


def _dec_to_float(v):
    """DECIMAL/None -> float/None(openpyxl 写 DECIMAL 不稳,转 float)"""
    if v is None:
        return None
    try:
        return float(v)
    except (InvalidOperation, TypeError, ValueError):
        return None


def _to_date(v):
    """business_start_date:DATE/DATETIME/字符串(YYYY-MM-DD) -> date;空 -> None"""
    if v is None:
        return None
    if isinstance(v, datetime):
        return v.date()
    if isinstance(v, date):
        return v
    s = str(v).strip()
    if s == '':
        return None
    try:
        return datetime.strptime(s[:10], '%Y-%m-%d').date()
    except ValueError:
        return s


def _set_cell(ws, r, c, v):
    """写入单元格;v 为 None 时显式清空。
    注意:openpyxl 的 ws.cell(r, c, value=None) 不会清除已存在的旧值,
    必须用 ws.cell(r, c).value = None 才能真正清空。"""
    ws.cell(r, c).value = v


class BaicSpecialProcessor:
    """北汽专项独立处理器"""

    def __init__(self, app=None):
        self.app = app

    # ============================================================
    # 附件模板下载(门店名称预填)
    # ============================================================

    def build_attachment_template(self):
        """基于附件模板预填门店名称(连续填充,自动扩展到全部门店),返回临时文件路径。

        门店来源:fetch_baic_store_info() 北汽项目组全量,**排除已闭店门店**
        (sale_close_store_record status=3,用户 2026-11-04;闭店查询失败时回退为全量预填)。
        布局:从 row3 起连续写门店名到 A 列(跳过 row1/2 表头);其余列及末尾汇总段示例值全部清空。
        末尾汇总段(北汽品牌汇总 / 售后门店数 / 售后场景开通率)随门店数动态下移,与门店列表之间
        保留一行空行作分隔,并复刻原模板汇总段样式(绿色标题行 + 黄色数据行,A-B 列填充、加粗、居中)。
        ⚠ D+ 不可达时 fetch_baic_store_info 返回 {},门店名列表为空(仅表头 + 空数据区 + 汇总段标签)。
        """
        # 门店名称列表(D+ 北汽项目组全量,排除已闭店,去重保序)
        store_info = fetch_baic_store_info()
        closed_codes = fetch_baic_closed_store_codes()
        seen = set()
        store_names = []
        excluded = 0
        for name, info in store_info.items():
            if name is None or name in seen:
                continue
            if closed_codes:
                code = (info or {}).get('store_code')
                if code is not None and str(code).strip() in closed_codes:
                    excluded += 1
                    continue
            seen.add(name)
            store_names.append(name)
        if excluded:
            logger.info(f"[北汽] 附件模板预填:排除已闭店门店 {excluded} 家,"
                        f"实际预填 {len(store_names)} 家")

        wb = openpyxl.load_workbook(BAIC_ATTACH_TEMPLATE_PATH)
        ws = wb[wb.sheetnames[0]]

        # ---- 1. 定位原模板汇总段,逐行逐列捕获样式 ----
        summary_labels = [BRAND_SUMMARY_LABEL, '售后门店数', '售后场景开通率']
        orig_summary_row = {}
        for r in range(1, ws.max_row + 1):
            v = ws.cell(row=r, column=1).value
            if v in summary_labels:
                orig_summary_row[v] = r

        def _capture_row_style(row):
            d = {}
            for c in range(1, ws.max_column + 1):
                cell = ws.cell(row=row, column=c)
                d[c] = (copy(cell.font), copy(cell.fill), copy(cell.border),
                        copy(cell.alignment), cell.number_format)
            return d

        summary_styles = [(lbl, _capture_row_style(orig_summary_row[lbl]))
                          for lbl in summary_labels]

        # 门店数据行边框(取自原模板任意门店行,如 row3),用于连续预填后保持表格线
        store_border = copy(ws.cell(row=3, column=1).border)

        # ---- 2. 解除数据区(row>=3)合并,避免清空/写入撞 MergedCell 只读 ----
        for rng in list(ws.merged_cells.ranges):
            if rng.min_row >= 3:
                ws.unmerge_cells(str(rng))

        # ---- 3. 清空整片数据区(值 + 样式)row>=3,消除原始示例门店/旧汇总段残留样式 ----
        blank_font = Font()
        blank_fill = PatternFill()
        blank_border = Border()
        blank_align = Alignment()
        for r in range(3, ws.max_row + 1):
            for c in range(1, ws.max_column + 1):
                cell = ws.cell(row=r, column=c)
                cell.value = None
                cell.font = blank_font
                cell.fill = blank_fill
                cell.border = blank_border
                cell.alignment = blank_align
                cell.number_format = 'General'

        # ---- 4. 连续预填门店名(row3 起),保留边框形成表格 ----
        n = len(store_names)
        for i, name in enumerate(store_names):
            r = 3 + i
            for c in range(1, ws.max_column + 1):
                ws.cell(row=r, column=c).border = store_border
            ws.cell(row=r, column=1, value=name)

        # ---- 5. 与门店列表之间留一行空行,再复刻汇总段(含原样式) ----
        gap_row = 3 + n                       # 空行分隔
        srow = gap_row + 1                     # 汇总段首行(随门店数变化)
        for i, (lbl, style) in enumerate(summary_styles):
            r = srow + i
            for c in range(1, ws.max_column + 1):
                fnt, fl, bd, al, nf = style[c]
                cell = ws.cell(row=r, column=c)
                cell.font = fnt
                cell.fill = fl
                cell.border = bd
                cell.alignment = al
                cell.number_format = nf
            ws.cell(row=r, column=1, value=lbl)

        # ---- 6. 删除尾部残留空行(含原模板多余门店行 / 旧汇总段样式行) ----
        last_row = srow + len(summary_styles) - 1
        if ws.max_row > last_row:
            ws.delete_rows(last_row + 1, ws.max_row - last_row)

        tmp_dir = tempfile.mkdtemp(prefix='baic_tpl_')
        path = os.path.join(tmp_dir, '北汽专项-门店数据模板.xlsx')
        wb.save(path)
        logger.info(f"[北汽] 生成附件模板:预填 {n} 家门店(含闭店),汇总段置于第 {srow} 行")
        return path, tmp_dir

    def process(self, task):
        """处理单个北汽专项任务:解析源文件 -> 落明细/汇总表 -> 置 COMPLETED"""
        task_id = task.id
        try:
            detail_rows, summary = self._parse(task)
            self._save(task, detail_rows, summary)

            task = DataProcessTask.query.filter_by(id=task_id).first()
            # 生成结果 Excel(基于用户模板:源文件 5 列覆盖 + 品牌汇总固定项)
            try:
                url = self.generate_result_excel(task)
            except Exception as ge:
                logger.warning(f"[北汽] 结果表生成失败(task {task_id}): {ge}")

            task.status = 'COMPLETED'
            task.result_file_url = url or ''   # 最终 Excel:基于用户模板生成
            task.error_msg = ''
            db.session.commit()
            logger.info(f"[北汽] 任务 {task_id} 处理完成:明细 {len(detail_rows)} 行,汇总 1 行")
        except Exception as e:
            db.session.rollback()
            mark_task_failed(task_id, str(e))
            raise

    # ============================================================
    # 调度器入口
    # ============================================================
    def scan_baic_special(self):
        """扫描 baic_special 类型的 PROCESSING 任务并逐个处理(供 BaicSpecialScheduler 调用)。"""
        logger.info("[北汽] 开始扫描 baic_special 待处理任务")
        tasks = DataProcessTask.query.filter_by(
            data_table_type='baic_special',
            status='PROCESSING',
            is_deleted=0,
        ).order_by(DataProcessTask.id.asc()).all()
        logger.info(f"[北汽] 扫描到 {len(tasks)} 个待处理任务")

        success_count = 0
        fail_count = 0
        for task in tasks:
            try:
                self.process(task)
                success_count += 1
                logger.info(f"[北汽] 任务 {task.id} 处理成功")
            except Exception as e:
                import traceback as _tb
                fail_count += 1
                logger.error(f"[北汽] 任务 {task.id} 处理失败: {str(e)}")
                logger.error(_tb.format_exc())
                try:
                    mark_task_failed(task.id, str(e))
                except Exception as mark_err:
                    logger.error(f"[北汽] 标记任务失败时出错: {mark_err}")

        logger.info(f"[北汽] 扫描完成,成功 {success_count},失败 {fail_count}")
        return {'success': success_count, 'failed': fail_count}

    def scan_baic_weekly(self):
        """手动补数入口:**只写 glsx_daily_deal_subtotal 基础表,不做其他逻辑**。

        口径(用户 2026-09-24 明确,2026-09-24 晚已下线对应定时任务):
        - 原为「每周日 23:00」定时任务,现该定时任务已移除,改为**仅保留每日快照任务**
          (GlsxDailyScheduler,每日 07:00 写 stat_date=昨天),本方法仅保留作手动补数用;
        - 本方法**不写** baic_special_month_data 的任何字段(w{n}_order_cnt /
          w{n}_new_delivery_cnt / w{n}_comprehensive_penetration / w{n}_light_level 均由
          结果表生成 generate_result_excel 按渲染口径回写);
        - 本方法**不查** D+ 订单数。

        动作:把「今天」的通用品牌报表快照落库基础表
        (glsx_daily_processor.snapshot_glsx(stat_date=今天),按 stat_date 幂等)。
        该日快照即北汽 W1/W2/W3 综合渗透「新车交付数」分母的来源。
        """
        today = date.today()
        try:
            from glsx_daily_processor import snapshot_glsx
        except Exception as e:
            logger.error(f"[北汽周快照] 导入 snapshot_glsx 失败: {e}")
            return {'success': 0, 'error': str(e)}
        result = snapshot_glsx(today)
        logger.info(f"[北汽周快照] 基础表快照(stat_date={today})结果: {result}")
        return result

    # ============================================================
    # 解析
    # ============================================================
    def _parse(self, task):
        task_id = task.id
        tmp_dir = tempfile.mkdtemp(prefix=f'baic_{task_id}_')
        try:
            file_map = download_all_files(task_id, tmp_dir)
            path = None
            for _form, p in file_map.items():
                if p:
                    path = p
                    break
            if not path:
                raise Exception('未找到可下载的北汽专项附件(北汽专项源数据表)')
            wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
            ws = wb[wb.sheetnames[0]]
            rows = list(ws.iter_rows(values_only=True))
        finally:
            cleanup_tmp_dir(tmp_dir)

        detail_rows = []
        summary_vals = {attr: None for attr in SUMMARY_LABELS.values()}
        brand = None
        # 跳过前 2 行表头(主表头 + 子表头),从第 3 行起取门店明细;
        # 末尾汇总段(如 r52「北汽品牌汇总」+ r53 售后门店数 + r54 售后场景开通率)单独解析。
        for row in rows[2:]:
            a = row[0] if len(row) > 0 else None
            if a is None or str(a).strip() == '':
                continue  # 隔行空白占位 / 空行跳过
            label = str(a).strip()
            if label == BRAND_SUMMARY_LABEL:
                brand = '北汽'
                continue
            if label in SUMMARY_LABELS:
                attr = SUMMARY_LABELS[label]
                val = row[1] if len(row) > 1 else None
                summary_vals[attr] = _to_rate(val) if attr in RATE_SUMMARY_ATTRS else val
                continue
            rec = {
                'store_name': str(a).strip(),
                'brand': (str(row[SRC_BRAND]).strip()
                          if len(row) > SRC_BRAND and row[SRC_BRAND] not in (None, '') else None),
                'underwriting_rule': (str(row[SRC_UNDERWRITING]).strip()
                          if len(row) > SRC_UNDERWRITING and row[SRC_UNDERWRITING] not in (None, '') else None),
                'delivery_check_group_cnt': (_to_int(row[SRC_DELIVERY_GROUP])
                          if len(row) > SRC_DELIVERY_GROUP else None),
                'visit_check_group_cnt': (_to_int(row[SRC_VISIT_GROUP])
                          if len(row) > SRC_VISIT_GROUP else None),
            }
            # 跳过纯标签/汇总段行(品牌与数值均为空),仅保留真实门店行
            if (rec['brand'] is None
                    and rec['delivery_check_group_cnt'] is None
                    and rec['visit_check_group_cnt'] is None):
                continue
            detail_rows.append(rec)

        if not detail_rows:
            logger.warning(f"[北汽] 任务 {task_id} 未解析到任何明细门店行")
        logger.info(f"[北汽] 任务 {task_id} 汇总段解析:{summary_vals}")

        # ---- 补充 D+ 系统基础信息(门店编码/区域/驻店类型/业务开展/区域运营)----
        store_info = fetch_baic_store_info()
        matched = 0
        unmatched = []
        for rec in detail_rows:
            info = store_info.get(rec['store_name'])
            if info:
                matched += 1
                rec.update(info)
            else:
                unmatched.append(rec['store_name'])
                rec.update({'store_code': None, 'region': None, 'store_type': None,
                            'business_start_date': None, 'operator_name': None,
                            'resident_staff': None})
        logger.info(f"[北汽] 任务 {task_id} D+ 基础信息匹配:{matched}/{len(detail_rows)} 家"
                    + (f";未匹配 {unmatched}" if unmatched else ""))

        # ---- 补充广联报表(产值目标/新车交付数/触客数系统/交车数核对-产值表/触客数核对-产值表)----
        stat_month = (getattr(task, 'month', None) or '')
        glsx_map = fetch_glsx_report(stat_month)
        glsx_matched = 0
        glsx_unmatched = []
        for rec in detail_rows:
            g = glsx_map.get(rec['store_name'])
            if g:
                glsx_matched += 1
                rec.update(g)
            else:
                glsx_unmatched.append(rec['store_name'])
                rec.update({'output_target_wan': None, 'new_delivery_cnt': None,
                            'visit_cnt': None, 'delivery_check_output_cnt': None,
                            'visit_check_output_cnt': None})
        logger.info(f"[北汽] 任务 {task_id} 广联报表匹配:{glsx_matched}/{len(detail_rows)} 家"
                    + (f";未匹配 {glsx_unmatched}" if glsx_unmatched else ""))

        # ---- 触客率 = 触客数 ÷ 新车交付数(广联报表口径;触客数=延保小计行 O,交付数=非小计行 K 取 max)----
        rate_hit = 0
        for rec in detail_rows:
            rec['visit_rate'] = _ratio(_to_int(rec.get('visit_cnt')),
                                       _to_int(rec.get('new_delivery_cnt')))
            if rec['visit_rate'] is not None:
                rate_hit += 1
        logger.info(f"[北汽] 任务 {task_id} 触客率计算:{rate_hit}/{len(detail_rows)} 家"
                    f"(新车交付数为空或 0 的门店留空)")

        # ---- 补充「截止目前产值」(D+ 支付成功金额汇总)与「达成率」----
        # 需在 D+ 基础信息(拿 store_code)与广联报表(拿产值目标)之后执行。
        p_start, p_end = _task_period(task)
        code_recs = {}
        for rec in detail_rows:
            code = rec.get('store_code')
            if code:
                code_recs.setdefault(str(code), []).append(rec)
        current_map = fetch_output_current(p_start, p_end, code_recs.keys())
        cur_hit = 0
        for code, recs in code_recs.items():
            wan = current_map.get(code)
            if wan is None:
                for rec in recs:
                    rec['output_current_wan'] = None
                    rec['achievement_rate'] = None
                continue
            cur_hit += 1
            for rec in recs:
                rec['output_current_wan'] = wan
                target = _to_dec(rec.get('output_target_wan'))
                # 达成率 = 截止目前产值 ÷ 产值目标(同为万元,比值为无量纲小数)
                rec['achievement_rate'] = ((Decimal(str(wan)) / target)
                                           if target else None)
        logger.info(f"[北汽] 任务 {task_id} 截止目前产值:{cur_hit}/{len(code_recs)} 家"
                    f"(共 {len(detail_rows)} 家门店,{len(detail_rows) - len(code_recs)} 家无门店编码)")

        # ---- 补充「延保/权益订单数」(D+ 子订单 dj_car_life_goods_sub_order)----
        # 需在 D+ 基础信息(拿 store_code)之后执行;按门店编码匹配,写入 rec 待 _save 落库。
        order_map = fetch_order_count(p_start, p_end, code_recs.keys())
        for code, recs in code_recs.items():
            om = order_map.get(code, {})
            ew = om.get(BAIC_BIZ_EXT_WARRANTY)
            rt = om.get(BAIC_BIZ_RIGHTS)
            for rec in recs:
                rec['ext_warranty_order_cnt'] = ew
                rec['rights_order_cnt'] = rt
        logger.info(f"[北汽] 任务 {task_id} 订单数:{len(order_map)}/{len(code_recs)} 家门店命中"
                    f"(整车延保/原厂权益)")

        return detail_rows, (brand, summary_vals)

    # ============================================================
    # 落库(按 task_id 先删后插,幂等)
    # ============================================================
    def _save(self, task, detail_rows, summary_tuple):
        task_id = task.id
        period_start = getattr(task, 'period_start', None)
        stat_month = (getattr(task, 'month', None) or ''
                      or (period_start.strftime('%Y-%m') if period_start else ''))

        # ---------- 明细 ----------
        # 逻辑删除(软删除):将本任务旧行置 is_deleted=1,再插入新行(is_deleted=0)
        BaicSpecialMonthData.query.filter_by(task_id=task_id, is_deleted=0).update(
            {BaicSpecialMonthData.is_deleted: 1}, synchronize_session=False)
        db.session.flush()
        detail_objs = []
        for rec in detail_rows:
            # 核对值先归一为 int,再据此计算差异,保证落库与结果表口径完全一致
            dc_output = _to_int(rec.get('delivery_check_output_cnt'))
            dc_group = _to_int(rec.get('delivery_check_group_cnt'))
            vc_output = _to_int(rec.get('visit_check_output_cnt'))
            vc_group = _to_int(rec.get('visit_check_group_cnt'))
            # 评灯标准按品牌固定取值(北汽极狐 0.5/0.3/0.3;北京越野 0.5/0.4/0.4)
            lv_excellent, lv_standard, lv_warning = _light_standard(rec.get('brand'))
            detail_objs.append(BaicSpecialMonthData(
                task_id=task_id,
                is_deleted=0,
                stat_month=stat_month,
                store_name=rec.get('store_name') or '',
                brand=rec.get('brand'),
                # 区域 / 驻店类型来自 D+ 系统(NOT NULL,未匹配时占位空串)
                region=rec.get('region') or '',
                store_type=rec.get('store_type') or '',
                store_code=rec.get('store_code'),
                business_start_date=_to_date(rec.get('business_start_date')),
                operator_name=rec.get('operator_name'),
                # 驻店人员来自 SCRM(园区店「驻店人员」角色,多人以「/」分隔)
                resident_staff=rec.get('resident_staff'),
                underwriting_rule=rec.get('underwriting_rule'),
                delivery_check_group_cnt=dc_group,
                visit_check_group_cnt=vc_group,
                # 广联报表(dj.glsx.com.cn 延保+权益门店产值及个人成交排名·通用品牌):
                #   output_target_wan       <- 延保小计行 H(8月目标产值(万元))
                #   new_delivery_cnt        <- 非小计行 K(累计交付数(台))同店取 max
                #   visit_cnt               <- 延保小计行 O(实际售前触客数,2026-11-04 起小计行口径;原为非小计行取 max)
                #   delivery_check_output_cnt   <- 延保小计行 K(交车数核对-产值表)
                #   visit_check_output_cnt      <- 延保小计行 O(触客数核对-产值表)
                #   以上 5 项按门店名从报表匹配;未匹配门店留 NULL。
                output_target_wan=_to_dec(rec.get('output_target_wan')),
                # 截止目前产值(万,D+ 支付成功金额/10000)与达成率(=截止目前产值 ÷ 产值目标)
                output_current_wan=_to_dec(rec.get('output_current_wan')),
                achievement_rate=_to_dec(rec.get('achievement_rate')),
                new_delivery_cnt=_to_int(rec.get('new_delivery_cnt')),
                visit_cnt=_to_int(rec.get('visit_cnt')),
                # 触客率 = 触客数 ÷ 新车交付数(无量纲小数,任一侧为空或分母 0 → NULL)
                visit_rate=_to_dec(rec.get('visit_rate')),
                delivery_check_output_cnt=dc_output,
                visit_check_output_cnt=vc_output,
                # 差异 = 产值表 - 一店一群(任一侧为空则留 NULL),与结果表 AC/AF 列同口径
                delivery_check_diff=_diff(dc_output, dc_group),
                visit_check_diff=_diff(vc_output, vc_group),
                # 评灯标准(优秀值/标准值/预警值):按品牌固定取值,未匹配品牌留 NULL
                excellent_value=_to_dec(lv_excellent),
                standard_value=_to_dec(lv_standard),
                warning_value=_to_dec(lv_warning),
            ))
        db.session.add_all(detail_objs)
        # flush 以拿到自增 store_id,供下方业务行(baic_special_monthly_business)外键引用
        db.session.flush()

        # 确保业务表存在(首次部署时按 ORM 定义补建,checkfirst 幂等;不删除任何数据)
        BaicSpecialMonthlyBusiness.__table__.create(db.engine, checkfirst=True)

        # ---------- 业务(逐门店×业务:延保/权益)----------
        # 订单数来自 D+ 子订单(dj_car_life_goods_sub_order),经 fetch_order_count 计算后挂在 rec 上。
        # 幂等:先按本任务主表明细 store_id 删除旧业务行,再插入新行(该表无 is_deleted 列,物理删除)。
        old_biz_ids = [r.store_id for r in BaicSpecialMonthData.query.filter_by(task_id=task_id).all()]
        if old_biz_ids:
            BaicSpecialMonthlyBusiness.query.filter(
                BaicSpecialMonthlyBusiness.store_id.in_(old_biz_ids)).delete(synchronize_session=False)
            db.session.flush()
        biz_objs = []
        for rec, obj in zip(detail_rows, detail_objs):
            sid = obj.store_id
            ew = _to_int(rec.get('ext_warranty_order_cnt'))
            rt = _to_int(rec.get('rights_order_cnt'))
            if ew is not None:
                biz_objs.append(BaicSpecialMonthlyBusiness(
                    store_id=sid, business_type=BAIC_BIZ_EXT_WARRANTY, order_cnt=ew))
            if rt is not None:
                biz_objs.append(BaicSpecialMonthlyBusiness(
                    store_id=sid, business_type=BAIC_BIZ_RIGHTS, order_cnt=rt))
        db.session.add_all(biz_objs)

        # ---------- 汇总(单任务一行)----------
        # 逻辑删除(软删除)旧汇总行,再插入新行
        BaicSpecialMonthSummaryMetrics.query.filter_by(task_id=task_id, is_deleted=0).update(
            {BaicSpecialMonthSummaryMetrics.is_deleted: 1}, synchronize_session=False)
        db.session.flush()
        brand, summary_vals = summary_tuple if summary_tuple else (None, {})
        sum_obj = BaicSpecialMonthSummaryMetrics(
            task_id=task_id,
            is_deleted=0,
            stat_month=stat_month,
            project_name='北汽',
            brand='极狐/越野',
            store_cnt=len(detail_objs),
            # 源文件末尾汇总段(品牌级手工上传):售后门店数 / 售后场景开通率
            after_sale_store_cnt=_to_int(summary_vals.get('after_sale_store_cnt')),
            after_sale_scene_open_rate=_to_dec(summary_vals.get('after_sale_scene_open_rate')),
            after_sale_order_cnt=_to_int(summary_vals.get('after_sale_order_cnt')),
            # 其余列(产值/交付/触客/渗透/环比)来自 D+ 系统或系统计算,本轮留空
        )
        db.session.add(sum_obj)
        db.session.commit()
        logger.info(f"[北汽] 落库完成:明细 {len(detail_objs)} 行 + 汇总 1 行(task_id={task_id},"
                    f"售后门店数={sum_obj.after_sale_store_cnt},"
                    f"售后场景开通率={sum_obj.after_sale_scene_open_rate})")

    # ============================================================
    # 结果表生成(基于模板 exporttemplete/baic_special_report_template.xlsx)
    # ============================================================
    def generate_result_excel(self, task):
        """根据 task 生成「北汽专项报表」结果 Excel:
        - 复制模板布局;标题月份 / 截止日期 / 品牌汇总段月份标签占位替换;
        - 按 store_name 用 DB 源值覆盖 5 列(门店名称/品牌/兜底门店/一店一群交车/一店一群触客);
        - 品牌汇总本月段(r59)项目/品牌/门店数 覆盖;其余系统列保留模板原样;
        - 生成后上传 OSS 并回填 result_file_url。
        返回 OSS 可访问 URL(失败抛异常)。"""
        task_id = task.id
        month = getattr(task, 'month', None) or ''

        # 报表月标签 / 上月标签
        if len(month) >= 7 and month[4] == '-':
            try:
                y, m = int(month[:4]), int(month[5:7])
                month_label = f"{m}月"
                pm = m - 1 if m > 1 else 12
                prev_month_label = f"{pm}月"
            except (ValueError, IndexError):
                month_label, prev_month_label = '', ''
        else:
            month_label, prev_month_label = '', ''

        # 截止日期规则:用报表所属月;若当前时间已在所属月之后 → 取所属月最后一天(封账)
        today = date.today()
        cutoff_date = datetime.now().strftime('%Y-%m-%d')  # 兜底
        if len(month) >= 7 and month[4] == '-':
            try:
                y, m = int(month[:4]), int(month[5:7])
                last_day = monthrange(y, m)[1]
                report_month_last = date(y, m, last_day)
                cutoff_date = (report_month_last if today > report_month_last
                               else today).strftime('%Y-%m-%d')
            except (ValueError, IndexError):
                cutoff_date = datetime.now().strftime('%Y-%m-%d')

        details = BaicSpecialMonthData.query.filter_by(
            task_id=task_id, is_deleted=0).order_by(BaicSpecialMonthData.store_id).all()
        # 汇总表(单任务一行):售后门店数 / 售后场景开通率 来源于源文件汇总段
        summary = BaicSpecialMonthSummaryMetrics.query.filter_by(
            task_id=task_id, is_deleted=0).order_by(
            BaicSpecialMonthSummaryMetrics.id.desc()).first()

        # 业务订单数(逐门店×业务):store_id -> {业务类型编码: 订单数}(来自 baic_special_monthly_business)
        store_ids = [d.store_id for d in details]
        biz_rows = (BaicSpecialMonthlyBusiness.query.filter(
            BaicSpecialMonthlyBusiness.store_id.in_(store_ids)).all()
            if store_ids else [])
        biz_map = {}
        for br in biz_rows:
            biz_map.setdefault(br.store_id, {})[br.business_type] = br.order_cnt

        # ---- 周度评灯取数:各节点(截止目前/W1/W2/W3)当月累计订单数 ----
        # 综合渗透(节点) = 当月累计(延保+权益)订单数 ÷ 新车交付数;
        #   · 分子:W1/W2/W3 取「截止到当前周」累计(窗口起点=当月1号,上界=各周结束日+1天),实时查 D+
        #   · 分母:W1/W2/W3 取该周结束日快照(glsx_daily_deal_subtotal.delivery_cnt,见下方 week_delivery_by_node)
        #   · 截止目前节点:分子上界=cutoff_date(封账后=当月最后一天),分母用全月实时 new_delivery_cnt
        month_start_obj = None
        if len(month) >= 7 and month[4] == '-':
            try:
                month_start_obj = date(int(month[:4]), int(month[5:7]), 1)
            except (ValueError, IndexError):
                month_start_obj = None
        cutoff_date_obj = _to_date(cutoff_date)
        week_nodes = compute_baic_week_ends(month, cutoff_date_obj)
        store_codes = [d.store_code for d in details if d.store_code]
        # ---- 售后订单数(J 列,品牌汇总·本月段):用户 2026-10-16 新口径 ----
        # 主订单 a + 支付单 b(pay_status=2) + 客户单 c(sales_type=1),按商户 COUNT(0) 得合并总数(不分延保/权益)。
        # K/M(整车延保/原厂权益成交数)仍走旧 biz_map 子订单拆分逻辑(用户明确保持旧逻辑)。
        _after_sale_total = 0
        if month_start_obj and store_codes:
            _aso = fetch_after_sale_order_count(
                month_start_obj, _month_last_day(month_start_obj), store_codes)
            _after_sale_total = sum(_aso.values())
        window_biz_by_node = []   # 与 week_nodes 同序:{store_code(str): {biz: cnt}}
        for (_lbl, _end) in week_nodes:
            if month_start_obj and _end:
                window_biz_by_node.append(
                    fetch_order_count_window(month_start_obj, _end, store_codes))
            else:
                window_biz_by_node.append({})
        logger.info(f"[北汽] 周度评灯节点: {[(lbl, (d.strftime('%Y-%m-%d') if d else None)) for lbl, d in week_nodes]}"
                    f";门店编码 {len(store_codes)} 个")

        # ---- 周度分母取数:W1/W2/W3 的「新车交付数」改从基础表 glsx_daily_deal_subtotal 取 ----
        # (用户 2026-09-24 明确:综合渗透公式的分子订单数实时查 D+,
        #   分母新车交付数(累计交付数) 从 glsx_daily_deal_subtotal 按该周结束日 stat_date 查)
        # 截止目前(T) 仍用全月实时 new_delivery_cnt(本次不改)。
        # 快照缺失(该日期无日快照)→ 该门店该周分母 None → 渗透留空且不评灯。
        _week_ends = [end for (_lbl, end) in week_nodes[1:] if end]
        _snap_delivery = fetch_delivery_snapshot_by_dates(_week_ends)
        week_delivery_by_node = [
            None if j == 0 else _snap_delivery.get(_end, {})
            for j, (_lbl, _end) in enumerate(week_nodes)
        ]

        if not os.path.exists(BAIC_TEMPLATE_PATH):
            raise Exception(f'北汽结果表模板不存在:{BAIC_TEMPLATE_PATH}')
        wb = openpyxl.load_workbook(BAIC_TEMPLATE_PATH)
        ws = wb[wb.sheetnames[0]]

        # ---- 标题 ----
        ws['A1'] = f"北汽专项报表 ·「{month_label}」页签 ·  数据截止 {cutoff_date}"

        # ---- 明细门店:动态展开(每家拆 延保/权益 两行,参照示例块 r6/r7)----
        EX1, EX2 = 6, 7  # 示例块:r6=延保行, r7=权益行
        n = len(details)
        if n == 0:
            raise Exception('北汽明细数据为空,无法生成结果表')

        # 示例块的两行合并(rows 6/7),用于新块复制
        example_merges = [str(r) for r in ws.merged_cells.ranges
                          if r.min_row == EX1 and r.max_row == EX2]

        # 可写入的列:源文件字段 + D+ 基础信息(区域/驻店类型/运营/业务开展/驻店人员)
        #          + 广联报表(产值目标/新车交付数/触客数/交车数核对-产值表/触客数核对-产值表)
        # 12/13 = 截止目前产值(万)/ 达成率(D+);26/27/28 = 评灯标准(按品牌固定取值)
        # 20/21/22/23/24/25 = 周度评灯(截止目前/W1~W5),由代码按综合渗透+评灯标准填灯色+底色
        # 注:本门店块已显式写入全部 1~34 列(A~AH),无需再按白名单清空(见 _fill_block 末尾说明)。

        def _fill_block(r_a, r_b, idx, d):
            # r_a 为两行合并的锚点行:可写入/清空本块所有列(合并区显示锚点值)
            _set_cell(ws, r_a, 1, idx)                          # A 序号
            _set_cell(ws, r_a, 2, d.region or None)             # B 区域(D+)
            _set_cell(ws, r_a, 3, d.store_type or None)         # C 驻店类型(D+:直营/服务商)
            _set_cell(ws, r_a, 4, d.store_name)                 # D 门店名称
            _set_cell(ws, r_a, 5, d.brand)                      # E 品牌
            _set_cell(ws, r_a, 6, d.operator_name)              # F 运营(D+ 区域运营)
            _set_cell(ws, r_a, 7, d.business_start_date)        # G 业务开展(D+)
            _set_cell(ws, r_a, 8, d.resident_staff)             # H 驻店人员(SCRM,多人「/」分隔)
            _set_cell(ws, r_a, 9, '延保')                       # I 业务
            _set_cell(ws, r_a, 10, d.underwriting_rule or '无')  # J 兜底门店
            _set_cell(ws, r_a, 11, _dec_to_float(d.output_target_wan))  # K 产值目标(万,广联报表)
            _set_cell(ws, r_a, 12, _dec_to_float(d.output_current_wan)) # L 截止目前产值(万,D+)
            _set_cell(ws, r_a, 13, _dec_to_float(d.achievement_rate))   # M 达成率(=L/K)
            _set_cell(ws, r_a, 14, d.new_delivery_cnt)          # N 新车交付数(广联报表)
            _set_cell(ws, r_a, 15, d.visit_cnt)                 # O 触客数(广联报表)
            _set_cell(ws, r_a, 16, _dec_to_float(d.visit_rate)) # P 触客率(=触客数÷新车交付数)
            # 评灯标准(按品牌固定取值:北汽极狐 0.5/0.3/0.3;北京越野 0.5/0.4/0.4)
            _set_cell(ws, r_a, 26, _dec_to_float(d.excellent_value))  # Z 优秀值
            _set_cell(ws, r_a, 27, _dec_to_float(d.standard_value))   # AA 标准值
            _set_cell(ws, r_a, 28, _dec_to_float(d.warning_value))    # AB 预警值
            _set_cell(ws, r_a, 29, d.delivery_check_output_cnt) # AC 交车数核对-产值表(广联报表)
            _set_cell(ws, r_a, 30, d.delivery_check_group_cnt)  # AD 一店一群交车数
            _set_cell(ws, r_a, 32, d.visit_check_output_cnt)    # AF 触客数核对-产值表(广联报表)
            _set_cell(ws, r_a, 33, d.visit_check_group_cnt)     # AG 一店一群触客数
            # 差异列 = 产值表 - 一店一群(任一侧为空则差异为空)
            _set_cell(ws, r_a, 31, _diff(d.delivery_check_output_cnt, d.delivery_check_group_cnt))  # AE 交车数核对-差异
            _set_cell(ws, r_a, 34, _diff(d.visit_check_output_cnt, d.visit_check_group_cnt))       # AH 触客数核对-差异
            # 订单数(D+ 子订单,按业务类型)与渗透率
            new_delivery = d.new_delivery_cnt   # N 新车交付数
            ext_cnt = biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY)    # 整车延保订单数
            rights_cnt = biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS)       # 原厂权益订单数
            # Q 订单数
            _set_cell(ws, r_a, 17, ext_cnt)     # Q 延保订单数
            # R 交车渗透率 = 本行订单数 ÷ 新车交付数
            _set_cell(ws, r_a, 18, _penetration(ext_cnt, new_delivery))
            # S 综合渗透 = (延保订单数 + 权益订单数) ÷ 新车交付数(门店级,两行同值)
            _combined = ((ext_cnt if ext_cnt is not None else 0)
                         + (rights_cnt if rights_cnt is not None else 0))
            _set_cell(ws, r_a, 19, _penetration(_combined, new_delivery))
            # ---- 周度评灯(截止目前/W1~W5):T~Y 列(BAIC_LIGHT_COLS)----
            # 综合渗透(节点) = 当月累计(延保+权益)订单数 ÷ 新车交付数
            #   · 分子:W1~W5 订单数取「截止到当前周」累计(见 window_biz_by_node),实时查 D+
            #   · 分母:W1~W5 用该周结束日快照(glsx_daily_deal_subtotal.delivery_cnt,
            #           见 week_delivery_by_node);截止目前(T) 仍用全月实时 new_delivery_cnt
            #   · 分母缺失(该周结束日无日快照 / 交付数为 0)→ 渗透 None → 该格留空且不评灯
            #   · 该周不存在(W5 起始超出月末等)→ 节点无数据,灯格与周度字段全部留空
            # 灯色:综合渗透 > 优秀值(X) → 绿;> 标准值(Y) → 黄;否则 → 红(底色见 BAIC_LIGHT_FILL)
            # 评灯标准为小数(如 0.5=50%),与综合渗透(小数)直接比较,切勿 ×100。
            scode = str(d.store_code) if d.store_code is not None else None
            for j, (_lbl, _end) in enumerate(week_nodes):
                wb_node = window_biz_by_node[j] if j < len(window_biz_by_node) else {}
                ec = wb_node.get(scode, {}).get(BAIC_BIZ_EXT_WARRANTY) if scode else None
                rc = wb_node.get(scode, {}).get(BAIC_BIZ_RIGHTS) if scode else None
                comb_node = ((ec if ec is not None else 0)
                             + (rc if rc is not None else 0))
                # 分母:j=0(截止目前)用全月实时新车交付数;W1/W2/W3 用该周结束日快照
                if j == 0:
                    node_delivery = new_delivery
                else:
                    _snap = week_delivery_by_node[j] if j < len(week_delivery_by_node) else {}
                    node_delivery = _snap.get(d.store_name)
                pen_node = _penetration(comb_node, node_delivery)
                light_txt, light_fill = _baic_light(pen_node, d.excellent_value, d.standard_value)
                col = BAIC_LIGHT_COLS[j]
                _set_cell(ws, r_a, col, light_txt)   # 绿/黄/红 文字(None=无法评估,留空)
                # 显式清/设底色:有灯色则填充;无灯色(无法评估,如门店无编码/无标准值)
                # 必须清除模板示例块/插入行的残留底色,避免误显为某色灯。
                ws.cell(r_a, col).fill = (
                    PatternFill(start_color=light_fill, end_color=light_fill, fill_type='solid')
                    if light_fill else PatternFill(fill_type='none'))
                # ---- 回写 baic_special_month_data:截止目前 + W1/W2/W3 周度字段(与 Excel 同口径)----
                # j=0 为「截止目前」节点 → 落到单列表 comprehensive_penetration / current_light;
                # j=1/2/3 → w1/w2/w3。
                #   *_order_cnt           该周累计(延保+权益)订单数(无门店编码→None,无法统计)
                #   *_new_delivery_cnt    该周结束日快照交付数(无快照→None)
                #   *_comprehensive_penetration  综合渗透(分母缺失→None)
                #   *_light_level         灯级(绿/黄/红;无法评估→None)
                if j == 0:
                    setattr(d, 'comprehensive_penetration', pen_node)
                    setattr(d, 'current_light', light_txt)
                elif _end is None:
                    # 该周不存在(如 W5 起始超出月末)→ 周度字段全部留空
                    setattr(d, f'w{j}_order_cnt', None)
                    setattr(d, f'w{j}_new_delivery_cnt', None)
                    setattr(d, f'w{j}_comprehensive_penetration', None)
                    setattr(d, f'w{j}_light_level', None)
                else:
                    setattr(d, f'w{j}_order_cnt', (comb_node if scode else None))
                    setattr(d, f'w{j}_new_delivery_cnt',
                            (int(node_delivery) if node_delivery is not None else None))
                    setattr(d, f'w{j}_comprehensive_penetration', pen_node)
                    setattr(d, f'w{j}_light_level', light_txt)
            # 说明:_fill_block 已显式写入本门店块的全部 1~34 列(A~AH),
            # 不存在「已写入列之外、仍需清空的 1~34 列」,故原先用于清空白名单外列的循环为 no-op,已移除。
            # 34 列之外(AI 起)的内容保持模板原样,不受本函数影响。
            # r_b(权益行)仅非合并列可写:业务(I) + Q/R/S
            _set_cell(ws, r_b, 9, '权益')
            _set_cell(ws, r_b, 17, rights_cnt)  # Q 权益订单数
            _set_cell(ws, r_b, 18, _penetration(rights_cnt, new_delivery))  # R 交车渗透率
            # 注:S(19) 综合渗透为两行合并的只读格,仅写在 r_a 锚点行(见上),
            #     合并区会自动把门店级同值显示到本行。

        # 一次性在示例块之后插入 (n-1)*2 行。
        # 注意:openpyxl 的 insert_rows 只移动单元格值、不移动已合并区域,
        # 故先解除「示例块之后」的合并(品牌汇总段标签行 A10:AF10 / A14:AF14),
        # 插入后按偏移重建,避免标签合并区压住门店行导致取值丢失。
        extra = (n - 1) * 2
        shift_merges = [(rng.min_col, rng.min_row, rng.max_col, rng.max_row)
                        for rng in ws.merged_cells.ranges if rng.min_row >= EX2 + 1]
        for (_c1, _r1, _c2, _r2) in shift_merges:
            ws.unmerge_cells(f"{get_column_letter(_c1)}{_r1}:{get_column_letter(_c2)}{_r2}")
        if extra > 0:
            ws.insert_rows(EX2 + 1, extra)
        for (_c1, _r1, _c2, _r2) in shift_merges:
            ws.merge_cells(
                f"{get_column_letter(_c1)}{_r1 + extra}:"
                f"{get_column_letter(_c2)}{_r2 + extra}")
        # 逐块填写:第 i 家(0-based)占 r_a=6+2i(延保)/ r_b=r_a+1(权益)
        for i in range(n):
            r_a = EX1 + 2 * i
            r_b = r_a + 1
            if i > 0:
                # 复制示例块样式并重建两行合并单元格
                for c in range(1, 35):
                    ws.cell(r_a, c)._style = copy(ws.cell(EX1, c)._style)
                    ws.cell(r_b, c)._style = copy(ws.cell(EX2, c)._style)
                delta = 2 * i
                for mr in example_merges:
                    L, R = mr.split(':')
                    m_l = re.match(r'([A-Z]+)(\d+)', L)
                    m_r = re.match(r'([A-Z]+)(\d+)', R)
                    new_mr = (f"{m_l.group(1)}{int(m_l.group(2)) + delta}:"
                              f"{m_r.group(1)}{int(m_r.group(2)) + delta}")
                    try:
                        ws.merge_cells(new_mr)
                    except Exception:
                        pass
            _fill_block(r_a, r_b, i + 1, details[i])

        # ---- 合计行(r4/r5):订单数按业务类型汇总 + 渗透率 ----
        # r4 为两行合并的锚点行,写 r4 即可清空合并区显示;
        # Q/R/S(订单数/交车渗透率/综合渗透)为非合并列,需对 r5 单独写。
        ext_total = sum((biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY) or 0) for d in details)
        rights_total = sum((biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS) or 0) for d in details)
        total_delivery = sum((d.new_delivery_cnt or 0) for d in details)  # 全门店新车交付数合计
        # 清空 r4 的 11~34 计算列(保留 R/S 后续单独填)
        for c in range(11, 35):
            if c in (18, 19):
                continue
            _set_cell(ws, 4, c, None)
        _set_cell(ws, 5, 17, None)
        # 订单数列(Q=17):r4=延保合计,r5=权益合计(D+ 子订单统计)
        _set_cell(ws, 4, 17, ext_total)
        _set_cell(ws, 5, 17, rights_total)
        # 交车渗透率(R=18):本业务订单数合计 ÷ 全门店新车交付数合计
        _set_cell(ws, 4, 18, _penetration(ext_total, total_delivery))
        _set_cell(ws, 5, 18, _penetration(rights_total, total_delivery))
        # 综合渗透(S=19):(延保合计 + 权益合计) ÷ 全门店新车交付数合计。
        # S 列为两行合并只读格,仅写 r4 锚点行,合并区显示到 r5。
        _combined_total = ext_total + rights_total
        _set_cell(ws, 4, 19, _penetration(_combined_total, total_delivery))

        # ---- 合计行:产值目标/截止目前产值/达成率/新车交付数/触客数/触客率/交车·触客核对(12 项求和)----
        # 合计行 r4 为两行合并锚点(K/L/M/N/O/P/AA/AB/AC/AD/AE/AF 均为合并列),写 r4 即在合并区显示。
        # 比率列(达成率 M、触客率 P)按「合计分子 ÷ 合计分母」计算,不做简单比率加和(比率相加无意义);
        # 差异列合计 = 逐店「差异」之和(仅累计两列均有值、差异非空的门店;任一为空的门店差异本身留空,不计入合计)。
        #   不可直接「合计产值表 − 合计一店一群」:后者会把「产值表缺失(通用品牌报表未命中)」的门店当 0 相减,
        #   使合计差异偏离逐店可见差异之和(如 4 家门店产值表为空但一店一群有值,会凭空计入负差)。
        total_target = sum((_dec_to_float(d.output_target_wan) or 0) for d in details)   # K 产值目标合计(万)
        total_current = sum((_dec_to_float(d.output_current_wan) or 0) for d in details)  # L 截止目前产值合计(万)
        total_visit = sum((d.visit_cnt or 0) for d in details)                            # O 触客数合计
        # 达成率(合计) = 合计截止目前产值 ÷ 合计产值目标
        _ach_total = (total_current / total_target) if total_target else None
        # 触客率(合计) = 合计触客数 ÷ 合计新车交付数
        _visit_rate_total = (total_visit / total_delivery) if total_delivery else None
        total_deliv_check_out = sum((d.delivery_check_output_cnt or 0) for d in details)  # AA 交车数核对-产值表 合计
        total_deliv_check_grp = sum((d.delivery_check_group_cnt or 0) for d in details)   # AB 交车数核对-一店一群 合计
        total_visit_check_out = sum((d.visit_check_output_cnt or 0) for d in details)     # AD 触客数核对-产值表 合计
        total_visit_check_grp = sum((d.visit_check_group_cnt or 0) for d in details)      # AE 触客数核对-一店一群 合计
        # 差异列合计 = 逐店差异之和(任一列为空 → 该店差异留空、不计入合计)
        total_deliv_diff = sum((_diff(d.delivery_check_output_cnt, d.delivery_check_group_cnt) or 0)
                               for d in details)   # AC 交车数核对-差异 合计
        total_visit_diff = sum((_diff(d.visit_check_output_cnt, d.visit_check_group_cnt) or 0)
                               for d in details)   # AF 触客数核对-差异 合计
        _set_cell(ws, 4, 11, total_target)                          # K 产值目标(万)合计
        _set_cell(ws, 4, 12, total_current)                         # L 截止目前产值(万)合计
        _set_cell(ws, 4, 13, _ach_total)                            # M 达成率 合计(=合计L÷合计K)
        _set_cell(ws, 4, 14, total_delivery)                        # N 新车交付数 合计
        _set_cell(ws, 4, 15, total_visit)                           # O 触客数 合计
        _set_cell(ws, 4, 16, _visit_rate_total)                     # P 触客率 合计(=合计O÷合计N)
        _set_cell(ws, 4, 29, total_deliv_check_out)                 # AC 交车数核对-产值表 合计
        _set_cell(ws, 4, 30, total_deliv_check_grp)                 # AD 交车数核对-一店一群 合计
        _set_cell(ws, 4, 31, total_deliv_diff)                      # AE 交车数核对-差异 合计(逐店差异之和)
        _set_cell(ws, 4, 32, total_visit_check_out)                 # AF 触客数核对-产值表 合计
        _set_cell(ws, 4, 33, total_visit_check_grp)                 # AG 触客数核对-一店一群 合计
        _set_cell(ws, 4, 34, total_visit_diff)                      # AH 触客数核对-差异 合计(逐店差异之和)

        # ---- 周度评灯节点聚合综合渗透(T/U/V/W 列,r4 锚点行,写数值不写灯色)----
        # 各节点综合渗透 = Σ门店该节点累计(延保+权益)订单数 ÷ Σ门店该节点新车交付数
        #   ⚠ 分子与分母必须同口径(同一门店集合),否则会出现 >1 的无意义值:
        #   截止目前(T):门店集合 = 有 store_code 的门店;分母 = 全月新车交付数合计
        #   W1/W2/W3  :门店集合 = 该周结束日「有快照交付数」且有 store_code 的门店;
        #               分母 = 该集合的快照 delivery_cnt 合计(无快照门店不参与分子分母)
        for j, (_lbl, _end) in enumerate(week_nodes):
            wb_node = window_biz_by_node[j] if j < len(window_biz_by_node) else {}
            if j == 0:
                _univ = [d for d in details if d.store_code]
                node_delivery_total = total_delivery
            else:
                _snap = week_delivery_by_node[j] if j < len(week_delivery_by_node) else {}
                _univ = [d for d in details
                         if d.store_code and _snap.get(d.store_name) is not None]
                node_delivery_total = sum((_snap.get(d.store_name) or 0) for d in _univ)
            ec_total = sum((wb_node.get(str(d.store_code), {}).get(BAIC_BIZ_EXT_WARRANTY) or 0)
                           for d in _univ)
            rc_total = sum((wb_node.get(str(d.store_code), {}).get(BAIC_BIZ_RIGHTS) or 0)
                           for d in _univ)
            comb_total = ec_total + rc_total
            _set_cell(ws, 4, BAIC_LIGHT_COLS[j], _penetration(comb_total, node_delivery_total))

        # ---- 回写落库:把本次渲染算出的 W1~W5 周度字段持久化 ----
        # 说明:_fill_block 已把 w{n}_order_cnt / w{n}_new_delivery_cnt /
        #       w{n}_comprehensive_penetration / w{n}_light_level 设到各 details 对象上,
        #       此处统一提交;失败仅告警,不影响 Excel 生成与 OSS 上传。
        try:
            db.session.commit()
            logger.info(f"[北汽] 周度字段(W1~W5)已回写 baic_special_month_data:{len(details)} 行"
                        f"(task {task_id})")
        except Exception as we:
            db.session.rollback()
            logger.warning(f"[北汽] 周度字段回写失败(task {task_id},不影响结果表): {we}")

        # ---- 品牌汇总 本月/上月段:插入门店行后位置下移,动态定位 ----
        cur_month_row = cur_prev_row = None
        for r in range(1, ws.max_row + 1):
            v = ws.cell(r, 1).value
            if v and '本月' in str(v):
                cur_month_row = r
            elif v and '上月' in str(v):
                cur_prev_row = r
        if cur_month_row is not None:
            lbl = ws.cell(cur_month_row, 1).value
            if lbl and '本月' in str(lbl):
                ws.cell(cur_month_row, 1).value = re.sub(
                    r'本月\s*\S*', f'本月 {month_label}', str(lbl))
            data_row = cur_month_row + 2
            _set_cell(ws, data_row, 1, '北汽')   # 项目
            _set_cell(ws, data_row, 2, '极狐/越野')   # 品牌(北汽极狐 + 北京越野 固定汇总显示)
            _set_cell(ws, data_row, 3, n)        # 门店数
            # 品牌汇总本月段:与合计行同口径聚合(D~N 系统/计算列均填,O~R 环比框架轮留空)
            _set_cell(ws, data_row, 4, total_current)                                  # D 产值(万)= 截止目前产值合计
            _set_cell(ws, data_row, 5, total_delivery)                                # E 交付数 = 新车交付数合计
            _set_cell(ws, data_row, 6, total_visit)                                   # F 售前触客数 = 触客数合计
            _set_cell(ws, data_row, 7, _visit_rate_total)                             # G 售前触客率 = 合计触客率
            # H 售后门店数 / I 售后场景开通率(源文件末尾汇总段,经汇总表落库后回填)
            if summary:
                _set_cell(ws, data_row, 8, summary.after_sale_store_cnt)
                _set_cell(ws, data_row, 9, _dec_to_float(summary.after_sale_scene_open_rate))
            _set_cell(ws, data_row, 10, _after_sale_total)                            # J 售后订单数 = 新口径合并总数(主订单+客户单 sales_type=1)
            _set_cell(ws, data_row, 11, ext_total)                                    # K 整车延保成交数 = 延保订单合计
            _set_cell(ws, data_row, 12, _penetration(ext_total, total_delivery))     # L 整车延保渗透率
            _set_cell(ws, data_row, 13, rights_total)                                 # M 原厂权益成交数 = 权益订单合计
            _set_cell(ws, data_row, 14, _penetration(rights_total, total_delivery))  # N 原厂权益渗透率
            # O(15)~R(18) 环比(本月 - 上月)在下方「上月真实数据」计算完成后回填(见 _fill_mom 段)
        # ---- 上月真实数据:用于填充「上月」汇总段,使其与上月结果表的「本月」汇总对齐 ----
        # 旧逻辑「上月段数据行保留模板原样」会让 9 月导出的「8月汇总」显示模板示例占位值,
        # 与 8 月结果表真实汇总对不上。现改为:取上一月真实任务(DataProcessTask,baic_special,
        # month=上月)的明细/业务/汇总,按与「本月」段完全相同的口径聚合后回填。
        # 无上月任务数据 → 仅更新月份标签,保留模板原样(避免用占位值误导)。
        prev_month = None
        if len(month) >= 7 and month[4] == '-':
            try:
                _y, _m = int(month[:4]), int(month[5:7])
                _pm = _m - 1 if _m > 1 else 12
                _py = _y if _pm != 12 else _y - 1
                prev_month = f"{_py:04d}-{_pm:02d}"
            except (ValueError, IndexError):
                prev_month = None
        _prev_details = []
        _prev_ext = _prev_rights = 0
        _prev_delivery = _prev_visit = _prev_current = 0
        _prev_visit_rate = None
        _prev_after_sale_total = 0
        _prev_store_cnt = 0
        _prev_summary = None
        if prev_month:
            _prev_task = DataProcessTask.query.filter_by(
                data_table_type='baic_special', month=prev_month).first()
            if _prev_task:
                _prev_details = (BaicSpecialMonthData.query
                                 .filter_by(task_id=_prev_task.id, is_deleted=0)
                                 .order_by(BaicSpecialMonthData.store_id).all())
                if _prev_details:
                    _p_ids = [d.store_id for d in _prev_details]
                    _p_biz = (BaicSpecialMonthlyBusiness.query
                              .filter(BaicSpecialMonthlyBusiness.store_id.in_(_p_ids)).all())
                    _p_biz_map = {}
                    for _br in _p_biz:
                        _p_biz_map.setdefault(_br.store_id, {})[_br.business_type] = _br.order_cnt
                    _prev_ext = sum((_p_biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY) or 0)
                                    for d in _prev_details)
                    _prev_rights = sum((_p_biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS) or 0)
                                       for d in _prev_details)
                    _prev_delivery = sum((d.new_delivery_cnt or 0) for d in _prev_details)
                    _prev_visit = sum((d.visit_cnt or 0) for d in _prev_details)
                    _prev_current = sum((_dec_to_float(d.output_current_wan) or 0) for d in _prev_details)
                    _prev_visit_rate = (_prev_visit / _prev_delivery) if _prev_delivery else None
                    # 上月段售后订单数(J):同样改用新口径(主订单+客户单 sales_type=1,合并总数)
                    _prev_store_codes = [d.store_code for d in _prev_details if d.store_code]
                    _prev_after_sale_total = 0
                    if _prev_store_codes:
                        _pme = _month_last_day(date(_py, _pm, 1))
                        _paso = fetch_after_sale_order_count(date(_py, _pm, 1), _pme, _prev_store_codes)
                        _prev_after_sale_total = sum(_paso.values())
                    _prev_store_cnt = len(_prev_details)
                    _prev_summary = (BaicSpecialMonthSummaryMetrics.query
                                     .filter_by(task_id=_prev_task.id, is_deleted=0)
                                     .order_by(BaicSpecialMonthSummaryMetrics.id.desc()).first())

        # ---- 品牌汇总·本月段 环比(O~R) = 本月 - 上月 ----
        # 与模板示例口径一致(已用模板 7月/6月样例校验:售前触客率0.8667-0.8562=0.0105 等)。
        # 仅当存在上月真实任务数据时才填;否则清空,避免残留模板示例值误导。
        if cur_month_row is not None:
            if _prev_details:
                _cur_open_rate = _dec_to_float(summary.after_sale_scene_open_rate) if summary else None
                _prev_open_rate = _dec_to_float(_prev_summary.after_sale_scene_open_rate) if _prev_summary else None
                _set_cell(ws, data_row, 15, _diff(_cur_open_rate, _prev_open_rate))        # O 售后场景开通率环比
                _set_cell(ws, data_row, 16, _diff(_visit_rate_total, _prev_visit_rate))    # P 售前触客率环比
                _set_cell(ws, data_row, 17, _diff(                                         # Q 整车延保渗透率环比
                    _penetration(ext_total, total_delivery),
                    _penetration(_prev_ext, _prev_delivery)))
                _set_cell(ws, data_row, 18, _diff(                                         # R 原厂权益渗透率环比
                    _penetration(rights_total, total_delivery),
                    _penetration(_prev_rights, _prev_delivery)))
            else:
                # 无上月真实任务数据 → 清空,避免残留模板示例值
                for c in range(15, 19):
                    _set_cell(ws, data_row, c, None)

        if cur_prev_row is not None:
            lbl = ws.cell(cur_prev_row, 1).value
            if lbl and '上月' in str(lbl):
                ws.cell(cur_prev_row, 1).value = re.sub(
                    r'上月\s*\S*', f'上月 {prev_month_label}', str(lbl))
            _p_row = cur_prev_row + 2
            # 上月段:整列去掉 4 个环比列(表头+数据),本月段不变(用户 2026-11-04)
            _p_hdr = cur_prev_row + 1
            for _c in range(15, 19):
                _set_cell(ws, _p_hdr, _c, None)
            if _prev_details:
                # 上月段数据行:用上月真实任务数据回填(与上月结果表「本月」汇总同口径)
                _set_cell(ws, _p_row, 1, '北汽')                                       # 项目
                _set_cell(ws, _p_row, 2, '极狐/越野')                                       # 品牌(极狐/越野 固定汇总显示)
                _set_cell(ws, _p_row, 3, _prev_store_cnt)                              # 门店数
                _set_cell(ws, _p_row, 4, _prev_current)                                # D 产值(万)
                _set_cell(ws, _p_row, 5, _prev_delivery)                               # E 交付数
                _set_cell(ws, _p_row, 6, _prev_visit)                                  # F 售前触客数
                _set_cell(ws, _p_row, 7, _prev_visit_rate)                             # G 售前触客率
                if _prev_summary:
                    _set_cell(ws, _p_row, 8, _prev_summary.after_sale_store_cnt)
                    _set_cell(ws, _p_row, 9, _dec_to_float(_prev_summary.after_sale_scene_open_rate))
                _set_cell(ws, _p_row, 10, _prev_after_sale_total)                     # J 售后订单数(新口径合并总数)
                _set_cell(ws, _p_row, 11, _prev_ext)                                   # K 整车延保成交数
                _set_cell(ws, _p_row, 12, _penetration(_prev_ext, _prev_delivery))     # L 整车延保渗透率
                _set_cell(ws, _p_row, 13, _prev_rights)                                # M 原厂权益成交数
                _set_cell(ws, _p_row, 14, _penetration(_prev_rights, _prev_delivery)) # N 原厂权益渗透率
                for _c in range(15, 19):                                               # O~R 环比:清空
                    _set_cell(ws, _p_row, _c, None)
            else:
                # 无上月真实任务数据 → 清除模板占位数据,整行(A~R)置空,避免示例值误导
                for _c in range(1, 19):
                    _set_cell(ws, _p_row, _c, None)

        # ---- 同步回填 baic_special_month_summary_metrics(与「品牌汇总·本月」段同口径)----
        # 历史问题:该表仅写 project_name/brand/store_cnt/售后门店数/售后场景开通率/售后订单数,
        # 产值/交付/触客/渗透/环比 等列一直留空(未落库)。现用品牌汇总段已算出的聚合值回填,
        # 使 DB 汇总表与结果表「品牌汇总·本月」段完全一致(generate_result_excel 是唯一能拿到
        # 全量聚合值 + 上月对比值的入口,故在此统一回写,避免与 _save 重复取数)。
        _sm_update = {
            BaicSpecialMonthSummaryMetrics.output_wan: total_current,
            BaicSpecialMonthSummaryMetrics.delivery_cnt: total_delivery,
            BaicSpecialMonthSummaryMetrics.pre_sale_visit_cnt: total_visit,
            BaicSpecialMonthSummaryMetrics.pre_sale_visit_rate: _visit_rate_total,
            BaicSpecialMonthSummaryMetrics.after_sale_order_cnt: _after_sale_total,
            BaicSpecialMonthSummaryMetrics.vehicle_ext_warranty_deal_cnt: ext_total,
            BaicSpecialMonthSummaryMetrics.vehicle_ext_warranty_penetration_rate:
                _penetration(ext_total, total_delivery),
            BaicSpecialMonthSummaryMetrics.original_rights_deal_cnt: rights_total,
            BaicSpecialMonthSummaryMetrics.original_rights_penetration_rate:
                _penetration(rights_total, total_delivery),
        }
        if _prev_details:
            _cur_open_rate = _dec_to_float(summary.after_sale_scene_open_rate) if summary else None
            _prev_open_rate = (_dec_to_float(_prev_summary.after_sale_scene_open_rate)
                               if _prev_summary else None)
            _sm_update[BaicSpecialMonthSummaryMetrics.after_sale_scene_open_rate_mom_pp] = \
                _diff(_cur_open_rate, _prev_open_rate)
            _sm_update[BaicSpecialMonthSummaryMetrics.pre_sale_visit_rate_mom_pp] = \
                _diff(_visit_rate_total, _prev_visit_rate)
            _sm_update[BaicSpecialMonthSummaryMetrics.vehicle_ext_warranty_penetration_rate_mom_pp] = \
                _diff(_penetration(ext_total, total_delivery),
                      _penetration(_prev_ext, _prev_delivery))
            _sm_update[BaicSpecialMonthSummaryMetrics.original_rights_penetration_rate_mom_pp] = \
                _diff(_penetration(rights_total, total_delivery),
                      _penetration(_prev_rights, _prev_delivery))
        else:
            # 无上月真实任务 → 环比列清空(与结果表 O~R 一致)
            _sm_update[BaicSpecialMonthSummaryMetrics.after_sale_scene_open_rate_mom_pp] = None
            _sm_update[BaicSpecialMonthSummaryMetrics.pre_sale_visit_rate_mom_pp] = None
            _sm_update[BaicSpecialMonthSummaryMetrics.vehicle_ext_warranty_penetration_rate_mom_pp] = None
            _sm_update[BaicSpecialMonthSummaryMetrics.original_rights_penetration_rate_mom_pp] = None
        _sm_n = BaicSpecialMonthSummaryMetrics.query.filter_by(
            task_id=task.id, is_deleted=0).update(_sm_update, synchronize_session=False)
        db.session.commit()
        logger.info(f"[北汽] 汇总指标表回填 {_sm_n} 行(task {task.id}):"
                    f"产值={total_current} 交付={total_delivery} 触客={total_visit} "
                    f"延保成交={ext_total} 权益成交={rights_total}")

        # ---- sheet 重命名(月份占位替换)----
        try:
            ws.title = f"{month_label}页签-字段取值说明"
        except Exception:
            pass

        # ---- 保存 + 上传 OSS ----
        tmp = tempfile.mktemp(suffix='.xlsx')
        wb.save(tmp)
        # 本地预览副本:与用户正在预览的文件对齐(带 _task)。
        # 放在 OSS 上传之前,确保即便上传失败本地预览仍能更新。
        _local_out = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'outputs', f'baic_special_{month}_task{task_id}.xlsx')
        os.makedirs(os.path.dirname(_local_out), exist_ok=True)
        wb.save(_local_out)
        logger.info(f"[北汽] 结果表本地副本已保存:{_local_out}")
        # OSS 上传(失败不影响本地预览)
        url = ''
        try:
            # 每次重新生成都带唯一时间戳(到微秒),避免同一 task_id 复用同一 OSS key
            # 导致覆盖后下游/CDN 仍返回首次上传的文件。
            _now = datetime.now()
            _ts = _now.strftime('%Y%m%d%H%M%S%f')
            object_key = f"data-process/{_now.strftime('%Y%m%d')}/北汽专项_{month}_{task_id}_{_ts}.xlsx"
            url = upload_file(tmp, object_key)
            logger.info(f"[北汽] 结果表已上传 OSS:task {task_id} -> {url}")
        except Exception as ue:
            logger.warning(f"[北汽] OSS 上传失败(本地副本已保留,不影响预览): {ue}")
        try:
            os.remove(tmp)
        except Exception:
            pass
        return url