processor.py 316 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 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209
# -*- coding: utf-8 -*-
"""
数据处理引擎
============================
功能:处理数据处理任务,解析上传的 Excel 文件,执行成本计算,生成汇总结果。

处理流程:
  1. 扫描待处理任务(status='PROCESSING')
  2. 下载关联文件到本地临时目录
  3. 按表单类型分发解析逻辑
  4. 执行成本计算(市场费、外援施工费、人力成本、房租水电施工费)
  5. 将结果写入 biz_budget_achieve 表
  6. 生成汇总 Excel 并上传到 OSS
  7. 更新任务状态

作者:数据处理引擎
"""

import os
import logging
import math
import re
import shutil
import tempfile
import uuid
from decimal import Decimal, ROUND_HALF_UP
from collections import defaultdict
from datetime import datetime
import time

import pandas as pd
import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from sqlalchemy import text

from models import DataProcessTask, DataProcessFile, BizBudgetAchieve, BizUnmatchedFee, db
from oss_utils import download_file, upload_file
from config import Config
from parsers.consumables_parser import normalize_bt

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger('DataProcessor')


# ============================================================
# 业务类型常量
# ============================================================
BIZ_TYPE_1_1 = "1.1"   # 贴膜等1.1业务
BIZ_TYPE_2_1 = "2.1"   # 2.1业务
BIZ_TYPE_2_3 = "2.3"   # 2.3业务

# 必需的表单类型(仅下载这些文件)
# 2026-10 精简:移除市场费总表/人力成本统计表/外施施工费用表(由 config.forms 控制)
REQUIRED_FORM_TYPES = ['房租水电费用表']

# 需要先行运行「预算达成数据清洗」(clean_budget_achievement) 的数据表类型;
# 该清洗负责建立 biz_budget_achieve 基础行与 GMV,供本脚本成本计算消费。
CLEAN_DATA_TABLE_TYPE = 'budget_achievement'

# 当前处理引擎支持的数据表类型白名单:
# 仅这些类型的 PROCESSING 任务会被调度器自动处理;
# 其余类型(如店效人效及盈利测算、产值达成表等新接入的报表)在单据层创建后
# 保持 PROCESSING 状态,等待对应处理引擎接入后再启用,避免被误判为处理失败。
SUPPORTED_PROCESS_TYPES = {CLEAN_DATA_TABLE_TYPE}

# 市场费 Title 与业务类型的映射关系
TITLE_TO_BIZ = {
    "Title2": BIZ_TYPE_1_1,
    "Title3": BIZ_TYPE_1_1,
    "Title4": BIZ_TYPE_1_1,
    "Title5": BIZ_TYPE_1_1,
    "Title6": BIZ_TYPE_2_1,
    "Title7": BIZ_TYPE_2_1,
    "Title9": BIZ_TYPE_2_3,
    "Title10": BIZ_TYPE_2_3,
}

# 市场费 Sheet 名称模式与业务类型、取费字段的映射
# 根据 Sheet 名称中的关键词匹配业务类型和取费列
# fee_col: 'market_fee' 表示取"市场费"列,'market_fee_total' 表示取"市场费总额"列
SHEET_BIZ_MAP = [
    # 1.1 业务:太阳膜、龙南系列
      {'pattern': '太阳膜-赛力斯', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'},  # 赛力斯用市场费总额
      {'pattern': '太阳膜', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'},  # 其他太阳膜用市场费
      # 2.1 业务:权益、续保 —— 精确规则放前面,避免被模糊规则拦截
      {'pattern': '龙南-权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'},  # 龙南下的权益=2.1+市场费
      {'pattern': '权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'},  # 权益默认取总额,Title行修正
      {'pattern': '续保', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'},
      # 2.3 业务:延保
      {'pattern': '延保', 'biz_type': BIZ_TYPE_2_3, 'fee_col': 'market_fee'},
      # 1.1 业务:龙南系列(排除权益后)
      {'pattern': '^龙南$', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'},
      {'pattern': '龙南-', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'},
]

# 跳过的 Sheet 名称关键词
SHEET_SKIP_PATTERNS = ['6月预算', '汇总', '合计']

# 品牌关键词映射
WENJIE_KEYWORDS = ["问界"]
HARMONY_KEYWORDS = ["享界", "智界", "尊界", "尚界"]
SERES_KEYWORDS = ["赛力斯", "AITO", "SERES"]

# 品牌映射表:Excel识别的品牌 -> 数据库中可能存储的品牌值
# 用于解决品牌名称不一致导致的匹配失败问题
BRAND_MAPPING = {
    "问界": ["问界", "赛力斯", "AITO"],  # 数据库中可能存储的品牌值
    "鸿蒙": ["鸿蒙", "问界"],
    "赛力斯": ["赛力斯", "问界", "AITO"],
}

# 已知密码映射(文件名 → 密码)
KNOWN_PASSWORDS = {
    "人力成本表-密码2026": "2026",
}

# ---------------- 标准名 / 别名映射(merchant_4s 流量方、merchant_yq 园区店) ----------------
_ALIAS_MAPS = {}   # kind('4s'|'yq') -> {alias_name: standard_name}

def strip_if_dplus(name):
    return str(name or '')

def load_alias_maps(force_refresh=False):
    """从 merchant_4s(流量方字典表)与 merchant_yq(园区店字典表)加载 别名→标准名 映射。
    结果缓存到模块级 _ALIAS_MAPS,整个进程只加载一次。
    
    Args:
        force_refresh: 是否强制刷新缓存(默认 False,设为 True 时忽略缓存重新加载)
    
    Returns:
        dict: {'4s': {alias_name: standard_name}, 'yq': {alias_name: standard_name}}
    """
    global _ALIAS_MAPS
    if _ALIAS_MAPS and not force_refresh:
        return _ALIAS_MAPS
    
    from models import db
    maps = {}
    for kind, table in (('4s', 'merchant_4s'), ('yq', 'merchant_yq')):
        m = {}
        try:
            with db.engine.connect() as conn:
                result = conn.execute(text(f'SELECT standard_name, alias_name FROM `{table}`'))
                for r in result.fetchall():
                    sn = (r[0] or '').strip()
                    an = (r[1] or '').strip()
                    if an:
                        m[an] = sn
        except Exception as e:
            logger.warning(f"[别名映射] 加载 {table} 失败: {e}")
        maps[kind] = m
    
    _ALIAS_MAPS = maps
    logger.info(f"[别名映射] {'强制刷新' if force_refresh else '加载完成'}: 4s({len(maps.get('4s', {}))}个), yq({len(maps.get('yq', {}))}个)")
    return _ALIAS_MAPS

def to_standard(raw, kind):
    """将流量方名称(kind='4s')或园区店名称(kind='yq')归一为字典表中的标准名。"""
    if raw is None:
        return raw
    raw = str(raw).strip()
    if not raw:
        return raw
    m = _ALIAS_MAPS.get(kind, {})
    if raw in m:
        return m[raw]
    s = strip_if_dplus(raw)
    if s and s != raw and s in m:
        return m[s]
    return raw


def decrypt_excel_if_needed(file_path):
    """
    检查 Excel 文件是否有密码保护,如有则解密到临时文件。
    返回:(file_path, is_decrypted) 元组
      - file_path: 可读取的文件路径(可能是解密后的临时文件)
      - is_decrypted: 是否进行了解密操作(调用方负责清理临时文件)
    """
    basename = os.path.basename(file_path)
    name_without_ext = os.path.splitext(basename)[0]

    # 检查是否有已知密码
    password = None
    for key, pwd in KNOWN_PASSWORDS.items():
        if key in name_without_ext:
            password = pwd
            break

    if not password:
        # 尝试直接读取,如果能读取则返回原路径
        try:
            pd.ExcelFile(file_path)
            return file_path, False
        except Exception:
            # 可能有密码,尝试用默认密码
            logger.warning(f"[解密] 文件可能有密码保护: {file_path}")
            return file_path, False

    # 使用密码解密
    try:
        import io
        import msoffcrypto

        with open(file_path, 'rb') as f:
            office_file = msoffcrypto.OfficeFile(f)
            if office_file.is_encrypted():
                office_file.load_key(password=password)
                
                # 写入临时文件(新版 API: decrypt(outfile=文件对象))
                tmp_fd, tmp_path = tempfile.mkstemp(suffix='.xlsx', prefix='decrypted_')
                with os.fdopen(tmp_fd, 'wb') as tmp_f:
                    office_file.decrypt(outfile=tmp_f)

                logger.info(f"[解密] 成功解密文件,密码: {password}")
                return tmp_path, True
    except ImportError:
        logger.warning("[解密] msoffcrypto 未安装,尝试使用 pandas 直接读取")
    except Exception as e:
        logger.error(f"[解密] 解密失败: {e}")

    # 回退:尝试用 openpyxl 的 password 参数
    try:
        wb = openpyxl.load_workbook(file_path, read_only=True, data_only=True)
        wb.close()
        return file_path, False
    except Exception:
        pass

    return file_path, False


# ============================================================
# 通用工具函数
# ============================================================

def safe_decimal(value):
    """
    将任意值安全转换为 Decimal 类型。
    规则:
      - None / NaN / 空字符串 → Decimal("0")
      - 数字字符串 → 解析为 Decimal(支持千分位逗号)
      - float/int/numpy类型 → 通过字符串中转,避免浮点精度丢失
      - 其他 → 尝试转换,失败则返回 0
    """
    if value is None:
        return Decimal("0")
    
    # 处理 numpy 类型
    try:
        import numpy as np
        if isinstance(value, (np.floating,)):
            fval = float(value)
            if math.isnan(fval) or math.isinf(fval):
                return Decimal("0")
            return Decimal(repr(fval))
        if isinstance(value, (np.integer,)):
            return Decimal(int(value))
        if isinstance(value, np.ndarray):
            return Decimal("0")
    except ImportError:
        pass
    
    # 处理 NaN/Inf
    if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
        return Decimal("0")
    
    if isinstance(value, Decimal):
        return value
    if isinstance(value, int):
        return Decimal(value)
    if isinstance(value, float):
        return Decimal(repr(value))
    s = str(value).strip()
    if s == "" or s == "-":
        return Decimal("0")
    s = s.replace(",", "")
    s = s.replace("%", "")
    multiplier = Decimal("1")
    if s.endswith("万"):
        multiplier = Decimal("10000")
        s = s[:-1]
    elif s.endswith("亿"):
        multiplier = Decimal("100000000")
        s = s[:-1]
    try:
        d = Decimal(s)
        return d * multiplier
    except Exception:
        return Decimal("0")


def round_2(value):
    """
    将 Decimal 值四舍五入保留2位小数。
    """
    if not isinstance(value, Decimal):
        value = safe_decimal(value)
    return value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)


def pct(numerator, denominator):
    """
    计算百分比(分子/分母*100),四舍五入保留2位小数。
    分母为0时返回 0.00。
    返回值上限 999.99(对应数据库 decimal(5,2) 字段)。
    """
    if denominator is None or denominator == 0:
        return Decimal("0.00")
    num = safe_decimal(numerator)
    den = safe_decimal(denominator)
    if den == 0:
        return Decimal("0.00")
    result = round_2(num / den * Decimal("100"))
    # 限制上限为 999.99,防止超出 decimal(5,2) 范围
    if result > Decimal("999.99"):
        result = Decimal("999.99")
    # 限制下限为 0
    if result < Decimal("0"):
        result = Decimal("0.00")
    return result


def parse_allocation_targets(target_str, flow_names_set, park_to_flows):
    if not target_str or not str(target_str).strip():
        return []

    separators = [',', ',', '、', ';', ';', '\n', '\r']

    normalized = str(target_str).strip()
    for sep in separators[1:]:
        normalized = normalized.replace(sep, separators[0])

    parts = [p.strip() for p in normalized.split(separators[0]) if p.strip()]

    targets = []
    for part in parts:
        std_part = to_standard(part, '4s')

        if std_part in flow_names_set or part in flow_names_set:
            targets.append({
                'name': part,
                'type': 'flow',
                'std_name': std_part
            })
        elif part in park_to_flows or to_standard(part, 'yq') in park_to_flows:
            targets.append({
                'name': part,
                'type': 'park',
                'std_name': to_standard(part, 'yq')
            })
        else:
            targets.append({
                'name': part,
                'type': 'flow',
                'std_name': std_part
            })

    return targets


def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names=None, only_dijia=True):
    """查询指定流量方 / 园区店的 GMV 汇总。
    Args:
        db: SQLAlchemy db 对象(需有 session 属性)
        task_id: 数据处理任务 ID
        business_type: 业务类型(如 "1.1" / "2.1" / "2.3")
        flow_names: 流量方标准名列表(可选)
        park_names: 园区店标准名列表(可选)
        only_dijia: True=只累计服务商含"嘀加"的行(默认 True,GMV 分摊口径)
    Returns:
        dict: {name(str): gmv(float)},键为流量方或园区店名称
    """
    from sqlalchemy import text, bindparam

    result = {}
    sp_clause = "AND service_provider LIKE '%嘀加%'" if only_dijia else ""

    if flow_names:
        sql = text(f"""
            SELECT traffic_name, SUM(gmv) as total_gmv
            FROM biz_budget_achieve
            WHERE traffic_name IN :names
            AND task_id = :task_id
            AND business_type = :biz_type
            {sp_clause}
            GROUP BY traffic_name
        """).bindparams(bindparam("names", expanding=True))

        params = {"names": flow_names, "task_id": task_id, "biz_type": business_type}

        try:
            rows = db.session.execute(sql, params).fetchall()
            for row in rows:
                result[row[0]] = float(row[1]) if row[1] else 0
        except Exception as e:
            logger.error(f"[GMV查询] 流量方GMV查询失败: {e}")

    if park_names:
        sql = text(f"""
            SELECT park_store, SUM(gmv) as total_gmv
            FROM biz_budget_achieve
            WHERE park_store IN :names
            AND task_id = :task_id
            AND business_type = :biz_type
            {sp_clause}
            GROUP BY park_store
        """).bindparams(bindparam("names", expanding=True))

        params = {"names": park_names, "task_id": task_id, "biz_type": business_type}

        try:
            rows = db.session.execute(sql, params).fetchall()
            for row in rows:
                result[row[0]] = float(row[1]) if row[1] else 0
        except Exception as e:
            logger.error(f"[GMV查询] 园区店GMV查询失败: {e}")

    for name in (flow_names or []):
        if name not in result:
            result[name] = 0
    for name in (park_names or []):
        if name not in result:
            result[name] = 0

    logger.info(f"[GMV查询] only_dijia={only_dijia}, biz={business_type}, "
                f"flows={len(flow_names or [])}, parks={len(park_names or [])}, result={len(result)} keys")
    return result


def allocate_by_gmv_ratio(total_fee, targets, gmv_data, only_dijia=True):
    """按 GMV 占比分摊费用。

    Args:
        total_fee: 总金额(Decimal)
        targets: 分摊对象列表 [{'name': str, 'type': 'flow'|'park', ...}, ...]
        gmv_data: {name(str): gmv(float)},来自 query_gmv_by_targets 的结果
        only_dijia: True=gmv_data 已过滤非嘀加;若 total_gmv=0 则直接返回 [](费用=0)
                    False=gmv_data 可能含非嘀加;total_gmv=0 时回退平均分配(原行为)

    Returns:
        list[dict]: [{'name': str, 'type': 'flow'|'park', 'share': Decimal, 'ratio': float}, ...]
    """
    if not targets or total_fee == 0:
        return []

    if len(targets) == 1:
        logger.info(f"[GMV分摊计算] 单对象: name={targets[0]['name']}, type={targets[0]['type']}, share={total_fee}, ratio=1.0")
        return [{
            'name': targets[0]['name'],
            'type': targets[0]['type'],
            'share': total_fee,
            'ratio': 1.0
        }]

    total_gmv = 0
    gmv_details = []
    for t in targets:
        gmv = gmv_data.get(t['name'], gmv_data.get(t.get('std_name', ''), 0))
        total_gmv += gmv
        gmv_details.append(f"{t['name']}={gmv}")

    logger.info(f"[GMV分摊计算] total_fee={total_fee}, targets={len(targets)}, total_gmv={total_gmv}, "
                f"only_dijia={only_dijia}, gmv_details=[{', '.join(gmv_details)}]")

    results = []

    if total_gmv > 0:
        allocated = Decimal("0")
        for i, t in enumerate(targets):
            gmv = gmv_data.get(t['name'], gmv_data.get(t.get('std_name', ''), 0))
            ratio = gmv / total_gmv if total_gmv > 0 else 0

            if i == len(targets) - 1:
                share = total_fee - allocated
            else:
                share = round_2(total_fee * Decimal(str(ratio)))

            allocated += share
            results.append({
                'name': t['name'],
                'type': t['type'],
                'share': share,
                'ratio': ratio
            })
            logger.info(f"[GMV分摊计算]   target[{i}]: name={t['name']}, gmv={gmv}, ratio={ratio:.4f}, share={share}")
    else:
        if only_dijia:
            # 服务商过滤后 total_gmv=0 → 不分摊,直接返回 [](费用默认=0)
            logger.info(f"[GMV分摊计算] only_dijia=True 且 total_gmv=0,跳过分摊(费用=0)")
            return []
        # total_gmv=0 且非 only_dijia → 保持原平均分配 fallback
        flow_count = len(targets)
        logger.warning(f"[GMV分摊计算] total_gmv=0, 平均分配给{flow_count}个对象")
        for i, t in enumerate(targets):
            if i == flow_count - 1:
                share = total_fee - sum(r['share'] for r in results)
            else:
                share = round_2(total_fee / flow_count)

            results.append({
                'name': t['name'],
                'type': t['type'],
                'share': share,
                'ratio': 1.0 / flow_count
            })
            logger.info(f"[GMV分摊计算]   target[{i}]: name={t['name']}, share={share}")

    total_share = sum(r['share'] for r in results)
    logger.info(f"[GMV分摊计算] 分摊汇总: total_fee={total_fee}, total_share={total_share}, diff={total_fee - total_share}")

    return results


def update_rent_utilities(db, task_id, business_type, target_name, target_type, allocation_result):
    from sqlalchemy import text

    share = allocation_result.get('share', Decimal('0'))

    if target_type == 'flow':
        query_sql = text("""
            SELECT id, gmv_ratio
            FROM biz_budget_achieve
            WHERE traffic_name = :traffic_name
            AND business_type = :biz_type
            AND task_id = :task_id
            AND gmv_ratio IS NOT NULL
        """)
        params = {"traffic_name": target_name, "biz_type": business_type, "task_id": task_id}
    else:
        query_sql = text("""
            SELECT id, gmv_ratio
            FROM biz_budget_achieve
            WHERE park_store = :park_store
            AND business_type = :biz_type
            AND task_id = :task_id
            AND gmv_ratio IS NOT NULL
        """)
        params = {"park_store": target_name, "biz_type": business_type, "task_id": task_id}

    try:
        rows = db.session.execute(query_sql, params).fetchall()

        updated_count = 0
        for row in rows:
            row_id, gmv_ratio = row
            if gmv_ratio is not None:
                rent_utilities = share * Decimal(str(gmv_ratio))

                update_sql = text("""
                    UPDATE biz_budget_achieve
                    SET rent_utilities = :rent_utilities
                    WHERE id = :row_id
                """)
                db.session.execute(update_sql, {"rent_utilities": rent_utilities, "row_id": row_id})
                updated_count += 1
                logger.info(f"[房租水电更新] id={row_id}, target={target_name}, share={share}, gmv_ratio={gmv_ratio}, rent_utilities={rent_utilities}")

        return updated_count
    except Exception as e:
        logger.error(f"[房租水电更新] 更新失败: {e}")
        return 0


def detect_merged_cells(df, row_idx, rent_col, water_col, construction_col, target_col=None):
    """
    检测指定行是否为合并行(房租、水电、施工费用任意一列是合并单元格)。

    合并行检测逻辑(修复版):
    1. 检查当前行的费用列是否有值
    2. 向下扫描,检查「费用列是否为空」作为合并判断依据
    3. 若后续行「所有费用列都为空」,则是合并行延续
    4. 若后续行「任何费用列有值」,则是独立费用行,停止扫描
    5. 合并行延续的分账对象列通常有值(每个分账对象对应一行)

    Args:
        df: DataFrame
        row_idx: 当前行索引
        rent_col: 房租费用列名
        water_col: 水电费列名
        construction_col: 施工费用列名
        target_col: 分账对象列名(可选)

    Returns:
        dict: {
            'is_merged': bool,  # 是否为合并行
            'merged_cols': list,  # 合并的列名列表
            'merged_row_count': int,  # 合并了多少行
            'independent_row_indices': list  # 独立费用行的索引列表
        }
    """
    # 收集所有费用列
    fee_cols = []
    for col, col_name in [(rent_col, '房租费用'), (water_col, '水电费'), (construction_col, '施工费用')]:
        if col:
            fee_cols.append((col, col_name))
    
    if not fee_cols or row_idx >= len(df) - 1:
        return {
            'is_merged': False,
            'merged_cols': [],
            'merged_row_count': 1,
            'independent_row_indices': []
        }
    
    # 检查当前行是否有费用
    current_has_fee = False
    for col, col_name in fee_cols:
        val = df.iloc[row_idx][col]
        if pd.notna(val) and str(val).strip() not in ('', 'nan', 'None'):
            current_has_fee = True
            break
    
    if not current_has_fee:
        return {
            'is_merged': False,
            'merged_cols': [],
            'merged_row_count': 1,
            'independent_row_indices': []
        }
    
    # 核心逻辑:基于「费用列是否为空」判断合并行
    # 向下扫描,找出合并行范围和独立费用行
    merged_count = 1  # 当前行算1行
    independent_row_indices = []  # 独立费用行索引
    
    # 安全限制:最多扫描 5 行
    max_scan = 5
    scan_limit = min(row_idx + max_scan + 1, len(df))
    
    for check_idx in range(row_idx + 1, scan_limit):
        # 检查该行的费用列是否有值
        row_has_any_fee = any(
            pd.notna(df.iloc[check_idx][col]) and str(df.iloc[check_idx][col]).strip() not in ('', 'nan', 'None')
            for col, _ in fee_cols
        )
        
        if row_has_any_fee:
            # 该行有费用,是独立费用行,停止扫描
            independent_row_indices.append(check_idx)
            break
        else:
            # 该行所有费用列为空,是合并行延续
            merged_count += 1
    
    # 安全限制:最多合并5行
    MAX_MERGED_ROWS = 5
    if merged_count > MAX_MERGED_ROWS:
        merged_count = MAX_MERGED_ROWS
        # 如果独立行索引超出限制,移除超出部分
        independent_row_indices = [idx for idx in independent_row_indices if idx <= row_idx + MAX_MERGED_ROWS]
    
    # 只有检测到合并延续行(merged_count > 1)才认为是合并行
    is_merged = merged_count > 1
    merged_row_count = merged_count if is_merged else 1
    
    # 构建合并列信息(仅当是合并行时)
    merged_cols = []
    if is_merged:
        for col, col_name in fee_cols:
            current_val = df.iloc[row_idx][col]
            if pd.notna(current_val) and str(current_val).strip() not in ('', 'nan', 'None'):
                merged_cols.append({
                    'col': col,
                    'name': col_name,
                    'merged_count': merged_count
                })
    
    # 诊断日志:合并行检测结果
    if is_merged:
        logger.debug(f"[房租水电][合并行检测] 行{row_idx}: is_merged=True, merged_count={merged_count}, "
                     f"independent_indices={independent_row_indices}, "
                     f"fee_cols_with_values={[m['name'] for m in merged_cols]}")
    
    return {
        'is_merged': is_merged,
        'merged_cols': merged_cols,
        'merged_row_count': merged_row_count,
        'independent_row_indices': independent_row_indices
    }


def detect_header_row(df_raw, max_scan=15):
    """
    自动检测 Excel 表头行位置。
    策略:扫描前 max_scan 行,找到非空单元格数量最多的行作为表头。
    同时识别是否存在多行表头(Title行)。
    """
    if df_raw.empty or len(df_raw) == 0:
        return 0, []

    best_row = 0
    best_count = 0
    title_rows = []

    scan_range = min(max_scan, len(df_raw))
    for idx in range(scan_range):
        row = df_raw.iloc[idx]
        non_null = sum(
            1 for v in row
            if pd.notna(v) and str(v).strip() != ""
        )
        if non_null > best_count:
            best_count = non_null
            best_row = idx

    # 识别 Title 行(表头之前的非空行)
    for idx in range(best_row):
        row = df_raw.iloc[idx]
        first_val = row.iloc[0] if len(row) > 0 else None
        if pd.notna(first_val) and str(first_val).strip() != "":
            title_rows.append((idx, str(first_val).strip()))

    return best_row, title_rows


def find_column(df, *keywords):
    """
    在 DataFrame 中查找包含指定关键词的列名(模糊匹配)。
    按优先级排序:完全匹配 > 包含匹配
    """
    cols = list(df.columns)
    # 完全匹配优先
    for kw in keywords:
        for col in cols:
            if str(col).strip() == kw:
                return col
    # 包含匹配
    for kw in keywords:
        for col in cols:
            if kw in str(col):
                return col
    return None


def get_visible_row_indices(file_path, sheet_name, header_row=0):
    """
    使用 zipfile + XML 直接解析 xlsx 文件,检测 Excel Sheet 中的可见行索引(跳过隐藏行)。
    此方法比 openpyxl 快得多,不会加载样式信息。
    
    参数:
      - file_path: Excel 文件路径
      - sheet_name: Sheet 名称
      - header_row: 表头行索引(0-based),需要跳过表头行检测
    
    返回: set of visible row indices (0-based, relative to data rows after header)
    """
    import zipfile
    import xml.etree.ElementTree as ET
    import traceback
    
    try:
        # xlsx 是 ZIP 包,直接解析 XML
        with zipfile.ZipFile(file_path, 'r') as zf:
            # 1. 读取 workbook.xml 获取 sheet 列表
            workbook_xml = zf.read('xl/workbook.xml')
            workbook_root = ET.fromstring(workbook_xml)
            
            # 命名空间
            ns = {'main': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
                  'rel': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'}
            
            # 查找目标 sheet 的 name 和 id
            sheet_id = None
            all_sheets = []
            for sheet in workbook_root.findall('.//main:sheet', ns):
                sheet_name_elem = sheet.get('name')
                sheet_id_elem = sheet.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id')
                all_sheets.append(f"{sheet_name_elem}(id={sheet_id_elem})")
                if sheet_name_elem == sheet_name:
                    sheet_id = sheet_id_elem
            
            if sheet_id is None:
                logger.warning(f"[市场费诊断] Sheet '{sheet_name}' 未在 workbook.xml 中找到。"
                             f" 可用的 Sheets: {all_sheets[:10]}")
                return None
            
            # 2. 读取 _rels/workbook.xml.rels 获取 sheet XML 文件路径
            rels_xml = zf.read('xl/_rels/workbook.xml.rels')
            rels_root = ET.fromstring(rels_xml)
            
            sheet_xml_path = None
            all_rels = []
            for rel in rels_root.findall('.//{http://schemas.openxmlformats.org/package/2006/relationships}Relationship'):
                rel_id = rel.get('Id')
                target = rel.get('Target')
                all_rels.append(f"{rel_id}->{target}")
                if rel_id == sheet_id:
                    sheet_xml_path = target
            
            if sheet_xml_path is None:
                logger.warning(f"[市场费诊断] Sheet '{sheet_name}' 未找到对应的 XML 文件路径。"
                             f" sheet_id={sheet_id}, 所有rels: {all_rels[:5]}")
                return None
            
            # 构建完整路径
            if sheet_xml_path.startswith('/'):
                full_xml_path = sheet_xml_path[1:]  # 去掉前导斜杠
            elif sheet_xml_path.startswith('xl/'):
                full_xml_path = sheet_xml_path
            else:
                full_xml_path = f'xl/{sheet_xml_path}'
            
            logger.info(f"[市场费诊断] Sheet '{sheet_name}': sheet_id={sheet_id}, xml_path={full_xml_path}")
            
            # 3. 读取 sheet XML 文件解析隐藏行
            try:
                sheet_xml = zf.read(full_xml_path)
            except KeyError:
                # 尝试其他路径格式
                alt_path = sheet_xml_path.replace('..', '').lstrip('/')
                logger.warning(f"[市场费诊断] 尝试读取 {full_xml_path} 失败,尝试 {alt_path}")
                sheet_xml = zf.read(alt_path)
            
            sheet_root = ET.fromstring(sheet_xml)
            
            # Excel XML 的默认命名空间
            MAIN_NS = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'
            
            # 获取工作表的完整数据范围(如果有 dimension 元素)
            max_row_num = 0
            dim_elem = sheet_root.find(f'{{{MAIN_NS}}}dimension')
            if dim_elem is not None:
                ref = dim_elem.get('ref', '')
                if ':' in ref:
                    end_ref = ref.split(':')[1]
                    # 从单元格引用提取行号(如 "C100" -> 100)
                    row_num = 0
                    for ch in end_ref:
                        if ch.isdigit():
                            row_num = row_num * 10 + int(ch)
                    max_row_num = row_num
                    logger.info(f"[市场费诊断] Sheet '{sheet_name}': dimension ref={ref}, max_row(from dimension)={max_row_num}")
            
            # 查找所有 <row> 元素,检测 hidden 属性
            hidden_row_numbers = set()
            total_row_elements = 0
            
            for row_elem in sheet_root.findall(f'{{{MAIN_NS}}}row'):
                total_row_elements += 1
                r_attr = row_elem.get('r')  # 行号(1-based)
                if r_attr:
                    row_num = int(r_attr)
                    max_row_num = max(max_row_num, row_num)
                    is_hidden = row_elem.get('hidden')
                    if is_hidden == '1' or is_hidden == 'true':
                        hidden_row_numbers.add(row_num)
            
            logger.info(f"[市场费诊断] Sheet '{sheet_name}': XML中找到 {total_row_elements} 个 <row> 元素, "
                       f"最大行号={max_row_num}, 隐藏行={len(hidden_row_numbers)}")
            
            # 如果没有找到任何行,返回空集合
            if max_row_num == 0:
                logger.info(f"[市场费诊断] Sheet '{sheet_name}': 未找到行数据")
                return set()
            
            # 4. 构建可见行索引(0-based, relative to data rows after header)
            visible_indices = set()
            hidden_count = 0
            
            for row_num in range(header_row + 1, max_row_num + 1):
                if row_num in hidden_row_numbers:
                    hidden_count += 1
                else:
                    visible_indices.add(row_num - header_row - 1)
            
            logger.info(f"[市场费诊断] Sheet '{sheet_name}': 总行数={max_row_num}, header_row={header_row}, "
                       f"隐藏行={hidden_count}, 可见行={len(visible_indices)}")
            
            return visible_indices
            
    except ImportError:
        logger.warning("[市场费诊断] 缺少 zip/xml 模块,跳过隐藏行检测")
        return None
    except Exception as e:
        logger.error(f"[市场费诊断] Sheet '{sheet_name}' 检测隐藏行失败: {e}\n{traceback.format_exc()}")
        return None


def identify_brand(model_text):
    """
    根据车型文本识别品牌。
    规则:
      - 含 "问界" → 问界
      - 含 "享界/智界/尊界/尚界" → 鸿蒙
      - 含 "赛力斯/AITO/SERES" → 赛力斯
      - 无车型信息 → 返回 None(后续按 GMV 分摊)
    """
    if model_text is None or (isinstance(model_text, float) and math.isnan(model_text)):
        return None
    s = str(model_text).strip()
    if s == "":
        return None
    for kw in WENJIE_KEYWORDS:
        if kw in s:
            return "问界"
    for kw in HARMONY_KEYWORDS:
        if kw in s:
            return "鸿蒙"
    for kw in SERES_KEYWORDS:
        if kw in s:
            return "赛力斯"
    return None


def identify_biz_type_by_title(title_text):
    """
    根据 Title 文本识别业务类型。
    规则:
      - Title2/3/4/5 → 1.1
      - Title6/7 → 2.1
      - Title9/10 → 2.3
    """
    if title_text is None:
        return None
    s = str(title_text).strip()
    match = re.match(r"Title\s*(\d+)", s, re.IGNORECASE)
    if match:
        title_num = int(match.group(1))
        title_key = f"Title{title_num}"
        return TITLE_TO_BIZ.get(title_key)
    title_num_map = {"2": "Title2", "3": "Title3", "4": "Title4", "5": "Title5",
                     "6": "Title6", "7": "Title7", "9": "Title9", "10": "Title10"}
    for num, key in title_num_map.items():
        if f"Title{num}" in s or f"title{num}" in s.lower():
            return TITLE_TO_BIZ.get(key)
    return None


# ============================================================
# 表单类型 → 解析函数映射
# ============================================================

class DataProcessor:
    """
    数据处理引擎核心类。
    负责扫描待处理任务、下载文件、解析数据、执行成本计算、生成结果。
    """

    def __init__(self, app=None):
        """
        初始化数据处理器。
        参数:
          - app: Flask app 实例(可选),用于获取 app context
        """
        self.app = app
        self._task_files = {}  # 缓存任务下载的文件路径

    def _fetch_gmv_from_db(self, task_id, stat_month):
        """
        从 biz_budget_achieve 表查询已有的 GMV 和产值数据。
        返回:(settlement_map, park_ratio_map, park_rows_data)
          settlement_map: {(流量方名称, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal, 
               "服务费": Decimal, "嘀加分润": Decimal, "服务商": str, "装修摊销": Decimal, "门店耗材": Decimal,
               "gmv_ratio": float|None, "gmv_ratio_park": float|None, "park_store": str, "park_store_raw": str}}
          park_ratio_map: {(业务类型, 园区店标准名): gmv_ratio_park}
          park_rows_data: [(flow_name, bt, brand, ps_raw, gmv_ratio_park, gmv_ratio, ps_std), ...]
        """
        logger.info(f"[GMV数据] 从数据库获取 task_id={task_id}, stat_month={stat_month} 的 GMV 数据")
        logger.info(f"[GMV数据] 参数类型: task_id={type(task_id).__name__}, stat_month={type(stat_month).__name__}")
        settlement_map = {}
        
        # 诊断:使用 SQL 直接查询验证数据存在性
        try:
            logger.info(f"[GMV数据] 开始诊断查询...")
            diag_sql = text("""
                SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN gmv_ratio IS NOT NULL THEN 1 ELSE 0 END) as has_ratio,
                    SUM(CASE WHEN gmv_ratio_park IS NOT NULL THEN 1 ELSE 0 END) as has_park_ratio,
                    SUM(CASE WHEN park_store IS NOT NULL AND park_store != '' THEN 1 ELSE 0 END) as has_park_store
                FROM biz_budget_achieve 
                WHERE task_id=:tid AND stat_month=:sm
            """)
            diag_result = db.session.execute(diag_sql, {"tid": task_id, "sm": stat_month}).fetchone()
            logger.info(f"[GMV数据] 诊断查询结果: total={diag_result[0]}, has_ratio={diag_result[1]}, has_park_ratio={diag_result[2]}, has_park_store={diag_result[3]}")
            
            if diag_result[0] == 0:
                logger.warning(f"[GMV数据] stat_month={stat_month} 无数据,尝试查找可用的 stat_month")
                month_sql = text("SELECT DISTINCT stat_month FROM biz_budget_achieve WHERE task_id=:tid")
                months = db.session.execute(month_sql, {"tid": task_id}).fetchall()
                logger.info(f"[GMV数据] 可用的 stat_month: {[m[0] for m in months]}")
        except Exception as diag_err:
            logger.error(f"[GMV数据] 诊断查询失败: {diag_err}")
            import traceback
            logger.error(traceback.format_exc())
        
        try:
            # 先检查数据库中是否有该 task_id 的记录(不限制 stat_month)
            try:
                check_sql = text("SELECT COUNT(*), MIN(stat_month), MAX(stat_month) FROM biz_budget_achieve WHERE task_id=:tid")
                check_result = db.session.execute(check_sql, {"tid": task_id}).fetchone()
                logger.info(f"[GMV数据] 预检查: task_id={task_id} 总记录数={check_result[0]}, stat_month范围=[{check_result[1]}, {check_result[2]}]")
            except Exception as check_err:
                logger.error(f"[GMV数据] 预检查失败: {check_err}")
            
            records = db.session.query(BizBudgetAchieve).filter(
                BizBudgetAchieve.task_id == task_id,
                BizBudgetAchieve.stat_month == stat_month
            ).all()
            
            logger.info(f"[GMV数据] 查询到 {len(records)} 条记录")
            
            if not records:
                logger.warning(f"[GMV数据] 数据库中无 task_id={task_id}, stat_month={stat_month} 的记录")
                # 额外诊断:直接查询数据库验证
                try:
                    diag_sql = text("SELECT COUNT(*) FROM biz_budget_achieve WHERE task_id=:tid")
                    diag_result = db.session.execute(diag_sql, {"tid": task_id}).fetchone()
                    logger.info(f"[诊断] task_id={task_id} 在 biz_budget_achieve 中的总记录数: {diag_result[0]}")
                    if diag_result[0] > 0:
                        logger.info(f"[诊断] stat_month 可能不匹配,检查所有 stat_month 值:")
                        month_sql = text("SELECT DISTINCT stat_month FROM biz_budget_achieve WHERE task_id=:tid")
                        months = db.session.execute(month_sql, {"tid": task_id}).fetchall()
                        logger.info(f"[诊断] 所有 stat_month: {[m[0] for m in months]}")
                        
                        # 回退:尝试使用第一个匹配的 stat_month 重新查询
                        if months:
                            actual_stat_month = months[0][0]
                            logger.info(f"[诊断] 回退查询: 使用 stat_month={actual_stat_month} 重新查询")
                            records = db.session.query(BizBudgetAchieve).filter(
                                BizBudgetAchieve.task_id == task_id,
                                BizBudgetAchieve.stat_month == actual_stat_month
                            ).all()
                            logger.info(f"[诊断] 回退查询结果: {len(records)} 条记录")
                            if records:
                                logger.info(f"[诊断] 回退查询成功,继续处理")
                            else:
                                logger.warning(f"[诊断] 回退查询仍然为空")
                                return settlement_map, {}, []
                except Exception as diag_err:
                    logger.error(f"[诊断] 额外查询失败: {diag_err}")
                if not records:
                    return settlement_map, {}, []
            
            for r in records:
                flow_name = (r.traffic_name or "").strip()
                biz_type_raw = (r.business_type or "").strip()
                biz_type = normalize_bt(biz_type_raw) if biz_type_raw else ""
                if biz_type_raw and biz_type_raw != biz_type:
                    logger.info(f"[GMV数据] business_type标准化: '{biz_type_raw}' -> '{biz_type}'")
                brand = (r.brand or "").strip()
                gmv_val = Decimal(str(r.gmv or 0))
                revenue_val = Decimal(str(r.revenue or 0))
                service_fee = Decimal(str(r.service_fee or 0))
                dijia_profit = Decimal(str(r.dijia_profit_sharing or 0))
                service_provider = (r.service_provider or "").strip()
                renovation = Decimal(str(r.renovation_amortization or 0))
                consumables = Decimal(str(r.store_consumables or 0))
                park_store_raw = (r.park_store or "").strip()
                park_store_val = to_standard(park_store_raw, 'yq') if park_store_raw else ""
                
                key = (flow_name, biz_type, brand)
                if key not in settlement_map:
                    settlement_map[key] = {
                        "GMV": Decimal("0"), "产值": Decimal("0"),
                        "服务费": Decimal("0"), "嘀加分润": Decimal("0"),
                        "服务商": "", "装修摊销": Decimal("0"), "门店耗材": Decimal("0"),
                        "gmv_ratio": None, "gmv_ratio_park": None,
                        "park_store": "", "park_store_raw": ""
                    }
                settlement_map[key]["GMV"] += gmv_val
                settlement_map[key]["产值"] += revenue_val
                settlement_map[key]["服务费"] += service_fee
                settlement_map[key]["嘀加分润"] += dijia_profit
                settlement_map[key]["服务商"] = service_provider  # 服务商不累积,直接覆盖
                settlement_map[key]["装修摊销"] += renovation
                settlement_map[key]["门店耗材"] += consumables
                settlement_map[key]["park_store"] = park_store_val  # 园区店标准化值直接覆盖
                settlement_map[key]["park_store_raw"] = park_store_raw  # 园区店原始值直接覆盖
            
            # 直接查询比例数据(不用ORM对象属性名冲突)
            # 修改:添加 park_store 字段,构建独立的 flow_ratio_entries 字典
            flow_ratio_entries = {}  # key: (flow_name, biz_type), value: list of (brand, park_store, gmv_ratio, gmv_ratio_park)
            try:
                ratio_records = db.session.execute(
                    text("SELECT traffic_name, business_type, brand, park_store, gmv_ratio, gmv_ratio_park FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
                    {"tid": task_id, "sm": stat_month}
                ).fetchall()
                logger.info(f"[GMV数据] 比例数据查询: 查询到 {len(ratio_records)} 条记录")
                
                # 诊断日志:检查比例数据样本
                if ratio_records:
                    for rr in ratio_records[:3]:
                        logger.info(f"[GMV数据] 比例数据样本: flow={rr[0]}, bt={rr[1]}, brand={rr[2]}, park_store={rr[3]}, gmv_ratio={rr[4]}, gmv_ratio_park={rr[5]}")
                else:
                    logger.warning(f"[GMV数据] 比例数据查询结果为空: task_id={task_id}, stat_month={stat_month}")
                
                # 诊断日志:检查龙联汽车科技的比例数据
                target_flow = '龙联汽车科技(深圳)有限公司'
                target_ratio_records = [rr for rr in ratio_records if rr[0] and target_flow in str(rr[0])]
                if target_ratio_records:
                    logger.info(f"[GMV数据] 找到 {len(target_ratio_records)} 条'{target_flow}'的比例数据")
                    for tr in target_ratio_records:
                        logger.info(f"[GMV数据]   flow={tr[0]}, bt={tr[1]}, brand={tr[2]}, park_store={tr[3]}, gmv_ratio={tr[4]}, gmv_ratio_park={tr[5]}")
                else:
                    logger.warning(f"[GMV数据] 未找到'{target_flow}'的比例数据")

                # 构建 flow_ratio_entries 字典,保留所有 park_store 的比例值
                # 这是关键修复:避免同一 (flow, biz_type, brand) 下不同 park_store 的比例被覆盖
                for rr in ratio_records:
                    flow_n = (rr[0] or "").strip()
                    bt_raw = (rr[1] or "").strip()
                    bt = normalize_bt(bt_raw) if bt_raw else ""
                    br = (rr[2] or "").strip()
                    ps_raw = (rr[3] or "").strip()
                    gmv_ratio_val = float(rr[4]) if rr[4] is not None else None
                    gmv_ratio_park_val = float(rr[5]) if rr[5] is not None else None
                    
                    if flow_n and bt:
                        key = (flow_n, bt)
                        if key not in flow_ratio_entries:
                            flow_ratio_entries[key] = []
                        flow_ratio_entries[key].append((br, ps_raw, gmv_ratio_val, gmv_ratio_park_val))
                    
                    # 诊断日志:检查龙联汽车科技
                    if flow_n == target_flow:
                        logger.info(f"[GMV数据] flow_ratio_entries: flow={flow_n}, bt={bt}, brand={br}, park_store={ps_raw}, gmv_ratio={gmv_ratio_val}")
                    
                    # 同时更新 settlement_map(保持向后兼容,其他方法可能依赖)
                    map_key = (flow_n, bt, br)
                    if map_key in settlement_map:
                        if rr[4] is not None:
                            settlement_map[map_key]["gmv_ratio"] = float(rr[4])
                        if rr[5] is not None:
                            settlement_map[map_key]["gmv_ratio_park"] = float(rr[5])
                
                # 诊断日志:检查 flow_ratio_entries 中的数据
                target_key = (target_flow, '1.1')
                if target_key in flow_ratio_entries:
                    logger.info(f"[GMV数据] flow_ratio_entries['{target_key}']: {len(flow_ratio_entries[target_key])} 条记录")
                    for brand, ps, gr, grp in flow_ratio_entries[target_key]:
                        logger.info(f"[GMV数据]   brand={brand}, park_store={ps}, gmv_ratio={gr}, gmv_ratio_park={grp}")
            except Exception as e2:
                logger.warning(f"[GMV数据] 比例数据查询失败: {str(e2)}")
                import traceback
                logger.error(f"[GMV数据] 比例数据查询异常堆栈: {traceback.format_exc()}")

            # 构建 park_ratio_map: (业务类型, 园区店) -> gmv_ratio_park
            park_ratio_map = {}
            try:
                park_ratio_records = db.session.execute(
                    text("SELECT business_type, park_store, gmv_ratio_park FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm AND gmv_ratio_park IS NOT NULL"),
                    {"tid": task_id, "sm": stat_month}
                ).fetchall()
                for pr in park_ratio_records:
                    bt_raw = (pr[0] or "").strip()
                    bt = normalize_bt(bt_raw) if bt_raw else ""
                    ps = to_standard((pr[1] or "").strip(), 'yq')
                    if bt and ps:
                        park_ratio_map[(bt, ps)] = float(pr[2])
            except Exception as e3:
                logger.warning(f"[GMV数据] 园区店比例查询失败: {str(e3)}")

            # 独立查询构建 park_rows 数据源(绕过 settlement_map 的 key 粒度限制)
            park_rows_data = []
            try:
                logger.info(f"[诊断] 开始查询park_rows: task_id={task_id}, stat_month={stat_month}")
                park_rows_records = db.session.execute(
                    text("SELECT traffic_name, business_type, brand, park_store, gmv_ratio_park, gmv_ratio FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
                    {"tid": task_id, "sm": stat_month}
                ).fetchall()
                
                # 诊断日志:原始查询结果
                logger.info(f"[诊断] park_rows 原始查询结果数={len(park_rows_records)}")
                
                if not park_rows_records:
                    logger.warning(f"[诊断] park_rows 查询结果为空!检查 stat_month={stat_month} 是否正确")
                    # 尝试不使用 stat_month 过滤
                    try:
                        fallback_sql = text("SELECT COUNT(*) FROM biz_budget_achieve WHERE task_id=:tid AND park_store IS NOT NULL AND park_store != ''")
                        fallback_count = db.session.execute(fallback_sql, {"tid": task_id}).fetchone()
                        logger.info(f"[诊断] 回退查询: task_id={task_id} 有park_store的记录数(不限定stat_month)={fallback_count[0]}")
                    except Exception as fe:
                        logger.error(f"[诊断] 回退查询失败: {fe}")
                
                # 诊断日志:统计有 park_store 的记录数
                records_with_ps = [r for r in park_rows_records if r[3] is not None and str(r[3]).strip()]
                logger.info(f"[诊断] 有park_store的记录数={len(records_with_ps)}")
                
                if park_rows_records:
                    for r in park_rows_records[:5]:
                        logger.info(f"[诊断] 原始记录: flow={r[0]}, bt_raw={r[1]}, brand={r[2]}, ps_raw={r[3]}, gmv_ratio_park={r[4]}, gmv_ratio={r[5]}, types={[type(x).__name__ for x in r]}")
                
                # 诊断日志:标准化处理
                filtered_count = 0
                skip_no_ratio = 0
                for pr in park_rows_records:
                    flow_n = (pr[0] or "").strip()
                    bt_raw = (pr[1] or "").strip()
                    bt = normalize_bt(bt_raw) if bt_raw else ""
                    brand = (pr[2] or "").strip()
                    ps_raw = (pr[3] or "").strip()
                    ps_std = to_standard(ps_raw, 'yq') if ps_raw else ""
                    
                    # 安全转换 Decimal/float 为 float
                    gmv_ratio_park_val = None
                    gmv_ratio_val = None
                    try:
                        if pr[4] is not None:
                            gmv_ratio_park_val = float(pr[4])
                    except (ValueError, TypeError):
                        gmv_ratio_park_val = None
                    try:
                        if pr[5] is not None:
                            gmv_ratio_val = float(pr[5])
                    except (ValueError, TypeError):
                        gmv_ratio_val = None
                    
                    # 检查标准化是否改变了值
                    if ps_raw and ps_std != ps_raw:
                        logger.info(f"[诊断] park_store标准化差异: 原始='{ps_raw}', 标准化='{ps_std}'")
                    
                    # 诊断日志:被过滤的记录(使用原始值判断)
                    if not flow_n or not bt or not ps_raw:
                        filtered_count += 1
                        if filtered_count <= 5:
                            logger.warning(f"[诊断] 记录被过滤: flow_n='{flow_n}'(空={not flow_n}), bt_raw='{bt_raw}', bt='{bt}'(空={not bt}), ps_raw='{ps_raw}'(空={not ps_raw})")
                        continue
                    
                    # 至少有一个比例不为 None 才加载
                    if gmv_ratio_park_val is None and gmv_ratio_val is None:
                        skip_no_ratio += 1
                        if skip_no_ratio <= 3:
                            logger.debug(f"[诊断] 记录被跳过(无比例): flow={flow_n}, bt={bt}, ps={ps_raw}")
                        continue
                    
                    # 存储原始 park_store 值和标准化值
                    park_rows_data.append((flow_n, bt, brand, ps_raw, gmv_ratio_park_val, gmv_ratio_val, ps_std))
                
                logger.info(f"[GMV数据] park_rows 独立查询: {len(park_rows_data)} 条记录, 字段过滤 {filtered_count} 条, 无比例跳过 {skip_no_ratio} 条")
                if park_rows_data:
                    for i, (flow_n, bt, brand, ps_raw, gmv_ratio_park_val, gmv_ratio_val, ps_std) in enumerate(park_rows_data[:5]):
                        logger.info(f"[GMV数据] park_rows_data[{i}]: flow='{flow_n}', bt='{bt}', brand='{brand}', ps_raw='{ps_raw}', gmv_ratio_park={gmv_ratio_park_val}, gmv_ratio={gmv_ratio_val}, ps_std='{ps_std}'")
                
                # 诊断日志:检查目标园区店是否在 park_rows_data 中
                target_ps = 'D+深圳布吉万国城园区店'
                target_records = [(flow_n, bt, ps_raw, gmv_ratio_park_val, gmv_ratio_val) 
                                  for flow_n, bt, brand, ps_raw, gmv_ratio_park_val, gmv_ratio_val, ps_std in park_rows_data 
                                  if target_ps in str(ps_raw)]
                logger.info(f"[诊断] park_rows_data中包含'{target_ps}'的记录数={len(target_records)}")
                for flow_n, bt, ps_raw, gmv_ratio_park_val, gmv_ratio_val in target_records:
                    logger.info(f"[诊断]   flow='{flow_n}', bt='{bt}', ps='{ps_raw}', gmv_ratio_park={gmv_ratio_park_val}, gmv_ratio={gmv_ratio_val}")
            except Exception as e4:
                logger.error(f"[GMV数据] park_rows 独立查询失败: {str(e4)}")
                import traceback
                logger.error(traceback.format_exc())

            # 诊断查询:检查特定 park_store 的数据(便于调试)
            try:
                diag_records = db.session.execute(
                    text("SELECT traffic_name, business_type, park_store, gmv_ratio, gmv_ratio_park FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm AND park_store LIKE '%万国城%'"),
                    {"tid": task_id, "sm": stat_month}
                ).fetchall()
                if diag_records:
                    logger.info(f"[GMV数据] 诊断: 含'万国城'的记录数={len(diag_records)}")
                    for r in diag_records[:5]:
                        logger.info(f"[GMV数据] 诊断: flow={r[0]}, bt={r[1]}, ps={r[2]}, gmv_ratio={r[3]}, gmv_ratio_park={r[4]}")
            except Exception as e5:
                logger.warning(f"[GMV数据] 诊断查询失败: {str(e5)}")

            # 记录 settlement_map 中 biz_type 的唯一值
            biz_types_in_map = set(bt for (_, bt, _) in settlement_map.keys())
            logger.info(f"[GMV数据] settlement_map 中业务类型: {biz_types_in_map}")
            park_store_count = len([v for v in settlement_map.values() if v.get('park_store')])
            logger.info(f"[GMV数据] 获取到 {len(settlement_map)} 条 GMV 记录,已装配 {park_store_count} 条 park_store")
            logger.info(f"[GMV数据] 比例数据: {len([v for v in settlement_map.values() if v.get('gmv_ratio') is not None])} 条有gmv_ratio, {len(park_ratio_map)} 条park_ratio_map")
            
            # 诊断日志:检查龙联汽车科技的所有品牌和比例数据
            target_flow = '龙联汽车科技(深圳)有限公司'
            logger.info(f"[GMV数据] ========== 诊断'{target_flow}'的 settlement_map 数据 ==========")
            target_keys = [(k, v) for k, v in settlement_map.items() if target_flow in str(k[0])]
            logger.info(f"[GMV数据] 找到 {len(target_keys)} 条记录")
            for key, value in target_keys:
                logger.info(f"[GMV数据]   key={key}")
                logger.info(f"[GMV数据]     gmv_ratio={value.get('gmv_ratio')}, gmv_ratio_park={value.get('gmv_ratio_park')}")
                logger.info(f"[GMV数据]     GMV={value.get('GMV')}, 产值={value.get('产值')}")
                logger.info(f"[GMV数据]     park_store={value.get('park_store')}, park_store_raw={value.get('park_store_raw')}")
        except Exception as e:
            logger.error(f"[GMV数据] 查询失败: {str(e)}")
        
        return settlement_map, park_ratio_map, park_rows_data, flow_ratio_entries

    def _fetch_previous_month_data(self, task_id, stat_month):
        """
        从上月 biz_budget_achieve 表查询历史数据,用于计算上月占比。
        返回:prev_month_data 字典 {(流量方名称, 业务类型, 品牌): {market_fee_ratio, personnel_salary_ratio, gmv}}
        """
        from datetime import datetime, timedelta
        try:
            year, month = stat_month.split("-")
            year = int(year)
            month = int(month)
            if month == 1:
                prev_year = year - 1
                prev_month = 12
            else:
                prev_year = year
                prev_month = month - 1
            prev_month_str = f"{prev_year}-{prev_month:02d}"
        except Exception:
            logger.warning(f"[上月数据] 无法解析月份: {stat_month}")
            return {}

        logger.info(f"[上月数据] 查询 {prev_month_str} 的历史数据 (task_id={task_id})")
        prev_month_data = {}
        try:
            records = db.session.query(BizBudgetAchieve).filter(
                BizBudgetAchieve.stat_month == prev_month_str
            ).all()

            if not records:
                logger.warning(f"[上月数据] {prev_month_str} 无历史数据")
                return prev_month_data

            for r in records:
                flow_name = r.traffic_name or ""
                biz_type = r.business_type or ""
                brand = r.brand or ""
                key = (flow_name, biz_type, brand)
                
                prev_month_data[key] = {
                    "market_fee_ratio": Decimal(str(r.market_fee_ratio_current or 0)),
                    "personnel_salary_ratio": Decimal(str(r.personnel_salary_ratio_current or 0)),
                    "gross_profit_ratio": Decimal(str(r.gross_profit_ratio_current or 0)),
                    "gmv": Decimal(str(r.gmv or 0)),
                }

            logger.info(f"[上月数据] 获取到 {len(prev_month_data)} 条 {prev_month_str} 历史记录")
        except Exception as e:
            logger.error(f"[上月数据] 查询失败: {str(e)}")

        return prev_month_data

    def scan_processing_tasks(self):
        """
        查询 data_process_task 表中 status='PROCESSING' 且 is_deleted=0 的任务列表。
        仅返回当前引擎支持的数据表类型(SUPPORTED_PROCESS_TYPES);
        其余类型(新接入报表等)暂不自动处理,保持 PROCESSING 待对应引擎接入。
        返回:任务列表(按创建时间升序)
        """
        logger.info("[扫描] 开始扫描待处理任务...")
        tasks = DataProcessTask.query.filter(
            DataProcessTask.status == 'PROCESSING',
            DataProcessTask.is_deleted == 0
        ).order_by(DataProcessTask.created_at.asc()).all()
        supported = [t for t in tasks if getattr(t, 'data_table_type', None) in SUPPORTED_PROCESS_TYPES]
        skipped = [t for t in tasks if getattr(t, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES]
        if skipped:
            logger.info(f"[扫描] 跳过 {len(skipped)} 个暂不支持自动处理的类型任务: "
                        f"{sorted({getattr(t, 'data_table_type_name', None) or getattr(t, 'data_table_type', '') for t in skipped})}")
        logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务,本次处理 {len(supported)} 个")
        return supported

    def _run_clean_pipeline(self, task):
        """
        前置运行「预算达成数据清洗」脚本(clean_budget_achievement),
        为成本计算建立 biz_budget_achieve 基础行与 GMV 数据。

        说明:
          - 仅对 data_table_type == CLEAN_DATA_TABLE_TYPE 的任务调用;
          - clean 使用独立的 pymysql 连接(get_conn)并自行提交,与本脚本的
            SQLAlchemy 会话互不干扰;运行结束后刷新 ORM 会话,确保后续成本计算
            能读到 clean 刚提交的新行;
          - 清洗失败直接抛异常,由调用方决定中止成本计算。
        """
        from clean_budget_achievement import get_conn, process_task as clean_process_task

        logger.info(f"[清洗前置] 任务 {task.id} ({task.month}) 开始运行预算达成数据清洗")
        conn = get_conn()
        try:
            try:
                clean_process_task(
                    conn,
                    {'id': task.id, 'month': task.month,
                     'data_table_type': task.data_table_type},
                    dry_run=False,
                )
            except (ImportError, ModuleNotFoundError) as e:
                logger.error(
                    f"[清洗前置] 任务 {task.id} ({task.month}) 缺少必要的依赖包: {e}\n"
                    f"请在终端运行: pip install -r requirements.txt"
                )
                raise
        finally:
            conn.close()
        # 清洗走独立连接并已提交;刷新 ORM 会话缓存,避免读到旧快照
        db.session.expire_all()
        logger.info(f"[清洗前置] 任务 {task.id} ({task.month}) 预算达成数据清洗完成")

    def process_all(self):
        """
        批量处理所有 PROCESSING 任务,单个失败不影响其他。
        对 data_table_type='budget_achievement' 的任务,先运行预算达成数据清洗
        (clean_budget_achievement)建立基础行与 GMV,再执行成本计算;
        清洗失败则该任务直接标记 FAILED,不再跑成本计算。
        """
        logger.info("=" * 60)
        logger.info("[批量处理] 开始批量处理所有待处理任务")
        logger.info("=" * 60)

        tasks = self.scan_processing_tasks()
        success_count = 0
        fail_count = 0

        for task in tasks:
            try:
                # 预算达成类任务:先跑数据清洗(建基础行 + GMV),失败则中止成本计算
                if getattr(task, 'data_table_type', None) == CLEAN_DATA_TABLE_TYPE:
                    self._run_clean_pipeline(task)
                self.process_task(task.id)
                success_count += 1
                logger.info(f"[批量处理] 任务 {task.id} ({task.month}) 处理成功")
            except Exception as e:
                import traceback
                fail_count += 1
                logger.error(f"[批量处理] 任务 {task.id} ({task.month}) 处理失败: {str(e)}")
                logger.error(traceback.format_exc())
                # 标记任务为失败
                try:
                    self._mark_task_failed(task.id, str(e))
                except Exception as mark_err:
                    logger.error(f"[批量处理] 标记任务失败状态时出错: {str(mark_err)}")

        logger.info("=" * 60)
        logger.info(f"[批量处理] 完成!成功 {success_count} 个,失败 {fail_count} 个")
        logger.info("=" * 60)
        return {'success': success_count, 'failed': fail_count}

    def process_task(self, task_id):
        """
        处理单个任务的完整流程。
        参数:
          - task_id: 任务ID
        """
        logger.info(f"[处理任务] 开始处理任务 ID: {task_id}")
        task_start_time = time.time()
        logger.info(f"[处理任务] 任务 {task_id} 开始处理, 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

        # 加载别名映射表(流量方、园区店标准名映射)- 强制刷新以获取最新配置
        load_alias_maps(force_refresh=True)

        # 获取任务
        task = DataProcessTask.query.filter_by(id=task_id, is_deleted=0).first()
        if not task:
            raise Exception(f"任务不存在: {task_id}")

        # 按 data_table_type 路由到对应处理器,避免非预算任务误跑预算达成流水线
        if getattr(task, 'data_table_type', None) == 'output_value':
            from output_value_processor import OutputValueProcessor
            logger.info(f"[处理任务] 路由 output_value 任务 {task_id} 至 OutputValueProcessor")
            OutputValueProcessor(app=self.app).process(task)
            return

        if getattr(task, 'data_table_type', None) == 'store_effect_earnings':
            from store_effect_summary_processor import StoreEffectSummaryProcessor
            logger.info(f"[处理任务] 路由 store_effect_earnings 任务 {task_id} 至 StoreEffectSummaryProcessor")
            StoreEffectSummaryProcessor(app=self.app).process(task)
            return

        if getattr(task, 'data_table_type', None) == 'avita_special':
            from avita_special_processor import AvitaSpecialProcessor
            logger.info(f"[处理任务] 路由 avita_special 任务 {task_id} 至 AvitaSpecialProcessor")
            AvitaSpecialProcessor(app=self.app).process(task)
            return

        if getattr(task, 'data_table_type', None) == 'baic_special':
            from baic_special_processor import BaicSpecialProcessor
            logger.info(f"[处理任务] 路由 baic_special 任务 {task_id} 至 BaicSpecialProcessor")
            BaicSpecialProcessor(app=self.app).process(task)
            return

        if getattr(task, 'data_table_type', None) == 'voyah_special':
            from voyah_processor import VoyahProcessor
            logger.info(f"[处理任务] 路由 voyah_special 任务 {task_id} 至 VoyahProcessor")
            VoyahProcessor(app=self.app).process(task)
            return

        if getattr(task, 'data_table_type', None) == 'leapmotor_special':
            from leapmotor_processor import LeapmotorProcessor
            logger.info(f"[处理任务] 路由 leapmotor_special 任务 {task_id} 至 LeapmotorProcessor")
            LeapmotorProcessor(app=self.app).process(task)
            return

        # 类型白名单保护:当前引擎仅支持 SUPPORTED_PROCESS_TYPES
        if getattr(task, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES:
            raise Exception(
                f"数据表类型「{task.data_table_type_name or task.data_table_type}」的处理引擎尚未接入,暂不支持自动处理")

        logger.info(f"[处理任务] 任务: {task.month} ({task.data_table_type_name})")

        # ========== 步骤 a: 将关联文件的 clean_status 从 1 更新为 2(清洗中) ==========
        step_a_start = time.time()
        logger.info("[处理任务] 步骤 a: 更新文件状态为清洗中...")
        files = DataProcessFile.query.filter_by(task_id=task_id, is_deleted=0).all()
        for f in files:
            f.clean_status = 2
        db.session.commit()
        logger.info(f"[处理任务] 已更新 {len(files)} 个文件状态为清洗中")
        logger.info(f"[处理任务] 步骤 a 完成, 耗时: {time.time() - step_a_start:.2f}s")

        # ========== 步骤 a-2: 重置所有待分配费用字段为 0 ==========
        reset_start = time.time()
        logger.info("[处理任务] 步骤 a-2: 重置费用字段...")
        try:
            import pymysql as _pymysql
            _uri = Config.SQLALCHEMY_DATABASE_URI or ''
            logger.info(f"[诊断] processor DB URI = {_uri}")
            _host = Config.MYSQL_HOST
            _port = int(Config.MYSQL_PORT or 3306)
            _user = Config.MYSQL_USER
            _pwd = Config.MYSQL_PASSWORD
            _db = Config.MYSQL_DB
            logger.info(f"[诊断] 连接 {_user}@{_host}:{_port}/{_db}")
            _conn = _pymysql.connect(host=_host, port=_port, user=_user,
                                     password=_pwd, db=_db, charset='utf8mb4', autocommit=True)
            _cur = _conn.cursor()
            # reset 前诊断
            # 2026-10 精简:仅诊断 processor 自己负责的字段(rent_utilities)
            #   renovation_amortization / store_consumables 由 clean_budget_achievement 写入,不得清零
            _cur.execute("SELECT SUM(rent_utilities) FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (task.id, task.month))
            _before = _cur.fetchone()
            logger.info(f"[诊断] reset 参数: task.id={task.id!r}, task.month={task.month!r}")
            logger.info(f"[诊断] reset 前: rent_utilities={float(_before[0] or 0):.2f}")
            # 2026-10 精简:仅清零 processor.py 自己负责重算的 rent_utilities
            #   renovation_amortization / store_consumables 由 clean_budget_achievement 管理,不应清零
            #   market_fee / external_construction / technician_salary / marketing_team_salary 已不再处理
            _cur.execute("""
                UPDATE biz_budget_achieve
                SET rent_utilities = 0,
                    updated_at = CURRENT_TIMESTAMP
                WHERE task_id = %s AND stat_month = %s
            """, (task.id, task.month))
            logger.info(f"[处理任务] 步骤 a-2 reset 影响行数: {_cur.rowcount}")
            # reset 后诊断
            _cur.execute("SELECT SUM(rent_utilities) FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (task.id, task.month))
            _after = _cur.fetchone()
            logger.info(f"[诊断] reset 后: rent_utilities={float(_after[0] or 0):.2f}")
            _conn.close()
            logger.info(f"[处理任务] 步骤 a-2 完成, 耗时 {time.time() - reset_start:.2f}s")
        except Exception as reset_err:
            logger.error(f"[处理任务] 步骤 a-2 重置失败: {reset_err}")

        try:
            # ========== 步骤 b: 下载所有关联文件到本地临时目录 ==========
            logger.info("[处理任务] 步骤 b: 下载文件到本地临时目录...")
            # 每次运行使用独立子目录(task_id + 随机uuid),避免并发处理同一任务时
            # 多个进程向同一文件名(如 市场费.xlsx)读写导致半截文件 -> BadZipFile
            tmp_dir = os.path.join(Config.UPLOAD_FOLDER, 'tmp', f"{task_id}_{uuid.uuid4().hex}")
            os.makedirs(tmp_dir, exist_ok=True)

            downloaded_files = {}
            
            # 过滤出必需的文件类型
            files_to_download = [f for f in files if f.form_type in REQUIRED_FORM_TYPES]
            skipped_files = [f for f in files if f.form_type not in REQUIRED_FORM_TYPES]
            for f in skipped_files:
                logger.warning(f"[处理任务] 跳过非必需文件: {f.form_type}")
            logger.info(f"[处理任务] 待下载文件列表 ({len(files_to_download)} 个):")
            for i, f in enumerate(files_to_download):
                logger.info(f"[处理任务]   [{i+1}] form_type={f.form_type}, file_url={f.file_url[:80] if f.file_url else 'None'}...")
            
            download_start_time = time.time()
            for i, f in enumerate(files_to_download):
                local_path = os.path.join(tmp_dir, f.file_name)
                file_download_start = time.time()
                logger.info(f"[处理任务] 开始下载 [{i+1}/{len(files_to_download)}]: {f.form_type}")
                
                # 检查 file_url 是否有效
                if not f.file_url or not str(f.file_url).strip():
                    logger.warning(f"[处理任务] 文件 {f.form_type} 无 file_url,跳过")
                    continue
                
                try:
                    download_file(f.file_url, local_path)
                    downloaded_files[f.form_type] = local_path
                    file_elapsed = time.time() - file_download_start
                    logger.info(f"[处理任务] 下载完成 [{i+1}/{len(files_to_download)}]: {f.form_type}, 耗时: {file_elapsed:.2f}s")
                except Exception as dl_err:
                    logger.error(f"[处理任务] 下载文件失败 [{i+1}/{len(files_to_download)}]: {f.form_type}, 错误: {str(dl_err)}")
                    # 对于必需的文件,下载失败时抛出异常
                    if f.form_type in REQUIRED_FORM_TYPES:
                        raise Exception(f"必需文件下载失败: {f.form_type} - {str(dl_err)}")
                    else:
                        logger.warning(f"[处理任务] 非必需文件下载失败,跳过: {f.form_type}")
                        continue

            total_download_elapsed = time.time() - download_start_time
            logger.info(f"[处理任务] 文件下载完成,共下载 {len(downloaded_files)} 个文件,总耗时: {total_download_elapsed:.2f}s")
            logger.info(f"[处理任务] 已下载文件类型: {list(downloaded_files.keys())}")

            # ========== 步骤 c: 根据 form_type 分发解析逻辑 ==========
            step_c_start = time.time()
            logger.info("[处理任务] 步骤 c: 解析上传的文件...")

            # 从数据库获取 GMV 和产值数据(替代解析结算数据汇总表 Excel)
            settlement_data = None
            logger.info(f"[诊断] 调用_fetch_gmv_from_db: task.id={task.id}, task.month={task.month}")
            settlement_map, park_ratio_map, park_rows_data, flow_ratio_entries = self._fetch_gmv_from_db(task.id, task.month)
            logger.info(f"[诊断] _fetch_gmv_from_db 返回: settlement_map={len(settlement_map)}, park_ratio_map={len(park_ratio_map)}, park_rows_data={len(park_rows_data) if park_rows_data else 0}, flow_ratio_entries={len(flow_ratio_entries)}")
            if settlement_map:
                # 构建兼容格式的 settlement_data(供 _build_cost_summary 使用)
                settlement_data = []
                for (flow, biz, brand), data in settlement_map.items():
                    settlement_data.append({
                        "流量方名称": flow,
                        "业务类型": biz,
                        "品牌": brand,
                        "GMV": data["GMV"],
                        "产值": data["产值"],
                        "服务费": data.get("服务费", Decimal("0")),
                        "嘀加分润": data.get("嘀加分润", Decimal("0")),
                        "服务商": data.get("服务商", ""),
                        "装修摊销": data.get("装修摊销", Decimal("0")),
                        "门店耗材": data.get("门店耗材", Decimal("0")),
                        "gmv_ratio": data.get("gmv_ratio"),
                        "gmv_ratio_park": data.get("gmv_ratio_park"),
                        "park_store": data.get("park_store", ""),
                    })
                logger.info(f"[处理任务] 从数据库获取 GMV 数据 {len(settlement_data)} 条记录")
            else:
                logger.warning("[处理任务] 数据库中无 GMV 数据,市场费分摊将降级为直接汇总")

            # 解析市场费(传入 settlement_map 用于 GMV 分摊)
            market_results = []
            unmatched_market = {}
            if '市场费总表' in downloaded_files:
                market_results, unmatched_market = self._parse_market_fee(downloaded_files['市场费总表'], settlement_map)
                logger.info(f"[处理任务] 市场费解析完成,共 {len(market_results)} 条记录")

            # 解析外援施工费(传入 flow_ratio_entries 用于 gmv_ratio 分摊)
            wage_results = {}
            unmatched_external = {}
            if '外施施工费用表' in downloaded_files:
                wage_results, unmatched_external = self._parse_external_worker_fee(downloaded_files['外施施工费用表'], settlement_map=settlement_map, flow_ratio_entries=flow_ratio_entries)
                logger.info(f"[处理任务] 外援施工费解析完成,共 {len(wage_results)} 条记录")

            # 解析人力成本(传递 flow_ratio_entries 用于无品牌比例分配)
            labor_results = {}
            unmatched_labor = {}
            if '人力成本统计表' in downloaded_files:
                labor_results, unmatched_labor = self._parse_labor_cost(downloaded_files['人力成本统计表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id, stat_month=task.month, db=db)
                logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 个key")
                # 按主键id更新
                labor_total_input, labor_total_output, labor_updated, labor_skipped = self._update_labor_cost_by_id(
                    task.id, task.month, labor_results
                )
                # 写库 skip 的钱暂存(稍后合并进 unmatched_collector)
                logger.info(f"[处理任务] 人力成本写库 skip: {labor_skipped}")
                logger.info(f"[处理任务] 人力成本更新完成: 输入={labor_total_input}, 输出={labor_total_output}, 更新{labor_updated}行")

            # 解析房租水电施工费
            utility_results = []
            gmv_allocated_utility = []
            unmatched_utility = {}
            if '房租水电费用表' in downloaded_files:
                utility_results, gmv_allocated_utility, unmatched_utility = self._parse_utility_fee(downloaded_files['房租水电费用表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id)
                logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录,GMV分摊 {len(gmv_allocated_utility)} 条")
                logger.info(f"[处理任务] 房租水电 unmatched_utility={unmatched_utility}")
            else:
                logger.warning(f"[处理任务] downloaded_files 里无 '房租水电费用表',available={list(downloaded_files.keys())}")

            # 收集所有未匹配金额(先不写库,等所有 update 完后统一写 —— 因为 _update_utility_fee_to_db 可能返回 failed_amount 需补进 unmatched)
            unmatched_collector = {**unmatched_market, **unmatched_external, **unmatched_labor, **unmatched_utility}
            # 合并 labor_cost 写库 skip 金额(因无 DB 行丢失的钱 → 归入 unmatched)
            try:
                if labor_skipped:
                    for col, amt in labor_skipped.items():
                        if amt > 0:
                            unmatched_collector[col] = unmatched_collector.get(col, Decimal("0")) + amt
                    logger.info(f"[未匹配收集] 合并 labor_skipped 后: {unmatched_collector}")
            except NameError:
                pass  # 没有人力成本统计表 → labor_skipped 未定义,跳过
            logger.info(f"[未匹配收集] processor 侧(初步): {unmatched_collector}")
            # 【写库延后到所有 update 之后统一执行 —— 见 L1725+】
            logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s")

            # ========== 步骤 d: 执行成本计算 ==========
            step_d_start = time.time()
            logger.info("[处理任务] 步骤 d: 执行成本计算...")
            
            # 外援施工费:直接按 gmv_ratio 分摊 + 按主键id更新
            if wage_results:
                logger.info(f"[处理任务] 外援施工费解析结果: {len(wage_results)} 个key, 开始按主键id分摊更新")
                wage_total_input, wage_total_output, wage_updated, _ = self._update_wage_fee_by_id(
                    task.id, task.month, wage_results
                )
                logger.info(f"[处理任务] 外援施工费更新完成: 输入={wage_total_input}, 输出={wage_total_output}, 更新{wage_updated}行")
            
            # 市场费已通过 _update_market_fee_by_id 独立处理,传递空列表避免重复匹配
            # 外援施工费已在步骤d中处理,传递空列表避免重复处理
            prev_month_data = self._fetch_previous_month_data(task.id, task.month)
            
            summary_data = self._build_cost_summary(
                settlement_data, [], [], [], utility_results, prev_month_data,
                settlement_map=settlement_map, park_ratio_map=park_ratio_map, flow_ratio_entries=flow_ratio_entries
            )
            logger.info(f"[处理任务] 成本计算完成,共 {len(summary_data)} 条汇总记录")
            logger.info(f"[处理任务] 步骤 d 完成, 耗时: {time.time() - step_d_start:.2f}s")

            # ========== 步骤 e: 将结果写入 biz_budget_achieve 表 ==========
            step_e_start = time.time()
            logger.info("[处理任务] 步骤 e: 写入预算达成表...")

            # 市场费直接使用 market_results,不通过 summary_data 提取(避免重复计算)
            market_fee_data = [r for r in market_results if r.get("市场费", Decimal("0")) > 0]
            utility_fee_data = [r for r in summary_data if r.get("房租及水电费", Decimal("0")) > 0]
            
            # 合并GMV分摊的记录,这些记录绕过了_build_cost_summary
            all_utility_data = utility_fee_data + gmv_allocated_utility

            logger.info(f"[处理任务] 各费用类型数据量: 市场费={len(market_fee_data)}, "
                        f"房租水电费={len(utility_fee_data)}+GMV分摊={len(gmv_allocated_utility)}")

            # 依次执行各独立更新
            if market_fee_data:
                self._update_market_fee_by_id(task.id, task.month, market_fee_data)
            if all_utility_data:
                _, failed_amount = self._update_utility_fee_to_db(task.id, task.month, all_utility_data)
                # 写库失败的金额 → 合并进 unmatched_collector(稍后统一写库)
                if failed_amount > 0:
                    cur_rent = Decimal(str(unmatched_collector.get('rent_utilities', 0) or 0))
                    unmatched_collector['rent_utilities'] = cur_rent + failed_amount
                    logger.info(f"[未匹配补录] 房租水电写库失败合并到 unmatched_collector: failed_amount={failed_amount}, rent_utilities now={unmatched_collector['rent_utilities']}")

            # 人员工资汇总值和占比更新(按主键ID直接更新,在所有金额数据落库后执行)
            # 2026-10 精简:人力成本统计表已移除,此步骤仅当 labor_results 非空时执行
            if labor_results:
                self._update_labor_ratios_by_id(task.id, task.month)

            # 毛利更新(按主键ID直接更新,在所有前置数据落库后最后执行)
            self._update_gross_profit_by_id(task.id, task.month)

            logger.info(f"[处理任务] 步骤 e 完成, 耗时: {time.time() - step_e_start:.2f}s")

            # ========== 步骤 e-2: 统一写库 biz_unmatched_fee(先删后插) ==========
            # 所有 update 执行完毕后,把 unmatched_collector 一次性写入,避免顺序问题
            # 2026-10 精简:仅保留房租水电的未匹配追踪(其他费用类型不再处理)
            PROCESSOR_FEE_TYPES = ['rent_utilities']
            try:
                logger.info(f"[未匹配写库] 最终 unmatched_collector={unmatched_collector}")
                BizUnmatchedFee.query.filter(
                    BizUnmatchedFee.task_id == task.id,
                    BizUnmatchedFee.stat_month == task.month,
                    BizUnmatchedFee.fee_type.in_(PROCESSOR_FEE_TYPES),
                ).delete(synchronize_session='fetch')
                db.session.flush()
                inserted = 0
                for fee_type, amount in unmatched_collector.items():
                    if fee_type not in PROCESSOR_FEE_TYPES:
                        continue
                    amt = Decimal(str(amount)) if amount is not None else Decimal('0')
                    if amt == 0:
                        continue
                    db.session.add(BizUnmatchedFee(
                        task_id=task.id, stat_month=task.month,
                        fee_type=fee_type, unmatched_amount=amt,
                    ))
                    inserted += 1
                db.session.commit()
                logger.info(f"[未匹配写库] 完成: task={task.id} month={task.month} 写入 {inserted} 条")
            except Exception as e_unm:
                db.session.rollback()
                logger.error(f"[未匹配写库] 失败: {e_unm}", e_unm)

            # ========== 步骤 f: 生成汇总 Excel 并上传到 OSS ==========
            step_f_start = time.time()
            logger.info("[处理任务] 步骤 f: 生成汇总 Excel 并上传到 OSS...")
            result_file_url = self._generate_and_upload_excel(task.id, task.month, tmp_dir)
            logger.info(f"[处理任务] 结果文件已上传: {result_file_url}")
            logger.info(f"[处理任务] 步骤 f 完成, 耗时: {time.time() - step_f_start:.2f}s")

            # ========== 步骤 g: 更新文件 clean_status 为 3(清洗完成) ==========
            step_g_start = time.time()
            logger.info("[处理任务] 步骤 g: 更新文件状态为清洗完成...")
            for f in files:
                f.clean_status = 3
            db.session.commit()
            logger.info(f"[处理任务] 步骤 g 完成, 耗时: {time.time() - step_g_start:.2f}s")

            # ========== 步骤 h: 更新任务 status 为 COMPLETED,回填 result_file_url ==========
            step_h_start = time.time()
            logger.info("[处理任务] 步骤 h: 更新任务状态为已完成...")
            task.status = 'COMPLETED'
            task.result_file_url = result_file_url
            task.error_msg = ''
            task.updater = task.updater or task.creator
            db.session.commit()
            logger.info(f"[处理任务] 步骤 h 完成, 耗时: {time.time() - step_h_start:.2f}s")
            total_elapsed = time.time() - task_start_time
            logger.info(f"[处理任务] 任务 {task_id} 处理完成!总耗时: {total_elapsed:.2f}s")

            # 清理临时文件
            self._cleanup_tmp_dir(tmp_dir)

        except Exception as e:
            # ========== 步骤 i: 异常时标记任务 status=FAILED,记录 error_msg ==========
            import traceback
            error_detail = f"处理任务 {task_id} 失败: {str(e)}\n{traceback.format_exc()}"
            logger.error(error_detail)
            db.session.rollback()
            try:
                self._mark_task_failed(task_id, str(e))
            except Exception as mark_err:
                logger.error(f"[处理任务] 标记失败状态时出错: {str(mark_err)}")
            # 清理临时文件
            try:
                self._cleanup_tmp_dir(tmp_dir)
            except Exception as cleanup_err:
                logger.warning(f"[处理任务] 清理临时文件时出错: {str(cleanup_err)}")
            raise

    # ========================================================
    # 解析结算数据汇总表(GMV 和产值)
    # ========================================================

    def _parse_settlement(self, file_path):
        """
        解析结算数据汇总表,获取 GMV 和产值数据。
        返回:List[dict],每行包含 {流量方名称, 业务类型, 品牌, GMV, 产值}
        """
        logger.info(f"[结算数据] 解析文件: {file_path}")

        if not os.path.exists(file_path):
            logger.warning(f"[结算数据] 文件不存在: {file_path}")
            return []

        xls = pd.ExcelFile(file_path)
        all_results = []

        for sheet_name in xls.sheet_names:
            df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
            header_row, title_rows = detect_header_row(df_raw)
            df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
            df.columns = [str(col).strip() for col in df.columns]

            # 查找关键列
            col_flow = find_column(df, "流量方名称", "流量方", "门店", "流量来源")
            col_gmv = find_column(df, "GMV", "gmv", "交易额")
            col_revenue = find_column(df, "产值", "收入", "营业额")
            col_biz = find_column(df, "业务类型", "业务分类")
            col_model = find_column(df, "车型", "商品名称", "产品名称", "品牌")

            for _, row in df.iterrows():
                flow_name = None
                if col_flow:
                    flow_name = row[col_flow]
                if flow_name is None or str(flow_name).strip() == "" or str(flow_name).strip() == "nan":
                    continue

                flow_name = str(flow_name).strip()
                if flow_name == "":
                    continue

                # 获取业务类型
                biz_type = None
                if col_biz:
                    biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
                    if "1.1" in biz_val or "贴膜" in biz_val:
                        biz_type = BIZ_TYPE_1_1
                    elif "2.1" in biz_val:
                        biz_type = BIZ_TYPE_2_1
                    elif "2.3" in biz_val:
                        biz_type = BIZ_TYPE_2_3

                # 获取 GMV
                gmv = Decimal("0")
                if col_gmv:
                    gmv = safe_decimal(row[col_gmv])

                # 获取产值
                revenue = Decimal("0")
                if col_revenue:
                    revenue = safe_decimal(row[col_revenue])

                if gmv == 0 and revenue == 0:
                    continue

                # 识别品牌
                brand = None
                if col_model:
                    brand = identify_brand(row[col_model])

                result_row = {
                    "流量方名称": flow_name,
                    "业务类型": biz_type or "未知",
                    "品牌": brand or "",
                    "GMV": round_2(gmv),
                    "产值": round_2(revenue),
                }
                all_results.append(result_row)

        # 按 (流量方, 业务类型, 品牌) 汇总
        aggregated = defaultdict(lambda: {"GMV": Decimal("0"), "产值": Decimal("0")})
        for r in all_results:
            key = (r["流量方名称"], r["业务类型"], r["品牌"])
            aggregated[key]["GMV"] += r["GMV"]
            aggregated[key]["产值"] += r["产值"]

        result = []
        for (flow, biz, brand), data in aggregated.items():
            result.append({
                "流量方名称": flow,
                "业务类型": biz,
                "品牌": brand,
                "GMV": round_2(data["GMV"]),
                "产值": round_2(data["产值"]),
            })

        logger.info(f"[结算数据] 解析完成,共 {len(result)} 条汇总记录")
        return result

    def _allocate_market_fee_by_gmv(self, records, settlement_map):
        """
        市场费品牌匹配主入口 —— 按 (流量方, 业务类型) 分组后走三个分支:
          场景A. 单条记录 → 跳过品牌匹配 + 跳过 GMV 分摊,identify_brand 返回什么就是什么
          场景B. 多条且同时存在 问界+鸿蒙 → 逐行按车型匹配,无车型行跳过(fee=0)
          默认. 多条但单品牌/全未知 → 走原有 GMV 分摊逻辑(_apply_gmv_allocation)
        参数:
          - records: List[dict],原始记录列表,每条包含 {流量方名称, 业务类型, 品牌, 市场费}
          - settlement_map: {(流量方, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal}}
        返回:List[dict],最终输出列表,元素 {流量方名称, 业务类型, 品牌, 市场费}
        """
        if not records:
            return []

        # 预构建 2-tuple 索引:(flow_key, biz) → [(brand, gmv_ratio, GMV)]
        # flow_key 同时存原始名和 to_standard 后的值,双向可查
        flat_index = defaultdict(list)
        for (sf, sb, sbr), data in settlement_map.items():
            if not (sf and sb and sbr):
                continue
            entry = (sbr, data.get("gmv_ratio"), data["GMV"])
            flat_index[(sf, sb)].append(entry)
            std_f = to_standard(sf, '4s')
            if std_f and std_f != sf:
                flat_index[(std_f, sb)].append(entry)

        # 按 (流量方, 业务类型) 分组
        groups = defaultdict(list)
        for r in records:
            key = (r["流量方名称"], r["业务类型"])
            groups[key].append(r)

        result = []
        for (flow, biz), group_records in groups.items():
            # ---------- 场景A: 单条记录 ----------
            if len(group_records) == 1:
                r = group_records[0]
                brand = r.get("品牌") or "未知品牌"
                fee = r.get("市场费", Decimal("0"))
                logger.info(f"[市场费·规则1命中] flow={flow}, biz={biz}, brand={brand}, fee={fee}")
                result.append({
                    "流量方名称": flow,
                    "业务类型": biz,
                    "品牌": brand,
                    "市场费": round_2(fee),
                })
                continue

            # ---------- 多条:检查品牌集合 ----------
            known_brands = {
                r.get("品牌") for r in group_records
                if r.get("品牌") and r.get("品牌") != "未知品牌"
            }

            has_wj = "问界" in known_brands
            has_hm = "鸿蒙" in known_brands

            # ---------- 场景B: 同时有 问界 + 鸿蒙 ----------
            if has_wj and has_hm:
                # 收集问界和鸿蒙在 settlement_map 里的 GMV,用于无车型行分摊
                wj_gmv_data = settlement_map.get((flow, biz, "问界"), {})
                hm_gmv_data = settlement_map.get((flow, biz, "鸿蒙"), {})
                wj_gmv = Decimal(str(wj_gmv_data.get("GMV", 0) or 0))
                hm_gmv = Decimal(str(hm_gmv_data.get("GMV", 0) or 0))
                total_gmv = wj_gmv + hm_gmv

                logger.info(f"[市场费·规则2命中·双品牌] flow={flow}, biz={biz}, 总行数={len(group_records)}, "
                            f"问界GMV={wj_gmv}, 鸿蒙GMV={hm_gmv}")

                output_by_brand = defaultdict(Decimal)
                unknown_fee = Decimal("0")
                for r in group_records:
                    brand = r.get("品牌")
                    fee = r.get("市场费", Decimal("0"))
                    if brand == "未知品牌":
                        unknown_fee += fee
                    else:
                        output_by_brand[brand] += fee

                # 无车型行费用按 GMV 比例分摊到问界和鸿蒙
                if unknown_fee > 0:
                    if total_gmv > 0:
                        wj_share = unknown_fee * (wj_gmv / total_gmv)
                        hm_share = unknown_fee - wj_share  # 吃掉尾差
                    else:
                        # GMV 为 0 → 回退平均分摊
                        wj_share = unknown_fee / 2
                        hm_share = unknown_fee - wj_share
                    output_by_brand["问界"] += wj_share
                    output_by_brand["鸿蒙"] += hm_share
                    logger.info(f"[市场费·规则2命中·无车型分摊] flow={flow}, biz={biz}, "
                                f"unknown_fee={round_2(unknown_fee)}, "
                                f"wj_share={round_2(wj_share)}, hm_share={round_2(hm_share)}")

                for brand, fee in output_by_brand.items():
                    result.append({
                        "流量方名称": flow,
                        "业务类型": biz,
                        "品牌": brand,
                        "市场费": round_2(fee),
                    })
                continue

            # ---------- 默认: 单品牌 / 全未知 → 走原有 GMV 分摊 ----------
            default_total_fee = sum(r.get("市场费", Decimal("0")) for r in group_records)
            default_brands = {r.get("品牌", "未知品牌") for r in group_records}
            logger.info(f"[市场费·规则3命中·GMV分摊] flow={flow}, biz={biz}, "
                        f"品牌={default_brands}, 行数={len(group_records)}, 费用={default_total_fee}")
            result.extend(self._apply_gmv_allocation(group_records, flow, biz, settlement_map))

        logger.info(f"[市场费分摊] 完成,共 {len(result)} 条记录")
        return result

    def _apply_gmv_allocation(self, group_records, flow, biz, settlement_map):
        """
        原有 GMV 分摊逻辑 —— 供 _allocate_market_fee_by_gmv 在默认分支调用。
        规则与改造前完全一致:未知品牌费用按已知品牌 GMV 占比分摊。
        """
        # 按品牌汇总费用
        brand_fees = defaultdict(Decimal)   # {品牌: 费用合计}
        unknown_brand_fee = Decimal("0")    # 未知品牌的费用总和

        for r in group_records:
            brand = r.get("品牌", "未知品牌")
            fee = r.get("市场费", Decimal("0"))
            if brand == "未知品牌":
                unknown_brand_fee += fee
            else:
                brand_fees[brand] += fee

        # 诊断日志:分摊前的品牌费用(仅针对特定流量方)
        if "广西恒为" in flow or "恒为" in flow:
            logger.info(f"[市场费诊断] 分摊前 flow={flow}, biz={biz}:")
            for brand, fee in brand_fees.items():
                logger.info(f"[市场费诊断]   品牌={brand}, 原始费用={fee}")
            logger.info(f"[市场费诊断]   未知品牌费用={unknown_brand_fee}, "
                        f"未知品牌行数={len([r for r in group_records if r.get('品牌') == '未知品牌'])}")

        # 如果有未知品牌费用且存在已知品牌,进行 GMV 分摊
        if unknown_brand_fee > 0 and brand_fees:
            # 获取各品牌的 GMV
            brand_gmv = {}
            for brand in brand_fees.keys():
                key = (flow, biz, brand)
                if key in settlement_map:
                    brand_gmv[brand] = settlement_map[key]["GMV"]
                else:
                    brand_gmv[brand] = Decimal("0")

            total_gmv = sum(brand_gmv.values())

            # 诊断日志:GMV 数据
            if "广西恒为" in flow or "恒为" in flow:
                logger.info(f"[市场费诊断] GMV数据 flow={flow}, biz={biz}:")
                for brand, gmv in brand_gmv.items():
                    logger.info(f"[市场费诊断]   品牌={brand}, GMV={gmv}")
                logger.info(f"[市场费诊断]   总GMV={total_gmv}")

            if total_gmv > 0:
                # 按 GMV 占比分摊未知品牌费用
                for brand in brand_fees.keys():
                    ratio = brand_gmv[brand] / total_gmv
                    allocated_fee = (unknown_brand_fee * ratio).quantize(
                        Decimal("0.01"), rounding=ROUND_HALF_UP)
                    brand_fees[brand] += allocated_fee

                    # 诊断日志:分摊金额
                    if "广西恒为" in flow or "恒为" in flow:
                        logger.info(f"[市场费诊断]   品牌={brand}, "
                                    f"GMV占比={ratio:.4f}, 分摊金额={allocated_fee}")

                # 尾差归并
                first_brand = list(brand_fees.keys())[0]
                allocated_sum = sum(
                    (unknown_brand_fee * (brand_gmv[b] / total_gmv)).quantize(
                        Decimal("0.01"), rounding=ROUND_HALF_UP)
                    for b in brand_fees.keys()
                )
                diff = unknown_brand_fee - allocated_sum
                if diff != 0:
                    brand_fees[first_brand] += diff
                    if "广西恒为" in flow or "恒为" in flow:
                        logger.info(f"[市场费诊断]   尾差={diff}, 加到第一个品牌={first_brand}")
            else:
                # GMV 都为 0,平均分摊
                n = len(brand_fees)
                avg_fee = (unknown_brand_fee / n).quantize(
                    Decimal("0.01"), rounding=ROUND_HALF_UP)
                for brand in brand_fees.keys():
                    brand_fees[brand] += avg_fee
                # 尾差归并
                allocated_sum = avg_fee * n
                diff = unknown_brand_fee - allocated_sum
                if diff != 0:
                    first_brand = list(brand_fees.keys())[0]
                    brand_fees[first_brand] += diff

        # 诊断日志:分摊后的品牌费用
        if "广西恒为" in flow or "恒为" in flow:
            logger.info(f"[市场费诊断] 分摊后 flow={flow}, biz={biz}:")
            for brand, fee in brand_fees.items():
                logger.info(f"[市场费诊断]   品牌={brand}, 分摊后费用={fee}")

        # 输出结果
        result = []
        for brand, fee in brand_fees.items():
            result.append({
                "流量方名称": flow,
                "业务类型": biz,
                "品牌": brand,
                "市场费": round_2(fee),
            })

        # 处理:如果所有记录都是未知品牌(无已知品牌可分摊),直接保留
        if not brand_fees and unknown_brand_fee > 0:
            result.append({
                "流量方名称": flow,
                "业务类型": biz,
                "品牌": "未知品牌",
                "市场费": round_2(unknown_brand_fee),
            })

        return result

    @staticmethod
    def _append_split_result(result, flow, biz, fixed_brand, total_fee, entries):
        """
        将 total_fee 按比例分摊到 entries 的各品牌,追加到 result。
        比例优先级:gmv_ratio 归一化 → GMV 值归一化 → 平均分摊

        Args:
            result: 待追加的结果列表
            flow: 流量方
            biz: 业务类型
            fixed_brand: 若不为 None,所有输出用这个品牌;若为 None 用 entries 里的品牌
            total_fee: 待分摊的总费用
            entries: [(brand, gmv_ratio_float_or_None, GMV_Decimal), ...]
        """
        n = len(entries)
        if n == 0:
            return

        # 判断是否有可用的 gmv_ratio(全部 None 就降级)
        ratios = []
        has_ratio = False
        for (br, rt, gmv) in entries:
            if rt is not None:
                ratios.append(Decimal(str(rt)))
                has_ratio = True
            else:
                ratios.append(Decimal("0"))

        if has_ratio:
            total_ratio = sum(ratios)
            if total_ratio > 0:
                for i, (br, rt, gmv) in enumerate(entries):
                    allocated = (total_fee * ratios[i] / total_ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
                    out_brand = fixed_brand if fixed_brand is not None else br
                    result.append({"流量方名称": flow, "业务类型": biz,
                                   "品牌": out_brand, "市场费": allocated})
                # 尾差归并到最后一条
                allocated_sum = sum(item["市场费"] for item in result[-n:])
                diff = total_fee - allocated_sum
                if diff != 0:
                    result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
                return

        # 降级:用 GMV 值
        gmv_total = sum(gmv for (_, _, gmv) in entries)
        if gmv_total > 0:
            for (br, rt, gmv) in entries:
                allocated = (total_fee * gmv / gmv_total).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
                out_brand = fixed_brand if fixed_brand is not None else br
                result.append({"流量方名称": flow, "业务类型": biz,
                               "品牌": out_brand, "市场费": allocated})
            allocated_sum = sum(item["市场费"] for item in result[-n:])
            diff = total_fee - allocated_sum
            if diff != 0:
                result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
            return

        # 最终降级:平均分摊
        avg = (total_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        for (br, rt, gmv) in entries:
            out_brand = fixed_brand if fixed_brand is not None else br
            result.append({"流量方名称": flow, "业务类型": biz,
                           "品牌": out_brand, "市场费": avg})
        allocated_sum = avg * n
        diff = total_fee - allocated_sum
        if diff != 0:
            result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)

    # ========================================================
    # 解析市场费表
    # ========================================================

    def _parse_market_fee(self, file_path, settlement_map=None):
        """
        解析市场费表。
        规则:
          - 按 Title 分组匹配业务类型(Title2-5→1.1,Title6-7→2.1,Title9-10→2.3)
          - 1.1业务:取"市场费"(Title2/3/5) 或 "市场费总额"(Title4)
          - 2.1业务:取"市场费"(Title7) 或 "市场费总额"(Title6)
          - 2.3业务:取"市场费+资源费";商品类别=权益服务/延保-原厂权益归属2.1
          - 品牌归属:含"问界"→问界,含"享界/智界/尊界/尚界"→鸿蒙,无车型→未知品牌
          - GMV 分摊:同组内未知品牌费用按已知品牌 GMV 占比分摊
        参数:
          - file_path: 市场费 Excel 文件路径
          - settlement_map: GMV 数据映射(可选),用于品牌分摊
        返回:List[dict],每行 {流量方名称, 业务类型, 品牌, 市场费}
        """
        logger.info(f"[市场费] 解析文件: {file_path}")

        if not os.path.exists(file_path):
            logger.warning(f"[市场费] 文件不存在: {file_path}")
            return [], {'market_fee': Decimal('0')}

        if settlement_map is None:
            settlement_map = {}

        unmatched = {'market_fee': Decimal('0')}
        total_input_fee = Decimal('0')

        # 预构建:从 settlement_map 收集所有有 2.1 业务记录的流量方
        has_2_1_biz = set()
        for (flow_n, bt, brand) in settlement_map.keys():
            if bt == BIZ_TYPE_2_1 and flow_n:
                has_2_1_biz.add(flow_n)
                # 同时添加标准化后的名称(用于匹配)
                std_flow = to_standard(flow_n, '4s')
                if std_flow:
                    has_2_1_biz.add(std_flow)
        logger.info(f"[市场费][2.3→2.1归属] 预构建完成: {len(has_2_1_biz)} 个流量方有 2.1 业务")

        xls = pd.ExcelFile(file_path)
        all_results = []
        total_skipped = 0  # 统计被跳过的行数

        for sheet_name in xls.sheet_names:
            # 检查是否需要跳过此 Sheet
            should_skip = False
            for skip_pattern in SHEET_SKIP_PATTERNS:
                if skip_pattern in sheet_name:
                    logger.info(f"[市场费] Sheet '{sheet_name}' 匹配跳过规则 '{skip_pattern}',跳过")
                    should_skip = True
                    break
            if should_skip:
                continue

            # 根据 Sheet 名称匹配业务类型和取费列
            sheet_config = None
            for config in SHEET_BIZ_MAP:
                pattern = config['pattern']
                if pattern.startswith('^'):
                    # 精确匹配(正则)
                    if re.match(pattern, sheet_name):
                        sheet_config = config
                        break
                else:
                    # 包含匹配
                    if pattern in sheet_name:
                        sheet_config = config
                        break
            
            if not sheet_config:
                logger.info(f"[市场费] Sheet '{sheet_name}' 未匹配到业务类型规则,跳过")
                continue
            
            sheet_biz_type = sheet_config['biz_type']
            fee_col_type = sheet_config['fee_col']
            logger.info(f"[市场费] Sheet '{sheet_name}' -> 业务类型={sheet_biz_type}, 取费列={fee_col_type}")

            df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
            header_row, title_rows = detect_header_row(df_raw)
            df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
            df.columns = [str(col).strip() for col in df.columns]
            
            # 查找关键列 - 支持多种列名模式(在过滤隐藏行之前执行,以便 ffill 使用完整数据)
            col_flow = find_column(df, "流量方-流量方", "流量方名称", "流量方", "门店", "服务商")
            col_fee_market = find_column(df, "市场费")
            col_fee_total = find_column(df, "市场费总额", "市场费合计")
            col_fee_resource = find_column(df, "资源费")
            col_model = find_column(df, "车型", "商品名称", "产品名称")
            col_category = find_column(df, "商品类型", "商品类别", "类别", "业务类别")

            # 记录 ffill() 前的非空值数量(用于诊断)
            if col_model:
                model_nonnull_before = df[col_model].notna().sum()
            if col_flow:
                flow_nonnull_before = df[col_flow].notna().sum()
            if col_category:
                category_nonnull_before = df[col_category].notna().sum()

            # 前向填充合并单元格的值(流量方、车型、商品类型列都可能有合并单元格)
            # 先保存原始空值标记(用于过滤末尾汇总行,防止 ffill 将汇总行错误填充)
            if col_flow:
                original_flow_empty_mask = df[col_flow].isna() | (df[col_flow].astype(str).str.strip() == '')
                df[col_flow] = df[col_flow].ffill()
            if col_model:
                df[col_model] = df[col_model].ffill()
            if col_category:
                df[col_category] = df[col_category].ffill()

            # 诊断:ffill() 填充效果
            if col_model:
                model_nonnull_after = df[col_model].notna().sum()
                logger.info(f"[市场费诊断] ffill 填充效果: 车型列 {model_nonnull_before}→{model_nonnull_after} (增加{model_nonnull_after - model_nonnull_before}行)")
            if col_flow:
                flow_nonnull_after = df[col_flow].notna().sum()
                logger.info(f"[市场费诊断] ffill 填充效果: 流量方列 {flow_nonnull_before}→{flow_nonnull_after} (增加{flow_nonnull_after - flow_nonnull_before}行)")
            if col_category:
                category_nonnull_after = df[col_category].notna().sum()
                logger.info(f"[市场费诊断] ffill 填充效果: 商品类型列 {category_nonnull_before}→{category_nonnull_after} (增加{category_nonnull_after - category_nonnull_before}行)")
            
            # 诊断:检测并过滤隐藏行
            visible_indices = get_visible_row_indices(file_path, sheet_name, header_row)
            logger.info(f"[市场费诊断] Sheet '{sheet_name}': get_visible_row_indices 返回 type={type(visible_indices).__name__}, len={len(visible_indices) if visible_indices else 0}")
            if visible_indices is not None:
                # 显示前5个和后5个索引
                sorted_indices = sorted(visible_indices)
                logger.info(f"[市场费诊断]   前5个索引: {sorted_indices[:5]}")
                logger.info(f"[市场费诊断]   后5个索引: {sorted_indices[-5:]}")
            
            if visible_indices is not None and len(visible_indices) > 0:
                original_row_count = len(df)
                # 安全检查:过滤掉超出 DataFrame 范围的索引
                max_valid_index = len(df) - 1
                valid_indices = [idx for idx in visible_indices if idx <= max_valid_index]
                if len(valid_indices) < len(visible_indices):
                    logger.warning(f"[市场费诊断] Sheet '{sheet_name}': 有 {len(visible_indices) - len(valid_indices)} 个索引超出范围,已过滤")
                # 过滤到只有可见行
                df = df.iloc[valid_indices]
                if len(df) < original_row_count:
                    logger.info(f"[市场费] Sheet '{sheet_name}': 过滤隐藏行后 {original_row_count} → {len(df)} 行")
            elif visible_indices is None:
                logger.warning(f"[市场费诊断] Sheet '{sheet_name}': get_visible_row_indices 返回 None,使用所有行")
            
            # 过滤 ffill 前原始流量方为空的行(汇总行/合计行被 ffill 错误填充导致的幽灵行)
            if col_flow:
                original_row_count = len(df)
                valid_mask = ~original_flow_empty_mask.reindex(df.index)
                df = df[valid_mask]
                filtered_count = original_row_count - len(df)
                if filtered_count > 0:
                    logger.info(f"[市场费] Sheet '{sheet_name}': 过滤原始空行 {filtered_count} 条(ffill填充的汇总行),剩余 {len(df)} 行")
            
            # 调试日志:显示所有列名
            logger.info(f"[市场费] Sheet '{sheet_name}' 共 {len(df.columns)} 列: {list(df.columns)}")
            logger.info(f"[市场费] 数据行数: {len(df)}")
            if len(df) > 0:
                logger.info(f"[市场费] 第1行数据预览:")
                first_row = {k: str(v)[:40] for k, v in df.iloc[0].items() if pd.notna(v) and str(v).strip()}
                logger.info(f"[市场费]   {first_row}")
                # 添加最后3行预览,排查汇总行
                if len(df) >= 2:
                    logger.info(f"[市场费] 最后3行数据预览:")
                    for idx in range(max(0, len(df)-3), len(df)):
                        last_row = {k: str(v)[:40] for k, v in df.iloc[idx].items() if pd.notna(v) and str(v).strip()}
                        logger.info(f"[市场费]   行{idx}: {last_row}")

            # 根据配置选择取费列
            if fee_col_type == 'market_fee':
                col_fee = col_fee_market
                # 如果没找到"市场费"列,尝试找包含"市场费"的列(排除比率类列)
                if not col_fee:
                    for col in df.columns:
                        col_str = str(col)
                        if '市场费' in col_str and '总额' not in col_str and '合计' not in col_str \
                           and '比例' not in col_str and '比率' not in col_str and '占比' not in col_str:
                            col_fee = col
                            break
            else:  # 'market_fee_total'
                col_fee = col_fee_total
                # 如果没找到"市场费总额"列,尝试找包含"总额"或"合计"的列
                if not col_fee:
                    for col in df.columns:
                        col_str = str(col)
                        if ('总额' in col_str or '合计' in col_str) \
                           and '比例' not in col_str and '比率' not in col_str:
                            col_fee = col
                            break
            
            logger.info(f"[市场费] 列匹配: 流量方={col_flow}, 市场费={col_fee_market}, "
                       f"市场费总额={col_fee_total}, 资源费={col_fee_resource}, 车型={col_model}, 商品类别={col_category}, "
                       f"取费列(col_fee)={col_fee}")

            # 诊断:显示车型字段的唯一值(前30个)
            if col_model:
                try:
                    model_values = df[col_model].dropna().unique().tolist()
                    # 过滤空字符串
                    model_values = [str(v).strip() for v in model_values if str(v).strip()]
                    logger.info(f"[市场费诊断] Sheet '{sheet_name}': 车型字段唯一值共 {len(model_values)} 个")
                    if model_values:
                        logger.info(f"[市场费诊断] Sheet '{sheet_name}': 车型前30个值: {model_values[:30]}")
                    # 统计空值数量
                    empty_model_count = df[col_model].isna().sum() + (df[col_model].astype(str).str.strip() == '').sum() - df[col_model].isna().sum()
                    logger.info(f"[市场费诊断] Sheet '{sheet_name}': 车型空值/NaN 行数约 {empty_model_count}")
                except Exception as e:
                    logger.warning(f"[市场费诊断] Sheet '{sheet_name}' 车型诊断失败: {e}")

            if not col_fee:
                # 尝试从 df 中兜底估算该 sheet 金额(取第一个非空数值列的合计,跳过比例类列)
                try:
                    fallback_total = Decimal('0')
                    for col in df.columns:
                        col_str = str(col)
                        if any(kw in col_str for kw in ['比例', '比率', '占比', 'GMV', '产值', '数量', '台数']):
                            continue
                        vals = pd.to_numeric(df[col], errors='coerce')
                        col_sum = safe_decimal(vals.sum())
                        if col_sum != 0:
                            fallback_total = col_sum
                            break
                    if fallback_total != 0:
                        unmatched['market_fee'] += fallback_total
                        logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列,兜底估算金额={fallback_total} 累加到未匹配")
                    else:
                        logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列,且无法兜底估算金额")
                except Exception as _e:
                    logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列,兜底估算失败: {_e}")
                continue

            # Sheet 级统计
            sheet_valid_count = 0
            sheet_skipped_count = 0
            sheet_fee_total = Decimal("0")
            skip_keywords = ["合计", "汇总", "总计", "小计", "月外"]

            for row_idx, (_, row) in enumerate(df.iterrows()):
                flow_name = None
                if col_flow:
                    flow_name = row[col_flow]
                if flow_name is None or str(flow_name).strip() == "" or str(flow_name).strip() == "nan":
                    sheet_skipped_count += 1
                    # 诊断:如果是恒为门店但流量方为空,记录一下
                    continue

                flow_name = str(flow_name).strip()
                if flow_name == "":
                    sheet_skipped_count += 1
                    continue

                # 从配置获取业务类型
                biz_type = sheet_biz_type

                # 提前取费(汇总行跳过等场景也需要用 fee 累加 unmatched)
                fee = safe_decimal(row[col_fee])
                if biz_type == BIZ_TYPE_2_3 and col_fee_resource and col_fee_resource != col_fee:
                    resource_fee = safe_decimal(row[col_fee_resource])
                    fee = fee + resource_fee

                # 跳过汇总行(防止尾行公式导致双倍计算)
                if any(k in flow_name for k in skip_keywords):
                    logger.info(f"[市场费] 跳过汇总行: Sheet='{sheet_name}', flow_name='{flow_name}', fee={fee}")
                    sheet_skipped_count += 1
                    total_skipped += 1
                    if fee != 0:
                        unmatched['market_fee'] += fee
                    continue

                if fee == 0:
                    sheet_skipped_count += 1
                    continue

                total_input_fee += fee

                # 识别品牌
                brand = None
                vehicle_model = None
                if col_model:
                    vehicle_model = row[col_model]
                    brand = identify_brand(vehicle_model)
                
                # 诊断:检查未知品牌行的车型字段值
                if (brand or "未知品牌") == "未知品牌" and sheet_valid_count < 10:
                    model_str = str(vehicle_model).strip() if pd.notna(vehicle_model) else "NaN/空"
                    logger.info(f"[市场费诊断] 未知品牌行: flow={flow_name}, model_raw='{model_str}', fee={fee}, biz_type={biz_type}")

                # 诊断:针对广西恒为汽车销售服务有限公司,打印每一行
                if "广西恒为" in flow_name or "恒为" in flow_name:
                    model_str = str(vehicle_model).strip() if pd.notna(vehicle_model) else "NaN/空"
                    logger.info(f"[市场费诊断] 恒为行#{row_idx}: flow='{flow_name}', fee={fee}, model='{model_str}', brand={brand or '未知品牌'}, biz_type={biz_type}")

                # 2.3→2.1 归属规则:流量方存在 2.1 业务记录 且 商品类别=权益服务/延保-原厂权益
                if biz_type == BIZ_TYPE_2_3:
                    # 先计算标准化名称(后续也需要使用)
                    std_flow_name = to_standard(flow_name, '4s')
                    # 判断流量方是否存在 2.1 业务记录
                    has_2_1 = flow_name in has_2_1_biz or std_flow_name in has_2_1_biz
                    # 获取商品类别
                    category = str(row[col_category]).strip() if col_category and pd.notna(row[col_category]) else ""
                    # 两个条件都满足才归属到 2.1
                    if has_2_1 and category in ["权益服务", "延保-原厂权益"]:
                        biz_type = BIZ_TYPE_2_1
                        logger.info(f"[市场费][2.3→2.1归属] flow={flow_name}, category={category}, 原因=存在2.1业务记录+商品类别匹配")
                else:
                    # 使用标准名映射(非 2.3 业务时在此计算)
                    std_flow_name = to_standard(flow_name, '4s')

                result_row = {
                    "流量方名称": std_flow_name,
                    "原始名称": flow_name,
                    "业务类型": biz_type,
                    "品牌": brand or "未知品牌",
                    "市场费": fee,
                }
                all_results.append(result_row)
                sheet_valid_count += 1
                sheet_fee_total += fee

            # Sheet 级汇总日志
            logger.info(f"[市场费] Sheet '{sheet_name}' 处理完成: 有效行={sheet_valid_count}, "
                       f"跳过行={sheet_skipped_count}, 费用合计={sheet_fee_total}")

            # 诊断:显示未识别品牌的车型唯一值(帮助确认需要添加的品牌关键词)
            unknown_brand_models = {}
            for r in all_results:
                if r.get("品牌") == "未知品牌":
                    model = str(r.get("车型", "未知")).strip()
                    if model and model != "nan" and model != "None":
                        if model not in unknown_brand_models:
                            unknown_brand_models[model] = 0
                        unknown_brand_models[model] += 1
            if unknown_brand_models:
                logger.info(f"[市场费诊断] Sheet '{sheet_name}': 未识别品牌的车型共 {len(unknown_brand_models)} 种")
                for model, count in sorted(unknown_brand_models.items(), key=lambda x: -x[1])[:20]:
                    logger.info(f"[市场费诊断]   未识别车型: '{model}' 出现 {count} 次")

            # 诊断:恒为门店汇总统计(逐行汇总)
            hx_rows = [r for r in all_results if "广西恒为" in str(r.get("原始名称", "")) or "恒为" in str(r.get("原始名称", ""))]
            if hx_rows:
                logger.info(f"[市场费诊断] 恒为门店 '{sheet_name}' 汇总: 共 {len(hx_rows)} 行")
                hx_stats = {}
                for r in hx_rows:
                    brand = r.get("品牌", "未知品牌")
                    biz = r.get("业务类型", "")
                    fee = r.get("市场费", Decimal("0"))
                    key = (biz, brand)
                    if key not in hx_stats:
                        hx_stats[key] = {"count": 0, "fee_sum": Decimal("0")}
                    hx_stats[key]["count"] += 1
                    hx_stats[key]["fee_sum"] += fee
                # 按品牌分组显示
                hx_total = Decimal("0")
                for (biz, brand), stats in sorted(hx_stats.items()):
                    logger.info(f"[市场费诊断]   biz={biz}, brand={brand}, count={stats['count']}, fee_sum={stats['fee_sum']}")
                    hx_total += stats["fee_sum"]
                logger.info(f"[市场费诊断]   恒为门店总计: {hx_total}")

            # 诊断:对比 Excel 原始金额与解析金额(检测是否有行被静默丢弃)
            # 注意:pandas read_excel 会读取所有行(包括隐藏行),如果 Excel 中使用了筛选器或隐藏行,
            # 代码解析的金额可能与 Excel 界面显示的金额不同
            if col_fee:
                try:
                    excel_raw_sum = safe_decimal(df[col_fee].sum())
                    logger.info(f"[市场费诊断] Sheet '{sheet_name}': Excel原始总额={excel_raw_sum}, "
                               f"解析有效行总额={sheet_fee_total}, 解析跳过行={sheet_skipped_count}")
                    
                    # 诊断:按流量方分组统计,帮助识别异常数据
                    if sheet_valid_count > 0:
                        flow_stats = {}
                        unknown_brand_count = 0
                        unknown_brand_fee = Decimal("0")
                        for r in all_results:
                            flow_name = r.get("流量方名称", "未知")
                            biz_type = r.get("业务类型", "未知")
                            brand = r.get("品牌", "未知")
                            fee_val = r.get("市场费", Decimal("0"))
                            key = (flow_name, biz_type, brand)
                            if key not in flow_stats:
                                flow_stats[key] = {"count": 0, "fee_sum": Decimal("0")}
                            flow_stats[key]["count"] += 1
                            flow_stats[key]["fee_sum"] += fee_val
                            
                            # 统计未知品牌
                            if brand == "未知品牌":
                                unknown_brand_count += 1
                                unknown_brand_fee += fee_val
                        
                        # 显示未知品牌统计
                        logger.info(f"[市场费诊断] Sheet '{sheet_name}': 未知品牌行={unknown_brand_count}条, 金额={unknown_brand_fee}")
                        
                        # 按金额排序,显示前30个流量方
                        sorted_flows = sorted(flow_stats.items(), key=lambda x: float(x[1]["fee_sum"]), reverse=True)
                        logger.info(f"[市场费诊断] Sheet '{sheet_name}': 共 {len(flow_stats)} 个不同流量方+业务类型+品牌组合")
                        logger.info(f"[市场费诊断] Sheet '{sheet_name}': 金额最大前30组:")
                        for i, ((flow, biz, brand), stats) in enumerate(sorted_flows[:30], 1):
                            logger.info(f"[市场费诊断]   {i}. flow={flow}, biz={biz}, brand={brand}, count={stats['count']}, fee_sum={stats['fee_sum']}")
                        
                        # 显示异常检测:单行金额大于1000的记录
                        high_value_rows = [(r["流量方名称"], r["市场费"]) for r in all_results if r.get("市场费", Decimal("0")) > Decimal("1000")]
                        if high_value_rows:
                            logger.info(f"[市场费诊断] Sheet '{sheet_name}': 高价值行(>1000)共 {len(high_value_rows)} 条")
                            # 显示最高的10条
                            high_value_sorted = sorted(high_value_rows, key=lambda x: float(x[1]), reverse=True)[:10]
                            for i, (flow, fee) in enumerate(high_value_sorted, 1):
                                logger.info(f"[市场费诊断]   高价值{i}. flow={flow}, fee={fee}")
                except Exception as e:
                    logger.warning(f"[市场费诊断] Sheet '{sheet_name}' 诊断失败: {e}")

        if not all_results:
            logger.info("[市场费] 无有效数据")
            return [], unmatched

        # 总量日志
        total_fee = sum(r["市场费"] for r in all_results)
        logger.info(f"[市场费] 汇总: 共 {len(all_results)} 条记录, 跳过 {total_skipped} 行, 总费用={total_fee}")

        # 使用 GMV 分摊进行品牌费用分配
        logger.info(f"[市场费] 原始记录 {len(all_results)} 条,开始 GMV 分摊...")
        result = self._allocate_market_fee_by_gmv(all_results, settlement_map)

        # 总量校验
        matched_sum = sum(r["市场费"] for r in result)
        unmatched_amount = total_input_fee - matched_sum

        # 按 biz_type 分别统计未匹配
        biz_input = defaultdict(Decimal)
        for r in all_results:
            biz_input[r["业务类型"]] += r["市场费"]
        biz_matched = defaultdict(Decimal)
        for r in result:
            biz_matched[r["业务类型"]] += r["市场费"]

        # 按 biz_type 分别存 unmatched
        for biz in [BIZ_TYPE_1_1, BIZ_TYPE_2_1, BIZ_TYPE_2_3]:
            z = biz_input.get(biz, Decimal("0")) - biz_matched.get(biz, Decimal("0"))
            unmatched[f'market_fee_{biz}'] = unmatched.get(f'market_fee_{biz}', Decimal("0")) + z

        # 未匹配合计
        unmatched['market_fee'] = unmatched.get('market_fee', Decimal("0")) + unmatched_amount

        logger.info(f"[市场费][未匹配汇总] 总额={total_input_fee} 已匹配={matched_sum} 未匹配合计={unmatched_amount}")
        for biz in [BIZ_TYPE_1_1, BIZ_TYPE_2_1, BIZ_TYPE_2_3]:
            z = unmatched.get(f'market_fee_{biz}', Decimal("0"))
            if biz_input.get(biz, Decimal("0")) > 0 or z != 0:
                logger.info(f"  biz={biz}: 输入={biz_input.get(biz, Decimal('0'))}, "
                            f"已匹配={biz_matched.get(biz, Decimal('0'))}, 未匹配={z}")

        logger.info(f"[市场费] 解析完成,共 {len(result)} 条汇总记录")
        return result, unmatched

    # ========================================================
    # 解析外援施工费表
    # ========================================================

    def _parse_external_worker_fee(self, file_path, settlement_map=None, flow_ratio_entries=None):
        """
        解析外援施工费表。
        规则:
          - 仅1.1业务统计,其他业务类型默认=0
          - 读取 Sheet "按门店名称汇总"
          - 按"流量来源"匹配流量方名称
        返回:Dict[(流量方名称, 业务类型), Decimal],按(流量方,业务类型)聚合的总金额
        """
        logger.info(f"[外援施工费] 解析文件: {file_path}")

        if not os.path.exists(file_path):
            logger.warning(f"[外援施工费] 文件不存在: {file_path}")
            return {}, {'external_construction': Decimal('0')}

        unmatched = {'external_construction': Decimal('0')}
        total_input_fee = Decimal('0')

        xls = pd.ExcelFile(file_path)
        logger.info(f"[外援施工费] 所有 Sheet: {xls.sheet_names}")

        # 查找 "按门店名称汇总" Sheet
        target_sheet = None
        for name in xls.sheet_names:
            if "按门店" in name or "门店名称汇总" in name:
                target_sheet = name
                break

        if not target_sheet:
            target_sheet = xls.sheet_names[0]
            logger.warning(f"[外援施工费] 未找到'按门店名称汇总'Sheet,使用第一个: {target_sheet}")
        else:
            logger.info(f"[外援施工费] 读取 Sheet: {target_sheet}")

        # 扫描前 5 行,查找包含"流量来源"的行作为表头行
        df_raw = pd.read_excel(file_path, sheet_name=target_sheet, header=None)
        header_row = 0
        for i in range(min(5, len(df_raw))):
            row_text = " ".join(str(v) for v in df_raw.iloc[i].tolist() if pd.notna(v))
            if "流量来源" in row_text:
                header_row = i
                logger.info(f"[外援施工费] 表头行: 第{i}行")
                break

        # 用检测到的表头行读取
        df = pd.read_excel(file_path, sheet_name=target_sheet, header=header_row)
        df.columns = [str(col).strip() for col in df.columns]
        logger.info(f"[外援施工费] 列名: {list(df.columns)}")
        logger.info(f"[外援施工费] 数据行数: {len(df)}")

        # 匹配列
        col_source = find_column(df, "流量来源")
        col_total = find_column(df, "总计")
        logger.info(f"[外援施工费] 列匹配: 流量来源={col_source}, 总计={col_total}")

        if not col_source or not col_total:
            logger.warning(f"[外援施工费] 列匹配失败,所有列: {list(df.columns)}")
            return {}, unmatched

        # 按 (流量方, 业务类型) 聚合总金额
        result = {}
        for _, row in df.iterrows():
            flow_source = row[col_source]
            if flow_source is None or pd.isna(flow_source) or str(flow_source).strip() == "":
                continue

            flow_source = str(flow_source).strip()
            fee = safe_decimal(row[col_total])

            # 跳过汇总行
            if any(k in flow_source for k in ["合计", "汇总", "总计", "月外"]):
                unmatched['external_construction'] += fee
                continue

            # 使用标准名映射
            std_source = to_standard(flow_source, '4s')

            if fee == 0:
                continue

            total_input_fee += fee
            key = (std_source, BIZ_TYPE_1_1)
            result[key] = result.get(key, Decimal("0")) + fee

        if not result:
            logger.info("[外援施工费] 无有效数据")
            return {}, unmatched

        total_amount = sum(result.values())
        matched_sum = total_amount
        unmatched_amount = total_input_fee - matched_sum
        unmatched['external_construction'] += unmatched_amount
        logger.info(f"[外援施工费][未匹配汇总] external_construction: 总额={total_input_fee} 已匹配={matched_sum} 未匹配={unmatched['external_construction']}")
        logger.info(f"[外援施工费] 解析完成: {len(result)} 个key, 总金额={total_amount}")
        # 打印前3条预览
        for i, (k, v) in enumerate(result.items()):
            if i >= 3:
                break
            logger.info(f"[外援施工费] 预览[{i}]: flow={k[0]}, biz={k[1]}, fee={v}")
        return result, unmatched

    # ========================================================
    # 解析人力成本表
    # ========================================================

    def _parse_labor_cost(self, file_path, settlement_map=None, park_ratio_map=None, park_rows_data=None, flow_ratio_entries=None, task_id=None, stat_month=None, db=None):
        """
        解析人力成本表(简化版)。
        规则:
          - 仅检核=TRUE的行参与计算
          - 1.1业务:岗位=贴膜技师→技师工资;其他→营销团队工资
          - 2.1/2.3业务:全部→营销团队工资
          - 匹配策略:先用"入驻门店"直接匹配流量方名称
          - 回退策略:匹配失败时用"入驻门店"匹配园区店名
          - 2.1/2.3 归属规则:同一门店若 DB 结果表只存在 2.1 或只存在 2.3,
            则 Excel 里该门店的所有工资(不论写 2.1 还是 2.3)统一归属到 DB 实际存在的那个业务
        返回:Dict[(流量方名称, 业务类型), {"技师工资": Decimal, "营销团队工资": Decimal}]
        """
        logger.info(f"[人力成本] 解析文件: {file_path}")

        if not os.path.exists(file_path):
            logger.warning(f"[人力成本] 文件不存在: {file_path}")
            return {}, {'technician_salary': Decimal('0'), 'marketing_team_salary': Decimal('0')}

        if settlement_map is None:
            settlement_map = {}

        unmatched = {'technician_salary': Decimal('0'), 'marketing_team_salary': Decimal('0')}
        total_input_tech = Decimal('0')
        total_input_mkt = Decimal('0')

        # 构建流量方名称集合和映射
        flow_names_set = set()
        std_to_original_flow = {}
        if settlement_map:
            for (fn, bt, br) in settlement_map.keys():
                flow_names_set.add(fn)
                std_name = to_standard(fn, '4s')
                std_to_original_flow[std_name] = fn
                flow_names_set.add(std_name)

        # 从 flow_ratio_entries 获取 park_to_flows 映射
        park_to_flows = defaultdict(list)
        if flow_ratio_entries:
            for (flow_name, biz_type), entries in flow_ratio_entries.items():
                std_flow = to_standard(flow_name, '4s')
                for brand, ps_raw, gmv_ratio, gmv_ratio_park in entries:
                    if ps_raw:
                        park_to_flows[ps_raw].append((flow_name, biz_type))
                        ps_std = to_standard(ps_raw, 'yq')
                        if ps_std != ps_raw:
                            park_to_flows[ps_std].append((flow_name, biz_type))

        # 构建 park_rows 索引(用于 gmv_ratio_park 分摊)
        # 只保留 service_provider 含"嘀加"的 entries(分摊分母口径)
        # settlement_map 里每个 (flow_name, biz_type, brand) 存了服务商字段
        def _is_dijia_flow(flow_name, biz_type, brand=None):
            """判断 settlement_map 中该 key 的服务商是否含"嘀加"(嘀加自营/嘀加直营)。"""
            if brand is not None:
                sp = (settlement_map.get((flow_name, biz_type, brand), {}).get("服务商") or "").strip()
                return "嘀加" in sp
            # brand=None → 查该 (flow, biz) 任意 brand 有嘀加就算
            for (fn, bt, br), data in settlement_map.items():
                if fn == flow_name and bt == biz_type and "嘀加" in (data.get("服务商") or ""):
                    return True
            return False

        park_rows = defaultdict(list)
        if flow_ratio_entries:
            for (flow_name, biz_type), entries in flow_ratio_entries.items():
                for brand, ps_raw, gmv_ratio, gmv_ratio_park in entries:
                    if ps_raw and _is_dijia_flow(flow_name, biz_type, brand):
                        park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
                        ps_std = to_standard(ps_raw, 'yq')
                        if ps_std != ps_raw:
                            park_rows[(ps_std, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
        if not park_rows and settlement_map:
            for (flow_name, biz_type, brand), data in settlement_map.items():
                sp = (data.get("服务商") or "").strip()
                if "嘀加" not in sp:
                    continue
                ps_raw = data.get("park_store_raw", "")
                gmv_ratio = data.get("gmv_ratio")
                gmv_ratio_park = data.get("gmv_ratio_park")
                if ps_raw:
                    park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
                    ps_std = to_standard(ps_raw, 'yq')
                    if ps_std != ps_raw:
                        park_rows[(ps_std, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))

        logger.info(f"[人力成本] park_rows 构建(仅嘀加服务商): {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合")

        if not park_to_flows and settlement_map:
            for (flow_name, biz_type, brand), data in settlement_map.items():
                ps_raw = data.get("park_store_raw", "")
                if ps_raw:
                    park_to_flows[ps_raw].append((flow_name, biz_type))

        # 解密并读取 Excel
        actual_path, is_decrypted = decrypt_excel_if_needed(file_path)
        try:
            xls = pd.ExcelFile(actual_path)
        except Exception as e:
            logger.error(f"[人力成本] 读取失败: {e}")
            if is_decrypted and actual_path != file_path and os.path.exists(actual_path):
                os.unlink(actual_path)
            return {}, unmatched

        # 聚合桶
        result = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
        total_input_salary = Decimal("0")
        row_count = 0
        check_passed = 0
        check_skipped = 0
        failed_match_count = 0
        # 诊断:收集完全未匹配的门店
        _unmatched_stores = defaultdict(lambda: {"tech": Decimal("0"), "mkt": Decimal("0"), "rows": 0})

        try:
            sheet_name = xls.sheet_names[0]
            logger.info(f"[人力成本] 读取第一个 Sheet: {sheet_name}")
            df_raw = pd.read_excel(actual_path, sheet_name=sheet_name, header=None)
            header_row, title_rows = detect_header_row(df_raw)
            df = pd.read_excel(actual_path, sheet_name=sheet_name, header=header_row)
            df.columns = [str(col).strip() for col in df.columns]

            # 查找关键列
            col_store = find_column(df, "入驻门店")
            col_biz = find_column(df, "人员业务归属")
            col_position = find_column(df, "岗位")
            col_salary = find_column(df, "个人本店分摊薪资")

            # 检核列
            col_check = None
            if len(df.columns) > 31:
                col_check = df.columns[31]
            else:
                col_check_af = find_column(df, "检核业务线")
                if col_check_af:
                    col_check = col_check_af
                if col_check is None:
                    col_check = find_column(df, "检核", "审核")

            logger.info(f"[人力成本] 列匹配: 门店={col_store}, 业务归属={col_biz}, 岗位={col_position}, 薪资={col_salary}, 检核={col_check}")

            # --- 归属规则预加载:查 DB 中每个门店实际存在哪些 business_type(2.1/2.3) ---
            # 用于后续将 Excel 里 2.1/2.3 的工资行归属到 DB 实际存在的业务
            store_biz_map = {}   # {store_name: set(biz_types)}
            if task_id and stat_month and db:
                try:
                    all_store_names = set()
                    if col_store:
                        for sn in df[col_store].dropna():
                            sn_s = str(sn).strip()
                            if sn_s and sn_s != "nan":
                                all_store_names.add(sn_s)
                    if all_store_names:
                        from sqlalchemy import text as sa_text
                        in_clause = ",".join(f":s{i}" for i in range(len(all_store_names)))
                        sql_biz = sa_text(f"""
                            SELECT DISTINCT traffic_name, park_store, business_type
                            FROM biz_budget_achieve
                            WHERE task_id = :tid AND stat_month = :sm
                              AND business_type IN ('2.1', '2.3')
                              AND (traffic_name IN ({in_clause}) OR park_store IN ({in_clause}))
                        """)
                        params = {"tid": task_id, "sm": stat_month}
                        for i, sn in enumerate(all_store_names):
                            params[f"s{i}"] = sn
                        rows_biz = db.session.execute(sql_biz, params).fetchall()
                        # 用 set 存 (traffic_name, park_store) → biz_type 映射
                        for tn, ps, bt in rows_biz:
                            if tn:
                                store_biz_map.setdefault(tn, set()).add(bt)
                            if ps:
                                store_biz_map.setdefault(ps, set()).add(bt)
                        if store_biz_map:
                            logger.info(f"[人力成本归属] 预加载 {len(store_biz_map)} 个门店的 DB 业务类型"
                                        f"(2.1/2.3)映射,用于归属纠正")
                except Exception as e_map:
                    logger.warning(f"[人力成本归属] 预加载 DB 业务类型失败: {e_map},归属纠正跳过")
                    store_biz_map = {}

            def _resolve_biz_by_store(sn, cur_biz):
                """归属规则:若 DB 中该门店只有 2.1 或只有 2.3,纠正 cur_biz 为 DB 存在的那个。
                其他情况(DB 两个都有、都没有、Excel 不是 2.1/2.3)原样返回。
                """
                if cur_biz not in (BIZ_TYPE_2_1, BIZ_TYPE_2_3):
                    return cur_biz
                real = store_biz_map.get(sn)
                if not real or len(real) != 1:
                    return cur_biz
                only_bt = next(iter(real))
                if only_bt != cur_biz:
                    logger.info(f"[规则1命中] 门店='{sn}', Excel biz={cur_biz}, DB 只有={only_bt} → 纠正为={only_bt}")
                    return only_bt
                return cur_biz

            for _, row in df.iterrows():
                # 检核列筛选
                if col_check:
                    check_val = row[col_check]
                    if pd.isna(check_val):
                        check_skipped += 1
                        continue
                    check_str = str(check_val).strip().upper()
                    if check_str not in ["TRUE", "1", "1.0", "Y", "YES"]:
                        check_skipped += 1
                        continue
                    check_passed += 1

                store_name = None
                if col_store:
                    store_name = row[col_store]
                if store_name is None or str(store_name).strip() == "" or str(store_name).strip() == "nan":
                    continue

                store_name = str(store_name).strip()
                std_store_name = to_standard(store_name, '4s')

                # 获取业务类型
                biz_type = None
                if col_biz:
                    biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
                    if "1.1" in biz_val or "贴膜" in biz_val:
                        biz_type = BIZ_TYPE_1_1
                    elif "2.1" in biz_val:
                        biz_type = BIZ_TYPE_2_1
                    elif "2.3" in biz_val:
                        biz_type = BIZ_TYPE_2_3

                # --- biz_type 兜底:空值时从 park_to_flows 推导或默认 1.1 ---
                if not biz_type:
                    ps_candidates = [store_name, to_standard(store_name, 'yq')]
                    for ps in ps_candidates:
                        if ps in park_to_flows:
                            biz_set = set(fb for _, fb in park_to_flows[ps])
                            if len(biz_set) == 1:
                                biz_type = list(biz_set)[0]
                                break
                    if not biz_type:
                        biz_type = BIZ_TYPE_1_1  # 最后兜底:贴膜技师通常归 1.1
                        logger.warning(f"[人力成本] biz_type 未知, 兜底为 1.1: store='{store_name}'")

                # --- 归属纠正(2.1/2.3 规则) ---
                if biz_type:
                    biz_type = _resolve_biz_by_store(store_name, biz_type)
                    if std_store_name != store_name:
                        # 也尝试标准化后的 store 名
                        biz_type = _resolve_biz_by_store(std_store_name, biz_type)

                # 获取岗位
                position = None
                if col_position:
                    position = str(row[col_position]).strip() if pd.notna(row[col_position]) else ""

                # 获取薪资
                salary = Decimal("0")
                if col_salary:
                    salary = safe_decimal(row[col_salary])
                if salary == 0:
                    continue

                # 岗位分类
                technician_salary = Decimal("0")
                marketing_salary = Decimal("0")

                if biz_type == BIZ_TYPE_1_1:
                    if position and "贴膜技师" in position:
                        technician_salary = salary
                    else:
                        marketing_salary = salary
                elif biz_type in [BIZ_TYPE_2_1, BIZ_TYPE_2_3]:
                    marketing_salary = salary
                else:
                    marketing_salary = salary

                total_input_salary += salary
                total_input_tech += technician_salary
                total_input_mkt += marketing_salary
                row_count += 1

                # 优先检查是否为园区店
                in_park_to_flows = store_name in park_to_flows
                std_in_park_to_flows = to_standard(store_name, 'yq') in park_to_flows

                if in_park_to_flows or std_in_park_to_flows:
                    # 园区店回退:找到关联的流量方(全部 flow,不做服务商过滤)
                    ps = store_name if in_park_to_flows else to_standard(store_name, 'yq')
                    related_flows = park_to_flows.get(ps, [])
                    # 优先用 Excel 的 biz_type 匹配;匹配不到就用所有关联 flow(各自带自己的真实 biz_type)
                    matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type]
                    use_flow_own_biz = False
                    if not matching_flows:
                        matching_flows = related_flows  # 回退:使用所有关联流量方
                        use_flow_own_biz = True  # 每个 flow 用自己的 DB biz_type

                    if matching_flows:
                        # 优先使用 gmv_ratio_park 分摊
                        # park_ratio_rows 也需要根据是否用 flow 自身 biz_type 来取
                        pr_key_biz = None if use_flow_own_biz else biz_type
                        park_ratio_rows = park_rows.get((ps, pr_key_biz), []) if pr_key_biz else []
                        if not park_ratio_rows and related_flows:
                            # 收集该园区店所有 biz_type 的 park_ratio_rows
                            all_biz = set(fb for _, fb in related_flows)
                            for ab in all_biz:
                                park_ratio_rows.extend(park_rows.get((ps, ab), []))
                        if park_ratio_rows:
                            raw_ratios = []
                            for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows:
                                # 从 matching_flows 里找该 flow 的真实 biz_type
                                real_biz = None
                                for fn, fb in matching_flows:
                                    if fn == flow_name:
                                        real_biz = fb
                                        break
                                if not real_biz:
                                    continue
                                if gmv_ratio_park is not None:
                                    r = Decimal(str(gmv_ratio_park))
                                    ratio_type = "gmv_ratio_park"
                                elif gmv_ratio is not None:
                                    r = Decimal(str(gmv_ratio))
                                    ratio_type = "gmv_ratio(回退)"
                                else:
                                    continue
                                raw_ratios.append((flow_name, brand, r, ratio_type, real_biz))
                            total_r = sum(r for _, _, r, _, _ in raw_ratios)
                            if total_r > 0:
                                for flow_name, brand, r, ratio_type, real_biz in raw_ratios:
                                    normalized_r = r / total_r
                                    result[(flow_name, real_biz)]["技师工资"] += technician_salary * normalized_r
                                    result[(flow_name, real_biz)]["营销团队工资"] += marketing_salary * normalized_r
                                logger.info(f"[规则3命中·园区店分摊] ps='{ps}', matching_flows={len(matching_flows)}, "
                                            f"有效比例行={len(raw_ratios)}, 分母sum_r={total_r:.4f}, "
                                            f"tech={technician_salary}, mkt={marketing_salary}, ratio_type={ratio_type}")
                            else:
                                flow_count = len(matching_flows)
                                for flow_name, real_biz in matching_flows:
                                    key = (flow_name, real_biz)
                                    result[key]["技师工资"] += technician_salary / flow_count
                                    result[key]["营销团队工资"] += marketing_salary / flow_count
                                logger.info(f"[规则3命中·园区店平均回退] ps='{ps}', flows={flow_count}, use_flow_own_biz={use_flow_own_biz}")
                        else:
                            flow_count = len(matching_flows)
                            for flow_name, real_biz in matching_flows:
                                key = (flow_name, real_biz)
                                result[key]["技师工资"] += technician_salary / flow_count
                                result[key]["营销团队工资"] += marketing_salary / flow_count
                            logger.info(f"[规则3命中·无park_ratio平均回退] ps='{ps}', flows={flow_count}, use_flow_own_biz={use_flow_own_biz}")
                    else:
                        failed_match_count += 1
                        _us = _unmatched_stores[store_name]
                        _us["tech"] += technician_salary
                        _us["mkt"] += marketing_salary
                        _us["rows"] += 1
                    continue

                # 直接匹配:检查是否为流量方(不做服务商过滤,非嘀加 flow 也正常拿工资)
                if std_store_name in flow_names_set:
                    original_flow = std_to_original_flow.get(std_store_name, std_store_name)
                    key = (original_flow, biz_type)
                    result[key]["技师工资"] += technician_salary
                    result[key]["营销团队工资"] += marketing_salary
                else:
                    # 尝试模糊匹配园区店
                    ps_std = to_standard(store_name, 'yq')
                    if ps_std in park_to_flows:
                        related_flows = park_to_flows[ps_std]
                        matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type]
                        use_flow_own_biz = False
                        if not matching_flows:
                            matching_flows = related_flows
                            use_flow_own_biz = True
                        if matching_flows:
                            pr_key_biz = None if use_flow_own_biz else biz_type
                            park_ratio_rows = park_rows.get((ps_std, pr_key_biz), []) if pr_key_biz else []
                            if not park_ratio_rows and related_flows:
                                all_biz = set(fb for _, fb in related_flows)
                                for ab in all_biz:
                                    park_ratio_rows.extend(park_rows.get((ps_std, ab), []))
                            if park_ratio_rows:
                                raw_ratios = []
                                for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows:
                                    real_biz = None
                                    for fn, fb in matching_flows:
                                        if fn == flow_name:
                                            real_biz = fb
                                            break
                                    if not real_biz:
                                        continue
                                    if gmv_ratio_park is not None:
                                        r = Decimal(str(gmv_ratio_park))
                                        ratio_type = "gmv_ratio_park"
                                    elif gmv_ratio is not None:
                                        r = Decimal(str(gmv_ratio))
                                        ratio_type = "gmv_ratio(回退)"
                                    else:
                                        continue
                                    raw_ratios.append((flow_name, brand, r, ratio_type, real_biz))
                                total_r = sum(r for _, _, r, _, _ in raw_ratios)
                                if total_r > 0:
                                    for flow_name, brand, r, ratio_type, real_biz in raw_ratios:
                                        normalized_r = r / total_r
                                        result[(flow_name, real_biz)]["技师工资"] += technician_salary * normalized_r
                                        result[(flow_name, real_biz)]["营销团队工资"] += marketing_salary * normalized_r
                                    logger.info(f"[人力成本] 园区店模糊分摊({ratio_type}·归一化): ps='{ps_std}', {len(raw_ratios)}行, sum_r={total_r:.4f}")
                                else:
                                    flow_count = len(matching_flows)
                                    for flow_name, real_biz in matching_flows:
                                        key = (flow_name, real_biz)
                                        result[key]["技师工资"] += technician_salary / flow_count
                                        result[key]["营销团队工资"] += marketing_salary / flow_count
                            else:
                                flow_count = len(matching_flows)
                                for flow_name, real_biz in matching_flows:
                                    key = (flow_name, real_biz)
                                    result[key]["技师工资"] += technician_salary / flow_count
                                    result[key]["营销团队工资"] += marketing_salary / flow_count
                                logger.info(f"[人力成本] 园区店模糊分摊(平均回退): ps='{ps_std}', flows={flow_count}, use_flow_own_biz={use_flow_own_biz}")
                        else:
                            failed_match_count += 1
                            _us = _unmatched_stores[store_name + "(park有关联但没匹配到biz_type)"]
                            _us["tech"] += technician_salary
                            _us["mkt"] += marketing_salary
                            _us["rows"] += 1
                    else:
                        failed_match_count += 1
                        _us = _unmatched_stores[store_name + "(flow和park_store都不匹配)"]
                        _us["tech"] += technician_salary
                        _us["mkt"] += marketing_salary
                        _us["rows"] += 1

        finally:
            if is_decrypted and actual_path != file_path and os.path.exists(actual_path):
                os.unlink(actual_path)

        # 检核过滤统计日志
        logger.info(f"[人力成本] 检核过滤: 总行数={len(df)}, 通过={check_passed}, 过滤掉={check_skipped}")
        logger.info(f"[人力成本] 解析完成: {row_count} 行有效, 总输入薪资={total_input_salary}")
        logger.info(f"[人力成本] 聚合结果: {len(result)} 个key, 匹配失败={failed_match_count}")
        
        # ===== 诊断:打印所有未匹配门店明细 =====
        if _unmatched_stores:
            total_um_tech = sum(v["tech"] for v in _unmatched_stores.values())
            total_um_mkt = sum(v["mkt"] for v in _unmatched_stores.values())
            logger.warning(f"[人力成本-诊断] 未匹配门店共 {len(_unmatched_stores)} 个, 合计 tech={total_um_tech}, mkt={total_um_mkt}")
            for store, info in sorted(_unmatched_stores.items(), key=lambda x: float(x[1]["tech"] + x[1]["mkt"]), reverse=True)[:30]:
                logger.warning(f"  未匹配: 门店='{store}', tech={info['tech']}, mkt={info['mkt']}, 行数={info['rows']}")

        if not result:
            logger.info("[人力成本] 无有效数据(无嘀加流量方匹配成功)")
            # 全部进 unmatched
            unmatched['technician_salary'] += total_input_tech
            unmatched['marketing_team_salary'] += total_input_mkt
            return {}, unmatched

        # 总量校验
        total_output = sum(v["技师工资"] + v["营销团队工资"] for v in result.values())
        total_output_tech = sum(v["技师工资"] for v in result.values())
        total_output_mkt = sum(v["营销团队工资"] for v in result.values())
        logger.info(f"[人力成本] 总量校验: 输入={total_input_salary}, 输出={total_output}, 差值={total_input_salary - total_output}")

        # 用总量守恒补全未匹配(精确匹配分摊后的微小差值也计入 unmatched)
        tech_unmatched_from_conservation = total_input_tech - total_output_tech
        mkt_unmatched_from_conservation = total_input_mkt - total_output_mkt
        unmatched['technician_salary'] += tech_unmatched_from_conservation
        unmatched['marketing_team_salary'] += mkt_unmatched_from_conservation
        logger.info(f"[人力成本][未匹配汇总] technician_salary: 输入={total_input_tech} 已匹配={total_output_tech} 未匹配={unmatched['technician_salary']}")
        logger.info(f"[人力成本][未匹配汇总] marketing_team_salary: 输入={total_input_mkt} 已匹配={total_output_mkt} 未匹配={unmatched['marketing_team_salary']}")

        # 预览前3条
        for i, (k, v) in enumerate(result.items()):
            if i >= 3:
                break
            logger.info(f"[人力成本] 预览[{i}]: flow={k[0]}, biz={k[1]}, tech={v['技师工资']}, mkt={v['营销团队工资']}")

        return result, unmatched

    # ========================================================
    # 解析房租水电施工费表
    # ========================================================

    def _parse_utility_fee(self, file_path, settlement_map=None, park_ratio_map=None, park_rows_data=None, flow_ratio_entries=None, task_id=None):
        """
        解析房租水电施工费表。
        规则:
          - 仅1.1业务统计
          - 按"分账对象"匹配"流量方名称"
          - 取"房租费用+水电费+施工费用"合计
          - 回退策略:匹配失败时按"分账对象"匹配"园区店"
          - 多条记录按GMV分摊
          - 支持多对象GMV分摊(task_id提供时启用)
        返回:List[dict],每行 {流量方名称, 业务类型, 房租及水电费}
        """
        logger.info(f"[房租水电] 解析文件: {file_path}")

        if not os.path.exists(file_path):
            logger.warning(f"[房租水电] 文件不存在: {file_path}")
            return [], [], {'rent_utilities': Decimal('0')}

        if settlement_map is None:
            settlement_map = {}
        
        if flow_ratio_entries is None:
            flow_ratio_entries = {}

        unmatched = {'rent_utilities': Decimal('0')}
        skip_reasons = defaultdict(lambda: Decimal('0'))   # 追踪每条 continue 跳过路径的金额(用于诊断漏记)

        # 构建索引
        flow_names_set = set()
        flow_ratios = defaultdict(list)
        park_rows = defaultdict(list)
        park_to_flows = defaultdict(list)  # 从 park_rows_data 直接构建

        # 优先使用独立查询的 park_rows_data(使用原始 park_store 值)
        # 只保留 service_provider 含"嘀加"的记录(分摊口径统一)
        def _is_dijia_flow(flow_name, biz_type, brand=None):
            """从 settlement_map 查服务商是否含"嘀加"(嘀加自营/嘀加直营)。"""
            if brand is not None:
                return "嘀加" in (settlement_map.get((flow_name, biz_type, brand), {}).get("服务商") or "")
            # brand=None → 任意 brand 有嘀加就算
            for (fn, bt, br), data in settlement_map.items():
                if fn == flow_name and bt == biz_type and "嘀加" in (data.get("服务商") or ""):
                    return True
            return False

        if park_rows_data:
            # ========== 第 1 步:先构建完整的 park_to_flows 查找索引(不过滤服务商) ==========
            # park_to_flows 是 Excel 门店名 → DB 流量方列表的查找表,
            # 必须包含所有门店(不管服务商是什么),否则 Excel 里非嘀加/无品牌门店找不到匹配目标 → 费用丢失
            for record in park_rows_data:
                try:
                    if len(record) >= 4:
                        flow_name, bt, brand, ps_raw = record[0], record[1], record[2], record[3]
                    else:
                        continue
                    if ps_raw and bt:
                        park_to_flows[ps_raw].append((flow_name, bt))
                        ps_std = to_standard(ps_raw, 'yq')
                        if ps_std != ps_raw:
                            park_to_flows[ps_std].append((flow_name, bt))
                except Exception as e:
                    logger.error(f"[房租水电][诊断] park_to_flows 构建失败: {e}")

            # ========== 第 2 步:再构建过滤后的 park_rows(GMV 分母池) ==========
            # park_rows 用于 gmv_ratio_park 分摊的分母池计算 —— 这里只保留嘀加服务商
            for i, record in enumerate(park_rows_data):
                try:
                    # 支持5/6/7元素三种格式
                    if len(record) == 7:
                        flow_name, bt, brand, ps_raw, gmv_ratio_park, gmv_ratio, ps_std = record
                    elif len(record) == 6:
                        flow_name, bt, brand, ps_raw, gmv_ratio_park, gmv_ratio = record
                        ps_std = to_standard(ps_raw, 'yq') if ps_raw else ""
                    elif len(record) == 5:
                        flow_name, bt, brand, ps_raw, gmv_ratio_park = record
                        gmv_ratio = None
                        ps_std = to_standard(ps_raw, 'yq') if ps_raw else ""
                    else:
                        continue

                    if not _is_dijia_flow(flow_name, bt, brand):
                        continue

                    if ps_raw and bt:
                        park_rows[(ps_raw, bt)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
                except Exception as e:
                    logger.error(f"[房租水电][诊断] park_rows_data[{i}] 处理失败: {e}")
        else:
            # 回退:从 settlement_map 聚合 —— 同时构建完整 park_to_flows + 过滤后 park_rows
            for (flow_name, biz_type, brand), data in settlement_map.items():
                ps_raw = data.get("park_store_raw", "")
                if not ps_raw:
                    continue
                # park_to_flows 查找索引:不加过滤
                park_to_flows[ps_raw].append((flow_name, biz_type))
                ps_std = to_standard(ps_raw, 'yq')
                if ps_std != ps_raw:
                    park_to_flows[ps_std].append((flow_name, biz_type))
                # park_rows 分母池:只保留嘀加
                if "嘀加" in (data.get("服务商") or ""):
                    gmv_ratio_park = data.get("gmv_ratio_park")
                    gmv_ratio = data.get("gmv_ratio")
                    if gmv_ratio_park is not None or gmv_ratio is not None:
                        park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))

        logger.info(f"[房租水电] park_rows 构建(仅嘀加服务商): {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合")
        logger.info(f"[房租水电] park_to_flows 完整索引(所有服务商): {len(park_to_flows)} 个园区店")

        # 优先使用 flow_ratio_entries 构建流量方索引(保留所有 park_store 的比例值)
        # 这是关键修复:避免同一 (flow, biz_type, brand) 下不同 park_store 的比例被覆盖
        if flow_ratio_entries:
            logger.info(f"[房租水电] 使用 flow_ratio_entries 构建流量方索引: {len(flow_ratio_entries)} 个 key")
            for (flow_name, biz_type), entries in flow_ratio_entries.items():
                flow_names_set.add(flow_name)
                std_flow = to_standard(flow_name, '4s')
                for brand, ps_raw, gmv_ratio, gmv_ratio_park in entries:
                    flow_ratios[(std_flow, biz_type)].append((brand, gmv_ratio, gmv_ratio_park, ps_raw))
        else:
            # 回退:从 settlement_map 构建(兼容旧逻辑)
            logger.info("[房租水电] flow_ratio_entries 为空,从 settlement_map 构建流量方索引")
            for (flow_name, biz_type, brand), data in settlement_map.items():
                flow_names_set.add(flow_name)
                std_flow = to_standard(flow_name, '4s')
                gmv_ratio = data.get("gmv_ratio")
                gmv_ratio_park = data.get("gmv_ratio_park")
                flow_ratios[(std_flow, biz_type)].append((brand, gmv_ratio, gmv_ratio_park, data.get("park_store_raw", "")))

        logger.info(f"[房租水电] settlement_map 索引: {len(flow_names_set)} 个流量方, {len(park_to_flows)} 个园区店, "
                    f"flow_ratios={len(flow_ratios)}, park_rows={len(park_rows)}")
        if flow_ratios:
            sample_keys = list(flow_ratios.keys())[:5]
            logger.info(f"[房租水电] flow_ratios 示例keys: {sample_keys}")
        gmv_ratio_count = sum(1 for rows in flow_ratios.values() for _, gmv_ratio, _, _ in rows if gmv_ratio is not None)
        logger.info(f"[房租水电] flow_ratios 中有gmv_ratio的行数: {gmv_ratio_count}")

        # 解密并读取 Excel
        actual_path, is_decrypted = decrypt_excel_if_needed(file_path)
        try:
            xls = pd.ExcelFile(actual_path)
        except Exception as e:
            logger.error(f"[房租水电] 读取失败: {e}")
            if is_decrypted and actual_path != file_path:
                os.unlink(actual_path)
            return [], [], unmatched

        raw_records = []
        gmv_allocated_records = []  # GMV分摊的记录,直接传递给数据库更新
        direct_match_count = 0
        park_match_count = 0
        park_fail_count = 0
        failed_count = 0
        failed_stores = []
        park_allocated_total = Decimal("0")

        # 第一阶段变量:聚合桶
        direct_buckets = {}
        park_buckets = {}
        row_count = 0
        total_input_fee = Decimal("0")

        try:
            for sheet_name in xls.sheet_names:
                df_raw = pd.read_excel(actual_path, sheet_name=sheet_name, header=None)
                header_row, title_rows = detect_header_row(df_raw)
                df = pd.read_excel(actual_path, sheet_name=sheet_name, header=header_row)
                df.columns = [str(col).strip() for col in df.columns]

                # 查找关键列
                col_target = find_column(df, "分账对象", "分账门店", "承担方", "流量方名称")
                col_rent = find_column(df, "房租费用", "房租", "租金")
                col_water = find_column(df, "水电费", "水电", "水费")
                col_construction = find_column(df, "施工费用", "施工费", "装修费")
                col_biz = find_column(df, "业务类型", "业务分类")
                col_gmv = find_column(df, "GMV", "产值")

                logger.debug(f"[房租水电] Sheet '{sheet_name}' 列匹配: 分账对象={col_target}, "
                            f"房租={col_rent}, 水电={col_water}, 施工={col_construction}, "
                            f"业务={col_biz}, GMV={col_gmv}")

                # 用于直接匹配的流量方名称集合(已标准化)
                std_flow_names_set = {to_standard(name, '4s') for name in flow_names_set}
                std_to_original_flow = {}
                for name in flow_names_set:
                    std_name = to_standard(name, '4s')
                    if std_name not in std_to_original_flow:
                        std_to_original_flow[std_name] = name

                skip_processed_rows = set()

                for idx, row in df.iterrows():
                    if idx in skip_processed_rows:
                        continue

                    target = None
                    if col_target:
                        target = row[col_target]
                    if target is None or str(target).strip() == "" or str(target).strip() == "nan":
                        skip_reasons['SKIP-target为空'] += Decimal('1')
                        continue

                    target = str(target).strip()
                    std_target = to_standard(target, '4s')

                    # 检测是否为合并行(房租、水电、施工费用列存在合并单元格)
                    # 传入 col_target 用于判定真实合并(后续行分账对象为空才算合并)
                    merged_info = detect_merged_cells(df, idx, col_rent, col_water, col_construction, col_target)
                    is_merged_row = merged_info['is_merged']

                    # 仅统计 1.1 业务
                    if col_biz:
                        biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
                        if biz_val and "1.1" not in biz_val and "贴膜" not in biz_val:
                            rent = safe_decimal(row[col_rent]) if col_rent else Decimal("0")
                            water = safe_decimal(row[col_water]) if col_water else Decimal("0")
                            construction = safe_decimal(row[col_construction]) if col_construction else Decimal("0")
                            total_fee = rent + water + construction
                            skip_reasons['SKIP-业务类型非1.1'] += total_fee
                            if total_fee > 0:
                                unmatched['rent_utilities'] += total_fee   # 差额完整性:即使非1.1业务,有金额也要计入未匹配
                            continue

                    # 合计 = 房租 + 水电 + 施工
                    rent = safe_decimal(row[col_rent]) if col_rent else Decimal("0")
                    water = safe_decimal(row[col_water]) if col_water else Decimal("0")
                    construction = safe_decimal(row[col_construction]) if col_construction else Decimal("0")
                    total_fee = rent + water + construction

                    if total_fee == 0:
                        skip_reasons['SKIP-金额为0'] += Decimal('1')
                        continue

                    # 诊断日志:打印每一行原始数据
                    logger.info(f"[房租水电][原始行] 行{idx}: target='{target}', rent={rent}, water={water}, construction={construction}, total={total_fee}, is_merged={is_merged_row}")
                    logger.info(f"[房租水电][原始行]   原始Excel数据: {row.to_dict()}")

                    # 合并行处理:如果当前行是合并行,向下扫描收集所有分账对象
                    if is_merged_row and merged_info['merged_row_count'] > 1:
                        collected_targets = []
                        merged_total_fee = Decimal("0")
                        skip_rows = set()
                        independent_rows = []  # 存储有独立费用的行
                        
                        # 收集当前行的分账对象和费用
                        if pd.notna(target) and target.strip():
                            collected_targets.append(target.strip())
                            merged_total_fee += total_fee
                        
                        # 从 detect_merged_cells 获取独立费用行索引
                        independent_indices = merged_info.get('independent_row_indices', [])
                        
                        # 向下扫描合并行,只收集分账对象
                        scan_count = merged_info['merged_row_count']
                        for scan_idx in range(idx + 1, min(idx + scan_count, len(df))):
                            # 如果是独立费用行,跳过合并处理
                            if scan_idx in independent_indices:
                                next_target = df.iloc[scan_idx][col_target] if col_target else None
                                next_rent = safe_decimal(df.iloc[scan_idx][col_rent]) if col_rent else Decimal("0")
                                next_water = safe_decimal(df.iloc[scan_idx][col_water]) if col_water else Decimal("0")
                                next_construction = safe_decimal(df.iloc[scan_idx][col_construction]) if col_construction else Decimal("0")
                                next_total = next_rent + next_water + next_construction
                                if next_total > 0:
                                    independent_rows.append({
                                        'idx': scan_idx,
                                        'target': str(next_target).strip() if next_target is not None else '',
                                        'rent': next_rent,
                                        'water': next_water,
                                        'construction': next_construction,
                                        'total': next_total
                                    })
                                continue
                            
                            # 合并行延续:收集分账对象
                            next_target = df.iloc[scan_idx][col_target] if col_target else None
                            if next_target is not None and pd.notna(next_target) and str(next_target).strip():
                                next_target_str = str(next_target).strip()
                                if next_target_str not in collected_targets:
                                    collected_targets.append(next_target_str)
                            skip_rows.add(scan_idx)

                        logger.info(f"[房租水电][合并行] 行{idx}: 收集{len(collected_targets)}个分账对象, 总费用={merged_total_fee}, 跳过行={skip_rows}, 独立费用行={len(independent_rows)}")
                        logger.info(f"[房租水电][合并行]   targets详情: {collected_targets}")
                        
                        # 先处理合并行的分摊
                        if merged_total_fee > 0 and len(collected_targets) > 1:
                            # 解析所有收集到的分账对象(用逗号拼接后解析)
                            combined_target_str = ','.join(collected_targets)
                            alloc_targets = parse_allocation_targets(combined_target_str, flow_names_set, park_to_flows)
                            logger.info(f"[房租水电][合并行]   解析后alloc_targets: {alloc_targets}")

                            if len(alloc_targets) > 1 and task_id:
                                # 多个分账对象:按 GMV 占比分摊
                                flow_names_list = [t['name'] for t in alloc_targets if t['type'] == 'flow']
                                park_names_list = [t['name'] for t in alloc_targets if t['type'] == 'park']

                                gmv_data = query_gmv_by_targets(db, task_id, BIZ_TYPE_1_1,
                                                                flow_names=flow_names_list,
                                                                park_names=park_names_list)
                                logger.info(f"[房租水电][合并行]   GMV数据: {gmv_data}")

                                allocation_results = allocate_by_gmv_ratio(merged_total_fee, alloc_targets, gmv_data)
                                logger.info(f"[房租水电][合并行]   分摊结果: {allocation_results}")

                                if allocation_results:
                                    for alloc in allocation_results:
                                        gmv_allocated_records.append({
                                            "流量方名称": alloc['name'],
                                            "业务类型": BIZ_TYPE_1_1,
                                            "品牌": "",
                                            "房租及水电费": alloc['share'],
                                            "匹配方式": "gmv_ratio_merged",
                                            "__gmv_allocated__": True,
                                            "target_type": alloc['type'],
                                        })
                                    total_input_fee += merged_total_fee
                                    row_count += 1
                                    logger.info(f"[房租水电][合并行分摊] targets={len(alloc_targets)}, total_fee={merged_total_fee}, results={len(allocation_results)}")
                            
                            # 处理独立费用行(每个行独立分摊)
                            for ind_row in independent_rows:
                                ind_target = ind_row['target']
                                ind_total = ind_row['total']
                                
                                if ind_target and ind_total > 0 and task_id:
                                    ind_alloc_targets = parse_allocation_targets(ind_target, flow_names_set, park_to_flows)
                                    if ind_alloc_targets:
                                        ind_flow_names = [t['name'] for t in ind_alloc_targets if t['type'] == 'flow']
                                        ind_park_names = [t['name'] for t in ind_alloc_targets if t['type'] == 'park']
                                        
                                        ind_gmv_data = query_gmv_by_targets(db, task_id, BIZ_TYPE_1_1, 
                                                                            flow_names=ind_flow_names, 
                                                                            park_names=ind_park_names)
                                        
                                        ind_results = allocate_by_gmv_ratio(ind_total, ind_alloc_targets, ind_gmv_data)
                                        
                                        if ind_results:
                                            for ind_alloc in ind_results:
                                                gmv_allocated_records.append({
                                                    "流量方名称": ind_alloc['name'],
                                                    "业务类型": BIZ_TYPE_1_1,
                                                    "品牌": "",
                                                    "房租及水电费": ind_alloc['share'],
                                                    "匹配方式": "gmv_ratio_independent",
                                                    "__gmv_allocated__": True,
                                                    "target_type": ind_alloc['type'],
                                                })
                                            total_input_fee += ind_total
                                            row_count += 1
                                            logger.info(f"[房租水电][独立行分摊] target='{ind_target}', fee={ind_total}, results={len(ind_results)}")
                                        
                            continue
                        elif merged_total_fee > 0 and len(collected_targets) == 1:
                            # 单个分账对象:直接分配
                            target_info = alloc_targets[0]
                            gmv_allocated_records.append({
                                "流量方名称": target_info['name'],
                                "业务类型": BIZ_TYPE_1_1,
                                "品牌": "",
                                "房租及水电费": merged_total_fee,
                                "匹配方式": "single_merged",
                                "__gmv_allocated__": True,
                                "target_type": target_info['type'],
                            })
                            total_input_fee += merged_total_fee
                            row_count += 1
                            logger.info(f"[房租水电][合并行单对象] target='{target_info['name']}', fee={merged_total_fee}")
                            
                            # 处理独立费用行
                            for ind_row in independent_rows:
                                ind_target = ind_row['target']
                                ind_total = ind_row['total']
                                
                                if ind_target and ind_total > 0 and task_id:
                                    ind_alloc_targets = parse_allocation_targets(ind_target, flow_names_set, park_to_flows)
                                    if ind_alloc_targets:
                                        ind_flow_names = [t['name'] for t in ind_alloc_targets if t['type'] == 'flow']
                                        ind_park_names = [t['name'] for t in ind_alloc_targets if t['type'] == 'park']
                                        
                                        ind_gmv_data = query_gmv_by_targets(db, task_id, BIZ_TYPE_1_1, 
                                                                          flow_names=ind_flow_names, 
                                                                          park_names=ind_park_names)
                                        
                                        ind_results = allocate_by_gmv_ratio(ind_total, ind_alloc_targets, ind_gmv_data)
                                        
                                        if ind_results:
                                            for ind_alloc in ind_results:
                                                gmv_allocated_records.append({
                                                    "流量方名称": ind_alloc['name'],
                                                    "业务类型": BIZ_TYPE_1_1,
                                                    "品牌": "",
                                                    "房租及水电费": ind_alloc['share'],
                                                    "匹配方式": "gmv_ratio_independent",
                                                    "__gmv_allocated__": True,
                                                    "target_type": ind_alloc['type'],
                                                })
                                            total_input_fee += ind_total
                                            row_count += 1
                                            logger.info(f"[房租水电][独立行分摊] target='{ind_target}', fee={ind_total}, results={len(ind_results)}")
                            
                            continue

                    # GMV分摊路径:当 task_id 提供时,尝试使用 GMV 分摊(非合并行或合并行回退)
                    gmv_allocated = False
                    if task_id:
                        try:
                            alloc_targets = parse_allocation_targets(target, flow_names_set, park_to_flows)
                            logger.info(f"[房租水电][GMV分摊路径] 行{idx}: target='{target}', alloc_targets={alloc_targets}")

                            if alloc_targets:
                                flow_names = [t['name'] for t in alloc_targets if t['type'] == 'flow']
                                park_names = [t['name'] for t in alloc_targets if t['type'] == 'park']

                                gmv_data = query_gmv_by_targets(db, task_id, BIZ_TYPE_1_1, flow_names=flow_names, park_names=park_names)
                                logger.info(f"[房租水电][GMV分摊路径]   GMV数据: {gmv_data}")

                                allocation_results = allocate_by_gmv_ratio(total_fee, alloc_targets, gmv_data)
                                logger.info(f"[房租水电][GMV分摊路径]   分摊结果: {allocation_results}")

                                if allocation_results:
                                    for alloc in allocation_results:
                                        gmv_allocated_records.append({
                                            "流量方名称": alloc['name'],
                                            "业务类型": BIZ_TYPE_1_1,
                                            "品牌": "",
                                            "房租及水电费": alloc['share'],
                                            "匹配方式": "gmv_ratio_allocation",
                                            "__gmv_allocated__": True,
                                            "target_type": alloc['type'],
                                        })
                                    gmv_allocated = True
                                    total_input_fee += total_fee
                                    row_count += 1
                                    merged_flag = " [合并行]" if is_merged_row else ""
                                    logger.info(f"[房租水电][GMV分摊完成]{merged_flag} target='{target}', fee={total_fee}, targets={len(alloc_targets)}, allocated={len(allocation_results)}")
                        except Exception as e:
                            logger.warning(f"[房租水电][GMV分摊] 分摊失败,回退原有逻辑: {e}")

                    if gmv_allocated:
                        continue

                    # 获取 GMV
                    gmv = Decimal("0")
                    if col_gmv:
                        gmv = safe_decimal(row[col_gmv])

                    # 聚合到桶中
                    total_input_fee += total_fee
                    row_count += 1

                    # 优先检查园区店匹配(使用 gmv_ratio_park)
                    # 如果 target 在 park_to_flows 中,走园区店回退路径
                    in_park_to_flows = target in park_to_flows
                    std_in_park_to_flows = to_standard(target, 'yq') in park_to_flows
                    
                    # 诊断日志:前10条记录显示匹配检查结果
                    if row_count <= 10:
                        logger.debug(f"[房租水电] 门店检查: store='{target}', in_park_to_flows={in_park_to_flows}, std_in_park_to_flows={std_in_park_to_flows}, in_flow_names={std_target in std_flow_names_set}")
                    
                    if in_park_to_flows or std_in_park_to_flows:
                        # 园区店回退桶 - 使用原始值或标准化值匹配
                        match_method = None
                        ps = target
                        
                        if in_park_to_flows:
                            match_method = "原始值"
                        else:
                            ps_std = to_standard(target, 'yq')
                            if ps_std in park_to_flows:
                                ps = ps_std
                                match_method = "标准化值"
                        
                        if match_method:
                            key = (ps, BIZ_TYPE_1_1)
                            if key not in park_buckets:
                                park_buckets[key] = Decimal("0")
                            park_buckets[key] += total_fee
                            if park_match_count < 5:
                                logger.debug(f"[房租水电] 园区店回退匹配成功: store='{target}', ps='{ps}', 方式={match_method}")
                            park_match_count += 1
                            continue  # 跳过直接匹配逻辑
                    
                    # 如果不是园区店,走直接匹配逻辑
                    if std_target in std_flow_names_set:
                        # 直接匹配桶
                        key = (std_target, BIZ_TYPE_1_1)
                        if key not in direct_buckets:
                            direct_buckets[key] = Decimal("0")
                        direct_buckets[key] += total_fee
                    else:
                        # 园区店回退桶(park_to_flows 中不存在的情况)
                        ps = target
                        
                        if ps in park_to_flows:
                            match_method = "原始值"
                        else:
                            ps_std = to_standard(target, 'yq')
                            if ps_std in park_to_flows:
                                ps = ps_std
                                match_method = "标准化值"
                            else:
                                # 尝试模糊匹配
                                if park_fail_count < 10:
                                    logger.warning(f"[房租水电] 园区店匹配失败: store='{target}'")
                                park_fail_count += 1
                                unmatched['rent_utilities'] += total_fee
                                continue
                        
                        key = (ps, BIZ_TYPE_1_1)
                        if key not in park_buckets:
                            park_buckets[key] = Decimal("0")
                        park_buckets[key] += total_fee
                        park_match_count += 1

            # 第一阶段日志
            logger.info(f"[房租水电] 聚合完成: {row_count} 行有效, 总输入金额={total_input_fee}")
            logger.info(f"[房租水电] 桶统计: direct_buckets={len(direct_buckets)}, park_buckets={len(park_buckets)}")
            for (k, v) in list(direct_buckets.items())[:3]:
                logger.debug(f"[房租水电] direct_bucket key={k}, fee={v}")
            for (k, v) in list(park_buckets.items())[:3]:
                logger.debug(f"[房租水电] park_bucket key={k}, fee={v}")

            # 第二阶段:分配

            # 2.1 直接匹配桶分配
            target_flow = '龙联汽车科技(深圳)有限公司'
            for (std_store, biz_type), fee in direct_buckets.items():
                if fee == 0:
                    continue

                original_flow = std_to_original_flow.get(std_store, std_store)
                is_target = target_flow in str(original_flow)

                # 查找 gmv_ratio
                ratio_rows = flow_ratios.get((std_store, biz_type), [])
                if not ratio_rows:
                    for (fn, bt), rows in flow_ratios.items():
                        if fn == std_store:
                            ratio_rows.extend(rows)

                if is_target:
                    logger.info(f"[直接匹配] 处理目标流量方: flow={original_flow}, std_store={std_store}, biz_type={biz_type}, fee={fee}")
                    logger.info(f"[直接匹配]   ratio_rows数量: {len(ratio_rows)}")
                    for i, (brand, gmv_ratio, gmv_ratio_park, park_store_val) in enumerate(ratio_rows):
                        logger.info(f"[直接匹配]   ratio_row[{i}]: brand={brand}, gmv_ratio={gmv_ratio}, gmv_ratio_park={gmv_ratio_park}, park_store={park_store_val}")

                ratio_applied = False
                if ratio_rows:
                    # 过滤非嘀加 brand,只保留嘀加自营行
                    dijia_entries = []
                    for brand, gmv_ratio, gmv_ratio_park, park_store_val in ratio_rows:
                        if gmv_ratio is None:
                            continue
                        # 判断该 brand 是否嘀加
                        sp = ""
                        if settlement_map:
                            sp = (settlement_map.get((original_flow, biz_type, brand), {}).get("服务商") or "").strip()
                        if "嘀加" in sp or not sp:  # 没 settlement_map 信息时保守保留
                            dijia_entries.append((brand, Decimal(str(gmv_ratio))))
                    
                    if dijia_entries:
                        # 过滤后重新归一化比例到 sum=1
                        sum_r = sum(r for _, r in dijia_entries)
                        if sum_r > 0:
                            for brand, r in dijia_entries:
                                normalized_r = r / sum_r
                                fee_share = round_2(fee * normalized_r)
                                raw_records.append({
                                    "流量方名称": original_flow,
                                    "业务类型": biz_type or BIZ_TYPE_1_1,
                                    "品牌": brand or "",
                                    "房租及水电费": fee_share,
                                    "匹配方式": "direct_ratio",
                                })
                                ratio_applied = True
                                logger.info(f"[直接匹配](嘀加归一化) flow={original_flow}, brand={brand}, raw_r={r}, norm_r={normalized_r:.4f}, fee_share={fee_share}")

                if not ratio_applied:
                    logger.warning(f"[直接匹配] flow={original_flow}, biz_type={biz_type} 无gmv_ratio, 回退100%分配")
                    raw_records.append({
                        "流量方名称": original_flow,
                        "业务类型": biz_type or BIZ_TYPE_1_1,
                        "品牌": "",
                        "房租及水电费": round_2(fee),
                        "匹配方式": "direct",
                    })
                direct_match_count += 1

            # 2.2 园区店回退桶分配
            for (ps, biz_type), fee in park_buckets.items():
                if fee == 0:
                    continue

                related_flows = park_to_flows.get(ps, [])
                matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type]

                if not matching_flows:
                    park_fail_count += 1
                    failed_count += 1
                    logger.warning(f"[园区店回退] ps='{ps}' 无匹配业务类型={biz_type}的流量方")
                    if len(failed_stores) < 10:
                        failed_stores.append(ps)
                    unmatched['rent_utilities'] += fee
                    continue

                # 优先查找 gmv_ratio_park
                park_ratio_rows = park_rows.get((ps, biz_type), [])
                if park_ratio_rows:
                    # 归一化:过滤非嘀加后比例和 < 1,需重新归一化到 100%
                    raw_ratios = []
                    for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows:
                        if gmv_ratio_park is not None:
                            r = Decimal(str(gmv_ratio_park))
                            ratio_type = "gmv_ratio_park"
                        elif gmv_ratio is not None:
                            r = Decimal(str(gmv_ratio))
                            ratio_type = "gmv_ratio(回退)"
                        else:
                            continue
                        raw_ratios.append((flow_name, brand, r, ratio_type))
                    total_r = sum(r for _, _, r, _ in raw_ratios)
                    if total_r > 0:
                        allocated_fee = Decimal("0")
                        for flow_name, brand, r, ratio_type in raw_ratios:
                            normalized_r = r / total_r
                            fee_share = round_2(fee * normalized_r)
                            allocated_fee += fee_share
                            raw_records.append({
                                "流量方名称": flow_name,
                                "业务类型": biz_type or BIZ_TYPE_1_1,
                                "品牌": brand or "",
                                "房租及水电费": fee_share,
                                "匹配方式": "park_ratio_db",
                            })
                        park_match_count += 1
                        park_allocated_total += allocated_fee
                        logger.info(f"[园区店回退] {ratio_type}(归一化): ps='{ps}', {len(raw_ratios)}行, sum_r={total_r:.4f}, fee={allocated_fee}")
                    else:
                        # 比例和为0 → 直接进 unmatched
                        unmatched['rent_utilities'] += fee
                        continue
                else:
                    # 回退:使用 gmv_ratio 按流量方分配
                    logger.info(f"[园区店回退] gmv_ratio_park不存在, 回退使用gmv_ratio: ps='{ps}', bt={biz_type}")
                    flow_ratio_list = []
                    total_ratio = Decimal("0")
                    for fn, fb in matching_flows:
                        std_fn = to_standard(fn, '4s')
                        ratio_entries = flow_ratios.get((std_fn, biz_type), [])
                        for brand, gmv_ratio, gmv_ratio_park, park_store_val in ratio_entries:
                            if gmv_ratio is None:
                                continue
                            # 过滤非嘀加 brand
                            sp = ""
                            if settlement_map:
                                sp = (settlement_map.get((fn, biz_type, brand), {}).get("服务商") or "").strip()
                            if sp and "嘀加" not in sp:
                                continue
                            r = Decimal(str(gmv_ratio))
                            flow_ratio_list.append((fn, brand, r))
                            total_ratio += r

                    if flow_ratio_list and total_ratio > 0:
                        for fn, brand, r in flow_ratio_list:
                            normalized_r = r / total_ratio
                            fee_share = round_2(fee * normalized_r)
                            raw_records.append({
                                "流量方名称": fn,
                                "业务类型": biz_type or BIZ_TYPE_1_1,
                                "品牌": brand or "",
                                "房租及水电费": fee_share,
                                "匹配方式": "park_fallback_gmv_ratio",
                            })
                            logger.info(f"[园区店回退] gmv_ratio回退: flow={fn}, brand={brand}, 归一比例={normalized_r:.4f}")
                        park_match_count += 1
                        park_allocated_total += sum(
                            Decimal(str(fee * r / total_ratio))
                            for _, _, r in flow_ratio_list
                        )
                    else:
                        # 比例数据完全不存在,跳过该桶(不分均)
                        logger.warning(f"[园区店回退] gmv_ratio也不存在, 跳过该桶: ps='{ps}', bt={biz_type}, fee={fee}")
                        park_fail_count += 1
                        failed_count += 1
                        if len(failed_stores) < 10:
                            failed_stores.append(ps)
                        available_keys = [(k, len(v)) for k, v in park_rows.items() if ps in str(k[0])]
                        logger.warning(f"[园区店回退] 诊断: park_rows中含'{ps}'的key={available_keys}")
                        unmatched['rent_utilities'] += fee
                        continue

        finally:
            if is_decrypted and actual_path != file_path and os.path.exists(actual_path):
                os.unlink(actual_path)

        # 日志汇总
        logger.info(f"[房租水电] 第一阶段聚合: {row_count} 行有效, 总输入金额={total_input_fee}")
        logger.info(f"[房租水电] 第二阶段分配: direct_buckets={len(direct_buckets)}, park_buckets={len(park_buckets)}")
        logger.info(f"[房租水电] 匹配统计: 直接匹配={direct_match_count}, "
                    f"园区店回退成功={park_match_count}, 园区店回退失败={park_fail_count}, "
                    f"总失败={failed_count}")
        logger.info(f"[房租水电] 园区店回退分摊金额合计: {park_allocated_total}")
        if failed_stores:
            logger.warning(f"[房租水电] 匹配失败的门店(最多显示10个): {failed_stores}")

        if not raw_records and not gmv_allocated_records:
            logger.info("[房租水电] 无有效数据")
            return [], [], unmatched

        # 按 (流量方名称, 业务类型, 品牌) 汇总
        aggregated = defaultdict(lambda: Decimal("0"))
        for r in raw_records:
            key = (r["流量方名称"], r["业务类型"], r.get("品牌", ""))
            aggregated[key] += r["房租及水电费"]

        result = []
        for (flow, biz, brand), fee in aggregated.items():
            result.append({
                "流量方名称": flow,
                "业务类型": biz,
                "品牌": brand,
                "房租及水电费": round_2(fee),
            })

        # 计算总量守恒
        total_input = sum(
            r["房租及水电费"] for r in raw_records
        )
        total_output = sum(
            r["房租及水电费"] for r in result
        )
        logger.info(f"[房租水电] 总量校验: 原始输入={total_input}, 输出汇总={total_output}, 差值={total_input - total_output}")

        # 总量校验:用 total_input_fee(接纳到各流程的总金额)减去实际分配到 raw_records + gmv_allocated_records 的金额
        gmv_allocated_total = sum(r["房租及水电费"] for r in gmv_allocated_records)
        matched_sum = total_output + gmv_allocated_total
        conservation_unmatched = total_input_fee - matched_sum
        unmatched['rent_utilities'] += conservation_unmatched
        logger.info(f"[房租水电][未匹配汇总] rent_utilities: 总额={total_input_fee} 已匹配={matched_sum} 未匹配={unmatched['rent_utilities']}")
        if skip_reasons:
            logger.warning(f"[房租水电][跳过追踪] 各路径跳过金额/行数: {dict(skip_reasons)}")

        # 打印 GMV 分摊记录详情
        if gmv_allocated_records:
            logger.info(f"[房租水电] GMV分摊记录详情({len(gmv_allocated_records)}条):")
            for i, rec in enumerate(gmv_allocated_records):
                logger.info(f"[房租水电]   GMV记录[{i}]: name={rec['流量方名称']}, fee={rec['房租及水电费']}, type={rec.get('target_type', 'unknown')}, method={rec.get('匹配方式', 'unknown')}")

        logger.info(f"[房租水电] 解析完成,共 {len(result)} 条记录,GMV分摊 {len(gmv_allocated_records)} 条")
        return result, gmv_allocated_records, unmatched

    # ========================================================
    # 构建成本汇总表
    # ========================================================

    def _build_cost_summary(self, settlement_data, market_results, wage_results, labor_results, utility_results, prev_month_data=None, settlement_map=None, park_ratio_map=None, flow_ratio_entries=None):
        """
        生成成本汇总表。
        综合结算数据、市场费、外援施工费、人力成本、房租水电施工费,
        按流量方/业务类型/品牌维度汇总各项费用,并计算占比。
        返回:List[dict],每条记录对应 biz_budget_achieve 的一行
        """
        _seen_sp = set()
        # 无效品牌列表:这些品牌是占位符,没有实际业务意义,不应参与比例计算
        INVALID_BRANDS = {"", "未知品牌", "未识别", "N/A", "null", "None"}
        logger.info("[成本汇总] 开始生成成本汇总...")

        # ---------- 收集 GMV 和产值数据 ----------
        # 从结算数据构建 GMV 和产值映射
        gmv_lookup = {}  # (流量方, 业务类型, 品牌) -> {GMV, 产值, 服务费, 嘀加分润, 服务商, 装修摊销, 门店耗材}
        if settlement_data:
            for s in settlement_data:
                key = (s["流量方名称"], s["业务类型"], s["品牌"] or "")
                gmv_lookup[key] = {
                    "GMV": s["GMV"],
                    "产值": s["产值"],
                    "服务费": s.get("服务费", Decimal("0")),
                    "嘀加分润": s.get("嘀加分润", Decimal("0")),
                    "服务商": s.get("服务商", ""),
                    "装修摊销": s.get("装修摊销", Decimal("0")),
                    "门店耗材": s.get("门店耗材", Decimal("0")),
                    "gmv_ratio": s.get("gmv_ratio"),
                    "gmv_ratio_park": s.get("gmv_ratio_park"),
                    "park_store": s.get("park_store", ""),
                }

        # 如果没有结算数据,从市场费结果中收集流量方信息用于占位
        if not settlement_data:
            logger.warning("[成本汇总] 无结算数据,使用占位值")
            for m in market_results:
                key = (m["流量方名称"], m["业务类型"], m["品牌"] or "")
                if key not in gmv_lookup:
                    gmv_lookup[key] = {
                        "GMV": Decimal("0"),
                        "产值": Decimal("0"),
                    }

        # ---------- 收集所有唯一键 ----------
        all_keys = set()

        # 市场费:含品牌维度
        for r in market_results:
            brand = r.get("品牌", "")
            all_keys.add((r["流量方名称"], r["业务类型"], brand or ""))

        # 外援施工费(已按 gmv_ratio 分摊,包含品牌和园区店)
        for r in wage_results:
            brand = r.get("品牌", "") or ""
            park = r.get("园区店", "") or ""
            all_keys.add((r["流量方名称"], r["业务类型"], brand, park))

        # 人力成本
        for r in labor_results:
            all_keys.add((r["流量方名称"], r["业务类型"], ""))

        # 房租水电(非园区店)
        for r in utility_results:
            if r.get("__park_store__"):
                continue
            brand = r.get("品牌", "") or ""
            all_keys.add((r["流量方名称"], r["业务类型"], brand))

        # 结算数据中的所有键
        for key in gmv_lookup.keys():
            all_keys.add(key)

        # 关键修复:从 flow_ratio_entries 扩展键,确保每个条目都有独立的输出行
        # 当同一(flow,biz,brand)有多条记录时(不同park_store/gmv_ratio),每条都需要独立一行
        # 改为四元组 (flow, biz, brand, park_store) 作为唯一键
        if flow_ratio_entries and isinstance(flow_ratio_entries, dict):
            expanded_count = 0
            for (flow, biz), entries in flow_ratio_entries.items():
                for br, ps, gr, grp in entries:
                    all_keys.add((flow, biz, br, ps))
                    expanded_count += 1
            if expanded_count > 0:
                logger.info(f"[成本汇总] 从flow_ratio_entries扩展了 {expanded_count} 个输出键(四元组)")

        # 预构建 ratio_lookup: (flow, biz, brand, park_store) -> gmv_ratio
        # 用于在主循环中直接查找,避免遍历匹配
        ratio_lookup = {}
        # 预构建 park_ratio_lookup: (flow, biz, brand, park_store) -> gmv_ratio_park
        # 用于同一品牌下多园区店的二次分摊
        park_ratio_lookup = {}
        # 统计每个(flow, biz, brand)下有多少个park_store
        brand_park_counts = defaultdict(int)
        
        if flow_ratio_entries and isinstance(flow_ratio_entries, dict):
            for (flow, biz), entries in flow_ratio_entries.items():
                for br, ps, gr, grp in entries:
                    if gr is not None:
                        # 四元组精确查找
                        ratio_lookup[(flow, biz, br, ps)] = gr
                        # 三元组回退查找(park_store为空时)
                        if (flow, biz, br, "") not in ratio_lookup:
                            ratio_lookup[(flow, biz, br, "")] = gr
                    if grp is not None:
                        park_ratio_lookup[(flow, biz, br, ps)] = grp
                        if (flow, biz, br, "") not in park_ratio_lookup:
                            park_ratio_lookup[(flow, biz, br, "")] = grp
                    brand_park_counts[(flow, biz, br)] += 1

        # ---------- 预先聚合各项费用 ----------
        labor_agg = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
        for l in labor_results:
            key = (l["流量方名称"].strip(), l["业务类型"].strip())
            labor_agg[key]["技师工资"] += l["技师工资"]
            labor_agg[key]["营销团队工资"] += l["营销团队工资"]
        
        # 人力成本聚合日志
        if labor_agg:
            labor_total_tech = sum(v["技师工资"] for v in labor_agg.values())
            labor_total_mkt = sum(v["营销团队工资"] for v in labor_agg.values())
            logger.info(f"[成本汇总] 人力成本聚合: {len(labor_agg)} 个(流量方,业务类型)键, "
                       f"技师工资合计={labor_total_tech}, 营销团队工资合计={labor_total_mkt}")

        # 外援施工费:已按 gmv_ratio 分摊,按 (flow, biz, brand, park) 聚合
        wage_agg = defaultdict(lambda: Decimal("0"))
        for w in wage_results:
            brand = w.get("品牌", "") or ""
            park = w.get("园区店", "") or ""
            key = (w["流量方名称"].strip(), w["业务类型"].strip(), brand.strip(), park.strip())
            wage_agg[key] += w["外援施工费"]
        
        if wage_agg:
            logger.info(f"[成本汇总] 外援施工费聚合: {len(wage_agg)} 个键, 总金额={sum(wage_agg.values())}")

        utility_agg = defaultdict(lambda: Decimal("0"))
        utility_gmv_allocated = set()  # 记录已GMV分摊的键,避免重复分摊
        for u in utility_results:
            if u.get("__park_store__"):
                continue
            brand = u.get("品牌", "") or ""
            key = (u["流量方名称"].strip(), u["业务类型"].strip(), brand.strip() if brand else "")
            utility_agg[key] += u["房租及水电费"]
            if u.get("__gmv_allocated__"):
                utility_gmv_allocated.add(key)

        # ---------- 过滤无效品牌 ----------
        original_key_count = len(all_keys)
        filtered_keys = set()
        for key in all_keys:
            brand = key[2].strip() if key[2] else ""
            if brand not in INVALID_BRANDS:
                filtered_keys.add(key)
        all_keys = filtered_keys
        filtered_count = original_key_count - len(all_keys)
        if filtered_count > 0:
            logger.info(f"[成本汇总] 过滤无效品牌: 原始={original_key_count}, 过滤后={len(all_keys)}, 移除={filtered_count}个无效品牌条目")
        
        # 诊断日志:检查龙联汽车科技的 utility_agg 数据
        target_flow = '龙联汽车科技(深圳)有限公司'
        if target_flow:
            logger.info(f"[成本汇总-诊断] 检查 utility_agg 中的龙联汽车科技数据:")
            for key, fee in utility_agg.items():
                if target_flow in str(key[0]):
                    logger.info(f"[成本汇总-诊断]   key={key}, fee={fee}")
            logger.info(f"[成本汇总-诊断] all_keys 中的龙联汽车科技条目:")
            for key in all_keys:
                if target_flow in str(key[0]):
                    logger.info(f"[成本汇总-诊断]   key={key}")

        # ---------- 按键汇总各项费用 ----------
        summary = []
        idx = 0

        for key in sorted(all_keys):
            # 支持三元组 (flow, biz, brand) 和四元组 (flow, biz, brand, park_store)
            flow_name = key[0].strip() if key[0] else ""
            biz_type = key[1].strip() if key[1] else ""
            brand = key[2].strip() if key[2] else ""
            park_store = key[3].strip() if len(key) > 3 and key[3] else ""
            
            # 获取 GMV 和产值
            settle_key = (flow_name, biz_type, brand)
            if settle_key in gmv_lookup:
                gmv = gmv_lookup[settle_key]["GMV"]
                revenue = gmv_lookup[settle_key]["产值"]
                service_fee = gmv_lookup[settle_key].get("服务费", Decimal("0"))
                dijia_profit = gmv_lookup[settle_key].get("嘀加分润", Decimal("0"))
                service_provider = (gmv_lookup[settle_key].get("服务商", "") or "").strip()
                renovation = gmv_lookup[settle_key].get("装修摊销", Decimal("0"))
                consumables = gmv_lookup[settle_key].get("门店耗材", Decimal("0"))
            else:
                # 尝试无品牌匹配
                settle_key_no_brand = (flow_name, biz_type, "")
                if settle_key_no_brand in gmv_lookup:
                    gmv = gmv_lookup[settle_key_no_brand]["GMV"]
                    revenue = gmv_lookup[settle_key_no_brand]["产值"]
                    service_fee = gmv_lookup[settle_key_no_brand].get("服务费", Decimal("0"))
                    dijia_profit = gmv_lookup[settle_key_no_brand].get("嘀加分润", Decimal("0"))
                    service_provider = (gmv_lookup[settle_key_no_brand].get("服务商", "") or "").strip()
                    renovation = gmv_lookup[settle_key_no_brand].get("装修摊销", Decimal("0"))
                    consumables = gmv_lookup[settle_key_no_brand].get("门店耗材", Decimal("0"))
                else:
                    gmv = Decimal("0")
                    revenue = Decimal("0")
                    service_fee = Decimal("0")
                    dijia_profit = Decimal("0")
                    service_provider = ""
                    renovation = Decimal("0")
                    consumables = Decimal("0")

            row = {
                "流量方名称": flow_name,
                "业务类型": biz_type,
                "品牌": brand,
                "园区店": park_store,
                "GMV": gmv,
                "产值": revenue,
                "服务商": service_provider,
                "服务费": service_fee,
                "嘀加分润": dijia_profit,
                "装修摊销": renovation,
                "门店耗材": consumables,
                "市场费": Decimal("0"),
                "外援施工": Decimal("0"),
                "技师工资": Decimal("0"),
                "营销团队工资": Decimal("0"),
                "人员工资": Decimal("0"),
                "房租及水电费": Decimal("0"),
            }

            # --- 匹配市场费 ---
            for m in market_results:
                m_brand = m.get("品牌", "") or ""
                # 严格品牌匹配:
                # 1. 如果 m 有品牌,只匹配精确品牌
                # 2. 如果 m 无品牌,只匹配无品牌的行(避免重复计入)
                brand_match = False
                if m_brand and brand:
                    brand_match = (m_brand.strip() == brand.strip())
                elif not m_brand and not brand:
                    brand_match = True
                # 一方有品牌、另一方无品牌时不匹配
                    
                if (m["流量方名称"] == flow_name
                        and m["业务类型"] == biz_type
                        and brand_match):
                    row["市场费"] += m["市场费"]

            # 同一 (流量方, 业务类型) 下所有品牌的 GMV 合计
            same_flow_biz_gmv = Decimal("0")
            brand_count = 0
            for s_key in gmv_lookup:
                if s_key[0] == flow_name and s_key[1] == biz_type:
                    same_flow_biz_gmv += gmv_lookup[s_key]["GMV"]
                    brand_count += 1

            if brand_count > 1:
                logger.info(f"[成本汇总] 多品牌分摊: 流量方={flow_name}, 业务类型={biz_type}, 品牌数={brand_count}, GMV合计={same_flow_biz_gmv}, 本品牌GMV={gmv}")

            # 计算本品牌的分摊比例 —— 优先使用 ratio_lookup(从 flow_ratio_entries 预构建)
            target_flow = '龙联汽车科技(深圳)有限公司'
            is_target_flow = target_flow in str(flow_name)
            flow_biz_ratio = Decimal("1")
            ratio_source = "gmv_calc"

            # 从 ratio_lookup 直接查找,key=(flow, biz, brand, park_store) 四元组
            db_ratio = None
            # 精确匹配:四元组 (flow, biz, brand, park_store)
            lookup_key_4 = (flow_name, biz_type, brand, park_store)
            if lookup_key_4 in ratio_lookup:
                db_ratio = ratio_lookup[lookup_key_4]
                if is_target_flow:
                    logger.info(f"[成本汇总] ratio_lookup四元组精确命中: brand='{brand}', ps='{park_store}' → gmv_ratio={db_ratio}")
            # 回退匹配:park_store为空的三元组 (flow, biz, brand, "")
            elif park_store and (flow_name, biz_type, brand, "") in ratio_lookup:
                db_ratio = ratio_lookup[(flow_name, biz_type, brand, "")]
                if is_target_flow:
                    logger.info(f"[成本汇总] ratio_lookup回退匹配(ps为空): brand='{brand}' → gmv_ratio={db_ratio}")
            elif not park_store:
                # 无park_store场景:尝试三元组
                if (flow_name, biz_type, brand, "") in ratio_lookup:
                    db_ratio = ratio_lookup[(flow_name, biz_type, brand, "")]
                    if is_target_flow:
                        logger.info(f"[成本汇总] ratio_lookup三元组匹配: brand='{brand}' → gmv_ratio={db_ratio}")
                elif brand == "":
                    # 无品牌无park_store场景
                    candidates = []
                    for (f, b, br, ps), gr in ratio_lookup.items():
                        if f == flow_name and b == biz_type and br:
                            candidates.append((br, ps, gr))
                    if candidates:
                        db_ratio = candidates[0][2]
                        if is_target_flow:
                            logger.info(f"[成本汇总] 无品牌回退: 使用第一个有效比例 brand='{candidates[0][0]}', ps='{candidates[0][1]}' → gmv_ratio={db_ratio}")
            
            # 回退:从 gmv_lookup 查找
            if db_ratio is None:
                if settle_key in gmv_lookup:
                    db_ratio = gmv_lookup[settle_key].get("gmv_ratio")
                if db_ratio is None:
                    nk = (flow_name, biz_type, "")
                    if nk in gmv_lookup:
                        db_ratio = gmv_lookup[nk].get("gmv_ratio")
                if is_target_flow:
                    logger.info(f"[成本汇总] ratio_lookup未命中, 回退gmv_lookup: brand='{brand}', db_ratio={db_ratio}")
            if db_ratio is not None:
                flow_biz_ratio = Decimal(str(float(db_ratio)))
                ratio_source = "db_gmv_ratio"
                if is_target_flow:
                    logger.info(f"[比例来源] 使用数据库 gmv_ratio={flow_biz_ratio} (流量方={flow_name}, 业务={biz_type}, 品牌={brand})")
            elif same_flow_biz_gmv > 0 and gmv > 0:
                flow_biz_ratio = gmv / same_flow_biz_gmv
                ratio_source = "gmv_calc"
                if is_target_flow:
                    logger.info(f"[比例来源] 回退 GMV 计算分摊 ratio={flow_biz_ratio} (流量方={flow_name}, 业务={biz_type}, 品牌={brand})")
            elif is_target_flow:
                logger.warning(f"[比例来源] 无法计算比例,使用默认值1: flow={flow_name}, db_ratio={db_ratio}, same_flow_biz_gmv={same_flow_biz_gmv}, gmv={gmv}")

            # --- 外援施工费(已在解析阶段按 gmv_ratio 分摊,直接使用)---
            wage_key = (flow_name, biz_type, brand, park_store)
            if wage_key in wage_agg:
                wage_fee = wage_agg[wage_key]
                row["外援施工"] += round_2(wage_fee)
                if is_target_flow:
                    logger.info(f"[外援施工费分摊] flow={flow_name}, bt={biz_type}, brand={brand}, ps={park_store}, fee={wage_fee}")

            # --- 人力成本(单品牌全额,多品牌按 GMV 占比分摊 + 多园区店二次分摊)---
            labor_key = (flow_name, biz_type)
            if labor_key in labor_agg:
                if brand_count <= 1:
                    # 单品牌:全额分配
                    tech_base = labor_agg[labor_key]["技师工资"]
                    mkt_base = labor_agg[labor_key]["营销团队工资"]
                else:
                    # 多品牌:按 GMV 占比分摊
                    tech_base = labor_agg[labor_key]["技师工资"] * flow_biz_ratio
                    mkt_base = labor_agg[labor_key]["营销团队工资"] * flow_biz_ratio
                
                # 多园区店二次分摊
                park_count = brand_park_counts.get((flow_name, biz_type, brand), 1)
                if park_count > 1 and park_store:
                    pr_key = (flow_name, biz_type, brand, park_store)
                    park_ratio = park_ratio_lookup.get(pr_key)
                    if park_ratio is not None:
                        tech_base = tech_base * Decimal(str(float(park_ratio)))
                        mkt_base = mkt_base * Decimal(str(float(park_ratio)))
                    else:
                        tech_base = tech_base / park_count
                        mkt_base = mkt_base / park_count
                
                row["技师工资"] += round_2(tech_base)
                row["营销团队工资"] += round_2(mkt_base)

            # --- 房租水电(使用已分摊到品牌的金额 + 多园区店二次分摊)---
            utility_key = (flow_name, biz_type, brand)
            if utility_key in utility_agg:
                utility_fee = utility_agg[utility_key]
                # 标记已GMV分摊的记录,避免在_update_utility_fee_to_db中重复分摊
                if utility_key in utility_gmv_allocated:
                    row["__gmv_allocated__"] = True
                # 多园区店二次分摊
                park_count = brand_park_counts.get((flow_name, biz_type, brand), 1)
                if park_count > 1 and park_store:
                    pr_key = (flow_name, biz_type, brand, park_store)
                    park_ratio = park_ratio_lookup.get(pr_key)
                    if park_ratio is not None:
                        utility_fee = utility_fee * Decimal(str(float(park_ratio)))
                    else:
                        utility_fee = utility_fee / park_count
                row["房租及水电费"] += round_2(utility_fee)
                if is_target_flow:
                    logger.info(f"[房租水电分摊] flow={flow_name}, brand={brand}, ps={park_store}, utility_fee={utility_fee}, gmv_allocated={utility_key in utility_gmv_allocated}")

            # 计算人员工资小计
            # 人员工资 = 外援施工 + 技师工资 + 营销团队工资
            row["人员工资"] = row["外援施工"] + row["技师工资"] + row["营销团队工资"]

            # ---------- 计算占比(基于分摊后的结果)----------
            # 确定比例计算的分母:优先使用产值,产值为0时使用GMV
            ratio_denominator = revenue if revenue > 0 else gmv
            if ratio_denominator <= 0:
                ratio_denominator = Decimal("0")
            
            # 市场费本月占比 = 市场费/GMV*100%
            row["市场费本月占比"] = pct(row["市场费"], gmv)
            
            # 市场费上月占比 - 从历史数据查询
            row["市场费上月占比"] = Decimal("0")
            if prev_month_data:
                prev_key = (flow_name, biz_type, brand)
                if prev_key in prev_month_data:
                    row["市场费上月占比"] = prev_month_data[prev_key]["market_fee_ratio"]
                else:
                    prev_key_no_brand = (flow_name, biz_type, "")
                    if prev_key_no_brand in prev_month_data:
                        row["市场费上月占比"] = prev_month_data[prev_key_no_brand]["market_fee_ratio"]

            # 技师工资占比 = 分摊后技师工资/分摊后产值*100%
            row["技师工资占比"] = pct(row["技师工资"], ratio_denominator)
            # 营销团队工资占比 = 分摊后营销团队工资/分摊后产值*100%
            row["营销团队工资占比"] = pct(row["营销团队工资"], ratio_denominator)
            # 人员工资本月占比 = 分摊后人员工资/分摊后产值*100%
            row["人员工资本月占比"] = pct(row["人员工资"], ratio_denominator)
            
            # 诊断日志:前5条记录显示比例计算结果
            if idx < 5 or (brand and idx < 20):
                logger.info(f"[比例计算] flow={flow_name}, bt={biz_type}, brand={brand}, "
                           f"tech_salary={row['技师工资']}, mkt_salary={row['营销团队工资']}, "
                           f"revenue={revenue}, gmv={gmv}, denominator={ratio_denominator}, "
                           f"tech_ratio={row['技师工资占比']}, mkt_ratio={row['营销团队工资占比']}")
            
            # 人员工资上月占比 - 从历史数据查询
            row["人员工资上月占比"] = Decimal("0")
            if prev_month_data:
                if prev_key in prev_month_data:
                    row["人员工资上月占比"] = prev_month_data[prev_key]["personnel_salary_ratio"]
                elif prev_key_no_brand in prev_month_data:
                    row["人员工资上月占比"] = prev_month_data[prev_key_no_brand]["personnel_salary_ratio"]

            # ---------- 计算毛利相关字段(2026-10 精简版) ----------
            # F公司毛利 - 固定为 0(不再计算)
            sp = (service_provider or "").strip()
            f_company_gross_profit = Decimal("0")
            row["F公司毛利"] = f_company_gross_profit
            
            # 2026-10 精简:统一公式,不再区分嘀加自营
            #   毛利 = 嘀加分润 - 房租水电 - 装修摊销
            gross_profit = dijia_profit - row["房租及水电费"] - renovation
            row["毛利"] = round_2(gross_profit)
            
            # 本月毛利率 = 毛利/GMV*100%
            row["毛利率本月"] = pct(gross_profit, gmv)
            
            # 上月毛利率 - 从历史数据查询
            row["毛利率上月"] = Decimal("0")
            if prev_month_data:
                if prev_key in prev_month_data:
                    row["毛利率上月"] = prev_month_data[prev_key].get("gross_profit_ratio", Decimal("0"))
                elif prev_key_no_brand in prev_month_data:
                    row["毛利率上月"] = prev_month_data[prev_key_no_brand].get("gross_profit_ratio", Decimal("0"))

            # 四舍五入所有金额
            # 2026-10 精简:移除市场费/外援施工/技师工资/营销团队工资/人员工资/门店耗材相关 key
            for key in ["房租及水电费", "F公司毛利", "毛利"]:
                row[key] = round_2(row[key])

            summary.append(row)
            idx += 1

        # 验证日志:检查龙联汽车科技的分摊结果
        target_flow = '龙联汽车科技(深圳)有限公司'
        logger.info(f"[成本汇总] 主循环完成,共 {len(summary)} 行记录")
        target_rows = [r for r in summary if target_flow in str(r.get("流量方名称", ""))]
        if target_rows:
            logger.info(f"[成本汇总-验证] 龙联汽车科技的分摊结果 ({len(target_rows)} 行):")
            for r in target_rows:
                logger.info(f"[成本汇总-验证]   flow={r['流量方名称']}, bt={r['业务类型']}, brand={r['品牌']}, "
                           f"ps={r.get('园区店', '')}, 外援施工={r['外援施工']}, "
                           f"技师工资={r['技师工资']}, 营销团队={r['营销团队工资']}, "
                           f"房租水电={r['房租及水电费']}")

        if _seen_sp:
            logger.info(f"[毛利计算] 服务商类型汇总: {_seen_sp}")

        # ---------- 处理园区店 GMV 分摊 ----------
        park_utility = [r for r in utility_results if r.get("__park_store__")]

        if park_utility:
            logger.info(f"[成本汇总] 处理园区店分摊:房租水电 {len(park_utility)} 条")

            # 按业务类型聚合园区店费用
            park_utility_agg = defaultdict(lambda: Decimal("0"))
            for p in park_utility:
                key = p["业务类型"].strip()
                park_utility_agg[key] += p["房租及水电费"]

            # 计算每个业务类型的总 GMV(跨所有流量方和品牌)
            biz_total_gmv = defaultdict(lambda: Decimal("0"))
            biz_brand_count = defaultdict(int)
            for s in summary:
                biz_total_gmv[s["业务类型"]] += s["GMV"]
                if s["品牌"]:
                    biz_brand_count[s["业务类型"]] += 1

            for biz, count in biz_brand_count.items():
                if count > 1:
                    logger.info(f"[成本汇总] 园区店多品牌分摊: 业务类型={biz}, 品牌数={count}, GMV合计={biz_total_gmv[biz]}")

            # 分摊到各品牌行(按 GMV 占比,跨流量方)
            for s in summary:
                biz = s["业务类型"]
                gmv = s["GMV"]
                flow = s["流量方名称"]
                brand = s.get("品牌", "")
                park = s.get("园区店", "")

                # 优先使用 ratio_lookup 精确查找
                db_ratio = None
                # 四元组精确匹配
                if (flow, biz, brand, park) in ratio_lookup:
                    db_ratio = ratio_lookup[(flow, biz, brand, park)]
                elif (flow, biz, brand, "") in ratio_lookup:
                    db_ratio = ratio_lookup[(flow, biz, brand, "")]
                elif settlement_map:
                    # 回退到 settlement_map
                    for (fn, bt, br), sv in settlement_map.items():
                        if fn == flow and bt == biz and sv.get("gmv_ratio") is not None:
                            db_ratio = sv["gmv_ratio"]
                            break

                brand_ratio = Decimal("0")
                if db_ratio is not None:
                    brand_ratio = Decimal(str(db_ratio))
                elif biz_total_gmv[biz] > 0 and gmv > 0:
                    brand_ratio = gmv / biz_total_gmv[biz]
                else:
                    logger.warning(f"[成本汇总分摊] 比例缺失且无GMV数据,流量方={flow}")

                if biz in park_utility_agg:
                    park_amount = park_utility_agg[biz] * brand_ratio
                    # 多园区店二次分摊
                    park_count = brand_park_counts.get((flow, biz, brand), 1)
                    if park_count > 1 and park:
                        pr_key = (flow, biz, brand, park)
                        park_ratio_val = park_ratio_lookup.get(pr_key)
                        if park_ratio_val is not None:
                            park_amount = park_amount * Decimal(str(float(park_ratio_val)))
                        else:
                            park_amount = park_amount / park_count
                    s["房租及水电费"] += round_2(park_amount)

            # 2026-10 精简:重新计算占比和毛利(已统一公式,不再区分嘀加自营)
            for s in summary:
                gmv = s["GMV"]
                revenue = s["产值"]
                # 确定比例计算的分母:优先使用产值,产值为0时使用GMV
                ratio_denominator = revenue if revenue > 0 else gmv
                if ratio_denominator <= 0:
                    ratio_denominator = Decimal("0")
                
                # 2026-10 精简:以下占比计算项不再有数据源,保留公式但值为 0
                # s["市场费本月占比"] = pct(s["市场费"], gmv)
                # s["技师工资占比"] = pct(s["技师工资"], ratio_denominator)
                # s["营销团队工资占比"] = pct(s["营销团队工资"], ratio_denominator)
                # s["人员工资本月占比"] = pct(s["人员工资"], ratio_denominator)
                
                # 2026-10 精简:F公司毛利固定为 0,毛利统一公式
                s["F公司毛利"] = Decimal("0")
                dijia_profit_sharing = s.get("嘀加分润", Decimal("0"))
                renovation_amort = s.get("装修摊销", Decimal("0"))
                gp = dijia_profit_sharing - s["房租及水电费"] - renovation_amort
                s["毛利"] = round_2(gp)
                s["毛利率本月"] = pct(gp, gmv)

        # ---------- 格式化输出 ----------
        logger.info(f"[成本汇总] 生成完成,共 {len(summary)} 行数据")
        return summary

    # ========================================================
    # 写入预算达成表
    # ========================================================

    @staticmethod
    def _safe_float(val):
        """安全转换为 float,处理 Decimal、None、空字符串等"""
        if val is None or val == '' or val == 'nan':
            return 0.0
        if isinstance(val, Decimal):
            return float(val)
        try:
            return float(val)
        except (ValueError, TypeError):
            return 0.0

    @staticmethod
    def _clamp_ratio(val):
        """限制比例值在 DECIMAL(5,2) 范围内 (-999.99 ~ 999.99)"""
        return max(-999.99, min(999.99, val))

    def _execute_batch_update(self, task_id, month, data_list, update_columns, log_prefix=""):
        """
        通用批量更新方法,只更新指定字段。

        Args:
            task_id: 任务ID
            month: 月份
            data_list: 数据列表,每项包含流量方名称、业务类型、品牌等
            update_columns: 需要更新的字段列表
            log_prefix: 日志前缀(如"市场费"、"人力成本"等)
        """
        if not data_list:
            logger.info(f"[{log_prefix}] 无数据需要更新")
            return 0

        # 构建参数列表
        params_list = []
        for row in data_list:
            traffic_name = (row.get("流量方名称", "") or "").strip()
            business_type = (row.get("业务类型", "") or "").strip()
            brand = (row.get("品牌", "") or "").strip()
            park_store = (row.get("园区店", "") or "").strip()

            params = {
                'task_id': task_id,
                'stat_month': month,
                'traffic_name': traffic_name,
                'business_type': business_type,
                'brand': brand,
            }
            if park_store:
                params['park_store'] = park_store

            # 只添加需要更新的字段
            for col in update_columns:
                # 字段名映射(数据库列名 -> Excel 列名)
                field_mapping = {
                    'market_fee': '市场费',
                    'market_fee_ratio_current': '市场费本月占比',
                    'market_fee_ratio_previous': '市场费上月占比',
                    'personnel_salary': '人员工资',
                    'external_construction': '外援施工',
                    'technician_salary': '技师工资',
                    'technician_salary_ratio': '技师工资占比',
                    'marketing_team_salary': '营销团队工资',
                    'marketing_team_salary_ratio': '营销团队工资占比',
                    'personnel_salary_ratio_current': '人员工资本月占比',
                    'personnel_salary_ratio_previous': '人员工资上月占比',
                    'rent_utilities': '房租及水电费',
                    'f_company_gross_profit': 'F公司毛利',
                    'gross_profit': '毛利',
                    'gross_profit_ratio_current': '毛利率本月',
                    'gross_profit_ratio_previous': '毛利率上月',
                }
                excel_col = field_mapping.get(col, col)
                params[col] = self._safe_float(row.get(excel_col, Decimal("0")))

            params_list.append(params)

        # 构建 UPDATE SQL(公共部分)
        table = BizBudgetAchieve.__tablename__
        set_clause = ', '.join([f'{col}=:{col}' for col in update_columns])
        set_clause += ', updated_at = CURRENT_TIMESTAMP'

        # 执行批量更新
        conn = db.engine.connect()
        updated_count = 0
        try:
            trans = conn.begin()
            for params in params_list:
                # 动态构建 WHERE 条件
                where_columns = ['task_id', 'stat_month', 'traffic_name', 'business_type', 'brand']
                if 'park_store' in params:
                    where_columns.append('park_store')
                where_clause = ' AND '.join([f'{col}=:{col}' for col in where_columns])

                sql_text = text(
                    f"UPDATE {table} SET {set_clause} "
                    f"WHERE {where_clause}"
                )

                bind_params = {}
                for col in where_columns + update_columns:
                    bind_params[col] = params.get(col, 0)
                if not bind_params.get('brand'):
                    bind_params['brand'] = ''
                result = conn.execute(sql_text, bind_params)
                if result.rowcount > 0:
                    updated_count += 1
            trans.commit()
            total = len(params_list)
            rate = updated_count / total * 100 if total > 0 else 0
            logger.info(f"[{log_prefix}] Update 成功,共处理 {total} 条,实际更新 {updated_count} 条,成功率 {rate:.1f}%")
        except Exception as e:
            trans.rollback()
            logger.error(f"[{log_prefix}] Update 失败: {str(e)}")
            raise
        finally:
            conn.close()

        return updated_count

    def _update_market_fee_by_id(self, task_id, month, market_fee_data):
        logger.info(f"[市场费更新] ===v3代码执行=== 开始按ID更新,task_id={task_id}, month={month}")

        rows = db.session.execute(
            text("SELECT id, traffic_name, business_type, brand, park_store, gmv_ratio, gmv "
                 "FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
            {"tid": task_id, "sm": month}
        ).fetchall()

        logger.info(f"[市场费更新] 查询到 {len(rows)} 条记录")

        # 诊断:查询广西恒为的数据库实际数据
        henhua_rows = [r for r in rows if "广西恒为" in str(r.traffic_name or "") or "恒为" in str(r.traffic_name or "")]
        if henhua_rows:
            logger.info(f"[市场费诊断] 广西恒为在数据库中共有 {len(henhua_rows)} 条记录")
            logger.info(f"[市场费诊断] 广西恒为品牌分布: {set(r.brand or '' for r in henhua_rows)}")
            for r in henhua_rows[:10]:  # 只打印前10条
                logger.info(f"[市场费诊断]   id={r.id}, brand={r.brand}, park_store={r.park_store}, gmv_ratio={float(r.gmv_ratio or 0)}, gmv={float(r.gmv or 0)}")
            if len(henhua_rows) > 10:
                logger.info(f"[市场费诊断]   ... 还有 {len(henhua_rows) - 10} 条记录")

        if not rows:
            logger.info("[市场费更新] 无数据需要更新")
            return 0

        year, month_str = month.split("-")
        year = int(year)
        month_int = int(month_str)
        if month_int == 1:
            prev_year = year - 1
            prev_month = 12
        else:
            prev_year = year
            prev_month = month_int - 1
        prev_month_str = f"{prev_year}-{prev_month:02d}"

        prev_records = db.session.execute(
            text("SELECT traffic_name, business_type, brand, park_store, market_fee, gmv "
                 "FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
            {"tid": task_id, "sm": prev_month_str}
        ).fetchall()

        prev_month_map = {}
        for r in prev_records:
            key = (r.traffic_name or "", r.business_type or "", r.brand or "", r.park_store or "")
            prev_month_map[key] = {
                "market_fee": float(r.market_fee or 0),
                "gmv": float(r.gmv or 0),
            }

        logger.info(f"[市场费更新] 上月数据 {len(prev_month_map)} 条")

        # 按 (流量方, 业务类型, 品牌) 三元组分组,每个品牌独立处理
        fee_by_flow_bt_brand = {}
        for item in market_fee_data:
            flow = item["流量方名称"]
            bt = item["业务类型"]
            brand = item["品牌"]
            fee = item["市场费"]
            
            key = (flow, bt, brand)
            if key not in fee_by_flow_bt_brand:
                fee_by_flow_bt_brand[key] = Decimal("0")
            fee_by_flow_bt_brand[key] += fee

        logger.info(f"[市场费更新] 市场费按(流量方+业务类型+品牌)分组后共 {len(fee_by_flow_bt_brand)} 组")
        for (flow, bt, brand), fee in fee_by_flow_bt_brand.items():
            logger.info(f"[市场费更新] 分组: 流量方='{flow}', 业务类型='{bt}', 品牌='{brand}', 金额={fee}")

        # 记录数据库中的流量方名称列表
        db_flow_names_all = set(r.traffic_name for r in rows)
        logger.info(f"[市场费更新] 数据库中所有流量方名称: {len(db_flow_names_all)} 个")
        # 如果有广西恒为相关的,打印出来
        henhua_in_db = [fn for fn in db_flow_names_all if "恒为" in str(fn)]
        if henhua_in_db:
            logger.info(f"[市场费诊断] 数据库中恒为相关的流量方名称: {henhua_in_db}")

        # 记录数据库中的品牌分布
        db_brands = {}
        for r in rows:
            key = (r.traffic_name, r.business_type)
            if key not in db_brands:
                db_brands[key] = set()
            db_brands[key].add(r.brand or "")
        logger.info(f"[市场费更新] 数据库品牌分布: {dict(db_brands)}")

        table = BizBudgetAchieve.__tablename__
        sql = text(f"""
            UPDATE {table}
            SET market_fee = :market_fee,
                market_fee_ratio_current = :market_fee_ratio_current,
                market_fee_ratio_previous = :market_fee_ratio_previous,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = :id
        """)

        conn = db.engine.connect()
        count = 0
        try:
            trans = conn.begin()
            for (flow, bt, brand), total_fee in fee_by_flow_bt_brand.items():
                
                # 收集所有可能的流量方名称
                all_possible_flows = {flow}
                original_names = set()
                for item in market_fee_data:
                    if item["流量方名称"] == flow:
                        orig = item.get("原始名称", "")
                        if orig and orig != flow:
                            original_names.add(orig)
                all_possible_flows.update(original_names)
                
                # 匹配数据库行:按 (flow, bt, brand) 精确匹配
                matching_rows = []
                for try_flow in all_possible_flows:
                    flow_rows = [r for r in rows if r.traffic_name == try_flow and r.business_type == bt and (r.brand or "") == brand]
                    if flow_rows:
                        matching_rows.extend(flow_rows)
                        if try_flow != flow:
                            logger.info(f"[市场费分摊] 使用原始名称匹配: '{try_flow}' (标准名='{flow}'), 品牌='{brand}', 匹配{len(flow_rows)}行")
                
                if not matching_rows:
                    # 尝试模糊匹配流量方名称
                    db_flow_names = set(r.traffic_name for r in rows)
                    fuzzy_matches = [fn for fn in db_flow_names if flow in str(fn) or str(fn) in flow]
                    if fuzzy_matches:
                        logger.info(f"[市场费分摊] flow='{flow}' 精确匹配失败, 模糊匹配到: {fuzzy_matches[:5]}")
                        for fuzzy_flow in fuzzy_matches:
                            flow_rows = [r for r in rows if r.traffic_name == fuzzy_flow and r.business_type == bt and (r.brand or "") == brand]
                            matching_rows.extend(flow_rows)
                            if flow_rows:
                                logger.info(f"[市场费分摊] 使用模糊匹配名称: '{fuzzy_flow}', 品牌='{brand}', 匹配{len(flow_rows)}行")
                                
                if not matching_rows and brand == "未知品牌":
                    # brand="未知品牌" fallback: 匹配同 (flow, biz) 下的所有 DB 行,按 gmv_ratio 分摊
                    for try_flow in all_possible_flows:
                        flow_rows = [r for r in rows if r.traffic_name == try_flow and r.business_type == bt]
                        if flow_rows:
                            matching_rows.extend(flow_rows)
                    if not matching_rows:
                        # 再试模糊匹配
                        db_flow_names = set(r.traffic_name for r in rows)
                        fuzzy_matches = [fn for fn in db_flow_names if flow in str(fn) or str(fn) in flow]
                        for fuzzy_flow in fuzzy_matches:
                            flow_rows = [r for r in rows if r.traffic_name == fuzzy_flow and r.business_type == bt]
                            matching_rows.extend(flow_rows)
                    if matching_rows:
                        logger.info(f"[市场费分摊·fallback] brand='未知品牌' → 匹配同 (flow={flow}, biz={bt}) 下所有 DB 行={len(matching_rows)}, 按gmv_ratio分摊")
                    
                if not matching_rows:
                    logger.warning(f"[市场费分摊] 流量方='{flow}', 业务类型='{bt}', 品牌='{brand}' 无匹配数据库行,跳过该品牌")
                    continue
                
                logger.info(f"[市场费分摊] 匹配: 流量方='{flow}', 业务类型='{bt}', 品牌='{brand}', 金额={total_fee}, 匹配{len(matching_rows)}行")
                
                # 诊断日志
                if "广西恒为" in flow or "恒为" in flow:
                    logger.info(f"[市场费诊断] 品牌分摊 flow={flow}, bt={bt}, brand={brand}: total_fee={total_fee}, 匹配行数={len(matching_rows)}")
                    for r in matching_rows:
                        logger.info(f"[市场费诊断]   行id={r.id}, gmv_ratio={float(r.gmv_ratio or 0)}, gmv={float(r.gmv or 0)}, brand={r.brand}")

                # 分配市场费到各行
                allocated_sum = Decimal("0")
                if len(matching_rows) == 1:
                    # 单条匹配:直接写入,无需分摊
                    db_row = matching_rows[0]
                    row_id = db_row.id
                    gmv = float(db_row.gmv or 0)
                    db_brand = db_row.brand or ""
                    park_store = db_row.park_store or ""

                    allocated_fee = total_fee
                    allocated_sum = allocated_fee

                    if gmv != 0:
                        market_fee_ratio_current = self._clamp_ratio(round(float(allocated_fee) / gmv * 100, 2))
                    else:
                        market_fee_ratio_current = 0.0

                    prev_key = (flow, bt, db_brand, park_store)
                    prev_data = prev_month_map.get(prev_key, {})
                    prev_market_fee = prev_data.get("market_fee", 0)
                    prev_gmv = prev_data.get("gmv", 0)
                    if prev_gmv != 0:
                        market_fee_ratio_previous = self._clamp_ratio(round(prev_market_fee / prev_gmv * 100, 2))
                    else:
                        market_fee_ratio_previous = 0.0

                    conn.execute(sql, {
                        'id': row_id,
                        'market_fee': float(allocated_fee),
                        'market_fee_ratio_current': market_fee_ratio_current,
                        'market_fee_ratio_previous': market_fee_ratio_previous,
                    })
                    count += 1
                    
                    if "广西恒为" in flow or "恒为" in flow:
                        logger.info(f"[市场费诊断]   单条写入: id={row_id}, market_fee={allocated_fee}")
                else:
                    # 多条匹配(同品牌不同 park_store):按 gmv_ratio 分摊
                    total_gmv_ratio = sum(float(r.gmv_ratio or 0) for r in matching_rows)
                    first_row_allocated_fee = None
                    
                    for i, db_row in enumerate(matching_rows):
                        row_id = db_row.id
                        gmv_ratio = float(db_row.gmv_ratio or 0)
                        gmv = float(db_row.gmv or 0)
                        db_brand = db_row.brand or ""
                        park_store = db_row.park_store or ""

                        if total_gmv_ratio > 0:
                            allocated_fee = (total_fee * Decimal(str(gmv_ratio / total_gmv_ratio))).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
                        else:
                            allocated_fee = (total_fee / len(matching_rows)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
                        
                        allocated_sum += allocated_fee
                        if i == 0:
                            first_row_allocated_fee = allocated_fee

                        if gmv != 0:
                            market_fee_ratio_current = self._clamp_ratio(round(float(allocated_fee) / gmv * 100, 2))
                        else:
                            market_fee_ratio_current = 0.0

                        prev_key = (flow, bt, db_brand, park_store)
                        prev_data = prev_month_map.get(prev_key, {})
                        prev_market_fee = prev_data.get("market_fee", 0)
                        prev_gmv = prev_data.get("gmv", 0)
                        if prev_gmv != 0:
                            market_fee_ratio_previous = self._clamp_ratio(round(prev_market_fee / prev_gmv * 100, 2))
                        else:
                            market_fee_ratio_previous = 0.0

                        conn.execute(sql, {
                            'id': row_id,
                            'market_fee': float(allocated_fee),
                            'market_fee_ratio_current': market_fee_ratio_current,
                            'market_fee_ratio_previous': market_fee_ratio_previous,
                        })
                        count += 1
                        
                        if "广西恒为" in flow or "恒为" in flow:
                            logger.info(f"[市场费诊断]   分摊写入: id={row_id}, market_fee={allocated_fee}, gmv_ratio={gmv_ratio}")

                    # 尾差归并到第一行(使用实际分配值,避免引用旧的 SELECT 值)
                    first_row = matching_rows[0]
                    diff = total_fee - allocated_sum
                    if diff != 0 and first_row_allocated_fee is not None:
                        corrected_fee = first_row_allocated_fee + diff
                        first_row_gmv = float(first_row.gmv or 0)
                        if first_row_gmv != 0:
                            corrected_ratio_current = self._clamp_ratio(round(float(corrected_fee) / first_row_gmv * 100, 2))
                        else:
                            corrected_ratio_current = 0.0
                        conn.execute(sql, {
                            'id': first_row.id,
                            'market_fee': float(corrected_fee),
                            'market_fee_ratio_current': corrected_ratio_current,
                            'market_fee_ratio_previous': 0,
                        })
                        if "广西恒为" in flow or "恒为" in flow:
                            logger.info(f"[市场费诊断]   尾差归并: diff={diff}, 加到第一行id={first_row.id}, 修正后market_fee={corrected_fee}")

            trans.commit()
            logger.info(f"[市场费更新] 更新完成,共更新 {count} 行")
            
            # 回查验证:检查广西恒为的写入结果(按品牌分组)
            verify_sql = text("SELECT id, brand, gmv_ratio, market_fee FROM biz_budget_achieve "
                             "WHERE task_id=:tid AND traffic_name LIKE '%恒为%' AND business_type='1.1' ORDER BY brand")
            verify_rows = db.session.execute(verify_sql, {"tid": task_id}).fetchall()
            if verify_rows:
                brand_summary = {}
                for r in verify_rows:
                    b = r.brand or ""
                    if b not in brand_summary:
                        brand_summary[b] = {"total": 0, "rows": []}
                    brand_summary[b]["total"] += float(r.market_fee or 0)
                    brand_summary[b]["rows"].append(r)
                logger.info(f"[市场费回查] 广西恒为1.1业务: 共{len(verify_rows)}行, {len(brand_summary)}个品牌")
                for brand_name, info in brand_summary.items():
                    logger.info(f"[市场费回查] 品牌='{brand_name}': {len(info['rows'])}行, market_fee总和={info['total']}")
                    for r in info["rows"][:3]:
                        logger.info(f"[市场费回查]   id={r.id}, gmv_ratio={float(r.gmv_ratio or 0)}, market_fee={float(r.market_fee or 0)}")
                    if len(info["rows"]) > 3:
                        logger.info(f"[市场费回查]   ... 还有{len(info['rows']) - 3}行")
        except Exception as e:
            trans.rollback()
            logger.error(f"[市场费更新] 更新失败: {str(e)}")
            raise
        finally:
            conn.close()

        return count

    def _update_market_fee_to_db(self, task_id, month, data_list):
        """只更新市场费相关字段"""
        update_columns = [
            'market_fee', 'market_fee_ratio_current', 'market_fee_ratio_previous',
        ]
        return self._execute_batch_update(task_id, month, data_list, update_columns, log_prefix="市场费")

    def _update_labor_cost_to_db(self, task_id, month, data_list):
        """只更新人力成本相关字段"""
        update_columns = [
            'personnel_salary', 'technician_salary', 'technician_salary_ratio',
            'marketing_team_salary', 'marketing_team_salary_ratio',
            'personnel_salary_ratio_current', 'personnel_salary_ratio_previous',
        ]
        return self._execute_batch_update(task_id, month, data_list, update_columns, log_prefix="人力成本")

    def _update_labor_ratios_to_db(self, task_id, month, data_list):
        """
        更新人员工资汇总值及占比字段。
        这些字段在 _build_cost_summary 中计算,需要与产值/GMV关联。
        """
        update_columns = [
            'personnel_salary', 'technician_salary_ratio',
            'marketing_team_salary_ratio',
            'personnel_salary_ratio_current', 'personnel_salary_ratio_previous',
        ]
        return self._execute_batch_update(task_id, month, data_list, update_columns, log_prefix="人力成本汇总")

    def _update_labor_ratios_by_id(self, task_id, month):
        logger.info(f"[人员工资占比更新] 开始按ID更新,task_id={task_id}, month={month}")

        rows = db.session.execute(
            text("SELECT id, external_construction, technician_salary, marketing_team_salary, "
                 "revenue, gmv, traffic_name, business_type, brand, park_store "
                 "FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
            {"tid": task_id, "sm": month}
        ).fetchall()

        logger.info(f"[人员工资占比更新] 查询到 {len(rows)} 条记录")

        if not rows:
            logger.info("[人员工资占比更新] 无数据需要更新")
            return 0

        year, month_str = month.split("-")
        year = int(year)
        month_int = int(month_str)
        if month_int == 1:
            prev_year = year - 1
            prev_month = 12
        else:
            prev_year = year
            prev_month = month_int - 1
        prev_month_str = f"{prev_year}-{prev_month:02d}"

        prev_records = db.session.execute(
            text("SELECT traffic_name, business_type, brand, park_store, personnel_salary, gmv "
                 "FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
            {"tid": task_id, "sm": prev_month_str}
        ).fetchall()

        prev_month_map = {}
        for r in prev_records:
            key = (r.traffic_name or "", r.business_type or "", r.brand or "", r.park_store or "")
            prev_month_map[key] = {
                "personnel_salary": float(r.personnel_salary or 0),
                "gmv": float(r.gmv or 0),
            }

        logger.info(f"[人员工资占比更新] 上月数据 {len(prev_month_map)} 条")

        table = BizBudgetAchieve.__tablename__
        sql = text(f"""
            UPDATE {table}
            SET personnel_salary = :personnel_salary,
                technician_salary_ratio = :technician_salary_ratio,
                marketing_team_salary_ratio = :marketing_team_salary_ratio,
                personnel_salary_ratio_current = :personnel_salary_ratio_current,
                personnel_salary_ratio_previous = :personnel_salary_ratio_previous,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = :id
        """)

        conn = db.engine.connect()
        updated_count = 0
        try:
            trans = conn.begin()
            for row in rows:
                row_id = row.id

                external_construction = float(row.external_construction or 0)
                technician_salary = float(row.technician_salary or 0)
                marketing_team_salary = float(row.marketing_team_salary or 0)
                revenue = float(row.revenue or 0)
                gmv = float(row.gmv or 0)
                traffic_name = row.traffic_name or ""
                business_type = row.business_type or ""
                brand = row.brand or ""
                park_store = row.park_store or ""

                personnel_salary = round(external_construction + technician_salary + marketing_team_salary, 2)

                denominator = revenue if revenue != 0 else gmv

                if denominator != 0:
                    technician_salary_ratio = self._clamp_ratio(round(technician_salary / denominator * 100, 2))
                else:
                    technician_salary_ratio = 0.0

                if denominator != 0:
                    marketing_team_salary_ratio = self._clamp_ratio(round(marketing_team_salary / denominator * 100, 2))
                else:
                    marketing_team_salary_ratio = 0.0

                if denominator != 0:
                    personnel_salary_ratio_current = self._clamp_ratio(round(personnel_salary / denominator * 100, 2))
                else:
                    personnel_salary_ratio_current = 0.0

                prev_key = (traffic_name, business_type, brand, park_store)
                prev_data = prev_month_map.get(prev_key, {})
                prev_personnel_salary = prev_data.get("personnel_salary", 0)
                prev_gmv = prev_data.get("gmv", 0)
                if prev_gmv != 0:
                    personnel_salary_ratio_previous = self._clamp_ratio(round(prev_personnel_salary / prev_gmv * 100, 2))
                else:
                    personnel_salary_ratio_previous = 0.0

                conn.execute(sql, {
                    'id': row_id,
                    'personnel_salary': personnel_salary,
                    'technician_salary_ratio': technician_salary_ratio,
                    'marketing_team_salary_ratio': marketing_team_salary_ratio,
                    'personnel_salary_ratio_current': personnel_salary_ratio_current,
                    'personnel_salary_ratio_previous': personnel_salary_ratio_previous,
                })
                updated_count += 1

            trans.commit()
            logger.info(f"[人员工资占比更新] 更新完成,共更新 {updated_count} 行")
        except Exception as e:
            trans.rollback()
            logger.error(f"[人员工资占比更新] 更新失败: {str(e)}")
            raise
        finally:
            conn.close()

        return updated_count

    def _update_rent_utilities_by_target(self, conn, table, task_id, month, target_name, business_type, fee, target_type):
        """
        按目标类型(流量方/园区店)查询匹配行,并用 分账结果 * gmv_ratio 更新数据库
        符合用户需求:
        1. 根据目标类型查询 biz_budget_achieve 表(不关联品牌)
        2. 获取 id, gmv_ratio
        3. 更新 rent_utilities = 分账结果 * gmv_ratio
        
        用户SQL示例:
        SELECT id, gmv_ratio FROM biz_budget_achieve 
        WHERE traffic_name IN (?) AND business_type = ? AND task_id = ?
        
        UPDATE biz_budget_achieve SET rent_utilities = 分账结果 * gmv_ratio WHERE id = ?
        """
        from sqlalchemy import text
        updated_count = 0

        if target_type == 'flow':
            # 流量方查询(不关联品牌)
            query_sql = text("""
                SELECT id, gmv_ratio
                FROM biz_budget_achieve
                WHERE traffic_name = :target_name
                AND business_type = :biz_type
                AND task_id = :task_id
            """)
            params = {"target_name": target_name, "biz_type": business_type, "task_id": task_id}
        else:
            # 园区店查询
            query_sql = text("""
                SELECT id, gmv_ratio
                FROM biz_budget_achieve
                WHERE park_store = :target_name
                AND business_type = :biz_type
                AND task_id = :task_id
            """)
            params = {"target_name": target_name, "biz_type": business_type, "task_id": task_id}

        try:
            rows = conn.execute(query_sql, params).fetchall()
            logger.info(f"[房租水电GMV写入] 查询到 {len(rows)} 条记录: target={target_name}, type={target_type}")

            for row in rows:
                row_id, gmv_ratio = row
                # 分账结果 * gmv_ratio
                ratio = Decimal(str(gmv_ratio)) if gmv_ratio is not None else Decimal("1")
                rent_utilities = Decimal(str(fee)) * ratio

                update_sql = text(f"""
                    UPDATE {table}
                    SET rent_utilities = :rent_utilities, updated_at = CURRENT_TIMESTAMP
                    WHERE id = :row_id
                """)
                conn.execute(update_sql, {"rent_utilities": float(rent_utilities), "row_id": row_id})
                updated_count += 1
                logger.info(f"[房租水电GMV写入] id={row_id}, gmv_ratio={gmv_ratio}, fee={fee}, rent_utilities={rent_utilities}")

        except Exception as e:
            logger.error(f"[房租水电GMV写入] 查询失败: target={target_name}, type={target_type}, error={e}")

        return updated_count

    def _update_utility_fee_to_db(self, task_id, month, data_list):
        """只更新房租水电费相关字段;对多 park_store 场景按 gmv_ratio 分摊写入
        
        Returns:
            tuple: (updated_count, failed_amount)
                - updated_count: 实际更新的行数
                - failed_amount: 写库时 DB 查不到对应 traffic_name/park_store 的金额(=应进 unmatched 的部分)
        """
        update_columns = ['rent_utilities']

        if not data_list:
            logger.info("[房租水电费] 无数据需要更新")
            return 0, Decimal('0')

        ratio_index = self._load_db_ratio_index(task_id, month)

        table = BizBudgetAchieve.__tablename__
        conn = db.engine.connect()
        updated_count = 0
        failed_amount = Decimal('0')   # 写库失败的金额(DB 查不到行的)
        try:
            trans = conn.begin()
            for row in data_list:
                traffic_name = (row.get("流量方名称", "") or "").strip()
                business_type = (row.get("业务类型", "") or "").strip()
                brand = (row.get("品牌", "") or "").strip()
                brand_level_fee = self._safe_float(row.get("房租及水电费", Decimal("0")))
                is_gmv_allocated = row.get("__gmv_allocated__", False)
                key = (traffic_name, business_type, brand)

                if not traffic_name or not business_type or brand_level_fee <= 0:
                    continue

                if is_gmv_allocated:
                    # 已GMV分摊的记录,按分账结果 * gmv_ratio 更新
                    target_type = row.get("target_type", "flow")
                    updated_rows = self._update_rent_utilities_by_target(
                        conn, table, task_id, month, traffic_name, business_type, 
                        brand_level_fee, target_type
                    )
                    updated_count += updated_rows
                    if updated_rows > 0:
                        logger.info(f"[房租水电GMV写入] flow={traffic_name}, biz={business_type}, fee={brand_level_fee}, target_type={target_type}, updated_rows={updated_rows}")
                    else:
                        logger.warning(f"[房租水电GMV写入] 未找到匹配行: flow={traffic_name}, biz={business_type}, target_type={target_type}, fee={brand_level_fee}")
                        failed_amount += Decimal(str(brand_level_fee))   # ← 新增:写库失败 → 计入差额
                    continue

                if key in ratio_index and len(ratio_index[key]) > 1:
                    rows_info = ratio_index[key]
                    total_ratio = sum(r for _, _, r in rows_info)

                    # 按 gmv_ratio 分摊到每行,最后一行吃掉舍入误差
                    allocated = Decimal("0")
                    for i, (row_id, park_store, gmv_r) in enumerate(rows_info):
                        is_last = (i == len(rows_info) - 1)
                        if is_last:
                            share = round_2(Decimal(str(brand_level_fee)) - allocated)
                        else:
                            if total_ratio > 0 and gmv_r is not None:
                                share = round_2(Decimal(str(brand_level_fee)) * gmv_r)
                            else:
                                share = round_2(Decimal(str(brand_level_fee)) / Decimal(str(len(rows_info))))
                        allocated += share

                        conn.execute(
                            text(f"UPDATE {table} SET rent_utilities=:ru, updated_at=CURRENT_TIMESTAMP WHERE id=:id"),
                            {'ru': float(share), 'id': row_id}
                        )
                        updated_count += 1
                        logger.info(f"[房租水电分摊写入] id={row_id}, park_store={park_store}, gmv_ratio={gmv_r}, share_amount={float(share)}")

                    logger.info(f"[房租水电分摊验证] flow={traffic_name}, biz={business_type}, brand={brand}, "
                                f"brand_level_fee={brand_level_fee}, sum_after={float(allocated)}")
                else:
                    # 单 park_store 场景:整笔写入
                    sql_text = text(
                        f"UPDATE {table} SET rent_utilities=:ru, updated_at=CURRENT_TIMESTAMP "
                        f"WHERE task_id=:tid AND stat_month=:sm AND traffic_name=:tn AND business_type=:bt AND brand=:br"
                    )
                    brand_val = brand if brand else ''
                    result = conn.execute(sql_text, {
                        'ru': brand_level_fee, 'tid': task_id, 'sm': month,
                        'tn': traffic_name, 'bt': business_type, 'br': brand_val
                    })
                    if result.rowcount > 0:
                        updated_count += 1
            trans.commit()
            total = len(data_list)
            rate = updated_count / total * 100 if total > 0 else 0
            logger.info(f"[房租水电费] Update 成功,共处理 {total} 条,实际更新 {updated_count} 条,成功率 {rate:.1f}%")
            if failed_amount > 0:
                logger.warning(f"[房租水电费] 写库失败需补入差额: failed_amount={failed_amount}")
        except Exception as e:
            trans.rollback()
            logger.error(f"[房租水电费] Update 失败: {str(e)}")
            raise
        finally:
            conn.close()

        return updated_count, failed_amount

    # ========================================================
    # 通用分摊更新方法:按 gmv_ratio 分摊 + 按主键id直接更新
    # ========================================================
    
    def _allocate_and_update_by_id(self, task_id, month, parsed_data, field_configs):
        """
        通用分摊更新方法。
        按 (traffic_name, business_type) 查找 biz_budget_achieve 中的所有行,
        按 gmv_ratio 分摊金额到对应行,直接按主键 id UPDATE。
        
        参数:
            task_id: 任务ID
            month: 月份 (YYYY-MM)
            parsed_data: Dict,key 为 (流量方, 业务类型) 或 (流量方, 业务类型, 品牌),value 为金额或 {字段: 金额}
            field_configs: List[Dict],每个配置:
                - 'value_key': 解析数据 value 中的键(如果 value 是 dict)
                - 'column': 数据库列名
                - 'label': 日志标签
        
        返回:
            (分摊前总金额, 分摊后总金额, 更新行数)
        """
        # 诊断:写库前查 DB 当前值(用 pymysql 直连,绕过 SQLAlchemy)
        try:
            import pymysql as _pym
            _diag = _pym.connect(host=Config.MYSQL_HOST, port=int(Config.MYSQL_PORT or 3306),
                                 user=Config.MYSQL_USER, password=Config.MYSQL_PASSWORD,
                                 db=Config.MYSQL_DB, charset='utf8mb4', autocommit=True)
            _dc = _diag.cursor()
            _cols = [c['column'] for c in field_configs]
            _dc.execute(f"SELECT {', '.join(f'SUM({c})' for c in _cols)} FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (task_id, month))
            _dv = _dc.fetchone()
            logger.info(f"[分摊更新-诊断] 写库前 DB sum: {dict(zip(_cols, _dv))}")
            _diag.close()
        except Exception as _de:
            logger.warning(f"[分摊更新-诊断] 写库前查询失败: {_de}")
        
        if not parsed_data:
            logger.info(f"[分摊更新] 无数据需要处理")
            return Decimal("0"), Decimal("0"), 0, {}
        
        # 1. 加载 biz_budget_achieve 所有行
        table = BizBudgetAchieve.__tablename__
        try:
            rows = db.session.execute(
                text("SELECT id, traffic_name, business_type, brand, park_store, gmv_ratio, service_provider FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
                {"tid": task_id, "sm": month}
            ).fetchall()
            
            # 构建索引: (traffic_name, business_type) → [(id, brand, park_store, gmv_ratio, is_dijia), ...]
            flow_biz_index = {}
            for r in rows:
                row_id, traffic_name, business_type, brand, park_store, gmv_ratio, service_provider = r
                _flow = (traffic_name or "").strip()
                _biz = (business_type or "").strip()
                key = (_flow, _biz)
                if key not in flow_biz_index:
                    flow_biz_index[key] = []
                sp = (service_provider or "").strip()
                row_info = {
                    'id': row_id,
                    'brand': (brand or "").strip(),
                    'park_store': (park_store or "").strip(),
                    'gmv_ratio': Decimal(str(gmv_ratio)) if gmv_ratio is not None else None,
                    'is_dijia': "嘀加" in sp,
                }
                flow_biz_index[key].append(row_info)
            
            logger.info(f"[分摊更新] 加载数据库行: {len(rows)} 条, 索引键: {len(flow_biz_index)} 个")
        except Exception as e:
            logger.error(f"[分摊更新] 加载数据库行失败: {e}")
            raise
        
        # 2. 分摊并更新
        total_input = Decimal("0")
        total_output = Decimal("0")
        updated_count = 0
        # 分字段统计 skip 金额(无匹配 DB 行导致钱丢失 → 需合并进 unmatched)
        skipped_by_col = {cfg['column']: Decimal("0") for cfg in field_configs}
        # 用 pymysql 直连(绕过 SQLAlchemy 在 Flask app context 下的事务管理问题)
        import pymysql as _pym
        _write_conn = _pym.connect(host=Config.MYSQL_HOST, port=int(Config.MYSQL_PORT or 3306),
                                   user=Config.MYSQL_USER, password=Config.MYSQL_PASSWORD,
                                   db=Config.MYSQL_DB, charset='utf8mb4', autocommit=False)
        _write_cur = _write_conn.cursor()
        
        try:
            for data_key, value in parsed_data.items():
                # 解析 key
                if isinstance(data_key, tuple) and len(data_key) >= 2:
                    flow_name = (data_key[0] or "").strip()
                    biz_type = (data_key[1] or "").strip()
                else:
                    continue
                
                # 获取要更新的字段值
                for config in field_configs:
                    if isinstance(value, dict):
                        field_value = value.get(config['value_key'], Decimal("0"))
                    else:
                        field_value = value
                    
                    field_value = Decimal(str(field_value)) if not isinstance(field_value, Decimal) else field_value
                    if field_value == 0:
                        continue
                    
                    total_input += field_value
                    column = config['column']
                    label = config['label']
                    
                    # 查找对应的数据库行
                    db_rows = flow_biz_index.get((flow_name, biz_type), [])
                    
                    if not db_rows:
                        logger.warning(f"[{label}] 未找到匹配的数据库行: flow={flow_name}, biz={biz_type}, 跳过金额={field_value}")
                        skipped_by_col[column] += field_value
                        continue
                    
                    # === 规则2验证 + 服务商过滤层 ===
                    # 优先使用嘀加 brand 行;只有全是非嘀加时才回退全量
                    dijia_rows = [r for r in db_rows if r.get('is_dijia')]
                    if dijia_rows:
                        target_rows = dijia_rows
                    else:
                        target_rows = db_rows
                    
                    # 规则2验证日志:多条记录 + 嘀加过滤
                    if len(db_rows) > 1:
                        logger.info(f"[规则2命中] flow={flow_name}, biz={biz_type}, DB 原始行={len(db_rows)}, "
                                    f"嘀加行={len(dijia_rows)}, 最终 target={len(target_rows)}, 金额={field_value}")
                    
                    # === 规则4外援施工专属验证日志 ===
                    if label == "外援施工费":
                        excluded = len(db_rows) - len(dijia_rows)
                        logger.info(f"[外援施工费·规则4命中] flow={flow_name}, biz={biz_type}, "
                                    f"DB原始行={len(db_rows)}, 嘀加行={len(dijia_rows)}, "
                                    f"非嘀加行排除={excluded}, 最终target={len(target_rows)}, 金额={field_value}")
                    
                    # 在 target_rows 内按 gmv_ratio 分摊(比例需重新归一化到 sum=1)
                    valid_rows = [(i, r) for i, r in enumerate(target_rows) if r['gmv_ratio'] is not None and r['gmv_ratio'] > 0]
                    none_ratio_rows = [(i, r) for i, r in enumerate(target_rows) if r['gmv_ratio'] is None or r['gmv_ratio'] <= 0]

                    if valid_rows and none_ratio_rows:
                        # 混合场景:有比例行 + 无比例行
                        # 先归一化 valid_rows 的 gmv_ratio 到 sum=1
                        raw_total = sum((r['gmv_ratio'] for _, r in valid_rows), Decimal("0"))
                        if raw_total > 0:
                            allocated = Decimal("0")
                            for idx, (i, row_info) in enumerate(valid_rows):
                                normalized_r = row_info['gmv_ratio'] / raw_total
                                if idx == len(valid_rows) - 1:
                                    share = round_2(field_value - allocated)
                                else:
                                    share = round_2(field_value * normalized_r)
                                allocated += share
                                row_info['_share'] = share

                            # none_ratio_rows 平均分配剩余
                            remaining_amount = field_value - allocated
                            if remaining_amount > 0 and none_ratio_rows:
                                per_row = remaining_amount / len(none_ratio_rows)
                                for idx, (i, row_info) in enumerate(none_ratio_rows):
                                    if idx == len(none_ratio_rows) - 1:
                                        row_info['_share'] = round_2(remaining_amount - per_row * (len(none_ratio_rows) - 1))
                                    else:
                                        row_info['_share'] = round_2(per_row)

                    elif valid_rows:
                        # 所有行都有 gmv_ratio → 归一化后分配
                        raw_total = sum((r['gmv_ratio'] for _, r in valid_rows), Decimal("0"))
                        if raw_total > 0:
                            allocated = Decimal("0")
                            for idx, (_, row_info) in enumerate(valid_rows):
                                normalized_r = row_info['gmv_ratio'] / raw_total
                                if idx == len(valid_rows) - 1:
                                    share = round_2(field_value - allocated)
                                else:
                                    share = round_2(field_value * normalized_r)
                                allocated += share
                                row_info['_share'] = share
                        else:
                            # raw_total=0 回退均分
                            per_row = field_value / len(target_rows)
                            for idx, row_info in enumerate(target_rows):
                                if idx == len(target_rows) - 1:
                                    row_info['_share'] = round_2(field_value - per_row * (len(target_rows) - 1))
                                else:
                                    row_info['_share'] = round_2(per_row)

                    else:
                        # 无 gmv_ratio,回退均分
                        allocated = Decimal("0")
                        for i, row_info in enumerate(target_rows):
                            if i == len(target_rows) - 1:
                                share = round_2(field_value - allocated)
                            else:
                                share = round_2(field_value / len(target_rows))
                            allocated += share
                            row_info['_share'] = share

                    # 执行更新(只更新有 _share 的 target_rows)
                    for row_info in target_rows:
                        row_id = row_info['id']
                        share = row_info.get('_share', Decimal("0"))

                        if share < 0:
                            share = Decimal("0")

                        total_output += share
                        # pymysql 方式执行 UPDATE
                        _write_cur.execute(
                            f"UPDATE {table} SET {column}=%s, updated_at=CURRENT_TIMESTAMP WHERE id=%s",
                            (float(share), row_id)
                        )
                        updated_count += 1

                        if gmv_ratio is not None or share > 0:
                            logger.info(f"[{label}] 分摊: id={row_id}, flow={flow_name}, biz={biz_type}, "
                                       f"brand={row_info['brand']}, ps={row_info['park_store']}, "
                                       f"gmv_ratio={gmv_ratio}, share={float(share)}")
            
            _write_conn.commit()
            _write_conn.close()
            
            # 诊断:写库后查 DB 实际值
            try:
                import pymysql as _pym2
                _diag2 = _pym2.connect(host=Config.MYSQL_HOST, port=int(Config.MYSQL_PORT or 3306),
                                      user=Config.MYSQL_USER, password=Config.MYSQL_PASSWORD,
                                      db=Config.MYSQL_DB, charset='utf8mb4', autocommit=True)
                _dc2 = _diag2.cursor()
                _dc2.execute(f"SELECT {', '.join(f'SUM({c})' for c in _cols)} FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (task_id, month))
                _dv2 = _dc2.fetchone()
                logger.info(f"[分摊更新-诊断] 写库后 DB sum: {dict(zip(_cols, _dv2))}")
                _diag2.close()
            except Exception as _de2:
                logger.warning(f"[分摊更新-诊断] 写库后查询失败: {_de2}")
            
            # 3. 验证总量守恒
            diff = total_input - total_output
            if abs(float(diff)) > Decimal("0.01"):
                logger.warning(f"[{field_configs[0]['label']} 总量校验: 输入={total_input}, 输出={total_output}, 差额={diff}")
            else:
                logger.info(f"[{field_configs[0]['label']}] 总量校验通过: 输入={total_input}, 输出={total_output}")
            
            total_skip = sum(skipped_by_col.values())
            logger.info(f"[分摊更新] 完成: 共更新 {updated_count} 行, 跳过(无DB行)={dict(skipped_by_col)}, 合计={total_skip}")
            
        except Exception as e:
            try:
                _write_conn.rollback()
            except:
                pass
            try:
                _write_conn.close()
            except:
                pass
            logger.error(f"[分摊更新] 失败: {e}")
            raise
        
        return total_input, total_output, updated_count, skipped_by_col
    
    def _update_wage_fee_by_id(self, task_id, month, parsed_data):
        """按 gmv_ratio 分摊外援施工费并按主键id更新"""
        field_configs = [{'value_key': '外援施工费', 'column': 'external_construction', 'label': '外援施工费'}]
        return self._allocate_and_update_by_id(task_id, month, parsed_data, field_configs)
    
    def _update_labor_cost_by_id(self, task_id, month, parsed_data):
        """按 gmv_ratio 分摊人力成本并按主键id更新"""
        field_configs = [
            {'value_key': '技师工资', 'column': 'technician_salary', 'label': '技师工资'},
            {'value_key': '营销团队工资', 'column': 'marketing_team_salary', 'label': '营销团队工资'},
        ]
        return self._allocate_and_update_by_id(task_id, month, parsed_data, field_configs)
    
    def _update_utility_fee_by_id(self, task_id, month, parsed_data):
        """按 gmv_ratio 分摊房租水电费并按主键id更新(支持品牌维度)"""
        field_configs = [{'value_key': '房租及水电费', 'column': 'rent_utilities', 'label': '房租水电费'}]
        return self._allocate_and_update_by_id(task_id, month, parsed_data, field_configs)

    def _update_wage_fee_to_db(self, task_id, month, data_list):
        """只更新外援施工费相关字段"""
        update_columns = ['external_construction']
        return self._execute_batch_update(task_id, month, data_list, update_columns, log_prefix="外援施工费")

    def _update_gross_profit_by_id(self, task_id, month):
        """按ID计算并更新毛利相关字段(2026-10 精简版本)

        新公式(统一,不再区分嘀加自营):
          毛利 = 嘀加分润 - 房租水电 - 装修摊销
          毛利率本月 = 毛利 / GMV * 100
          毛利率上月 = 上月毛利 / 上月GMV * 100

        移除:市场费、门店耗材因子,f_company_gross_profit 固定为 0。
        """
        logger.info(f"[毛利更新] 开始按ID更新(2026-10 精简版),task_id={task_id}, month={month}")

        # 1. 查询当前月份所有记录(精简查询字段)
        rows = db.session.execute(
            text("""
                SELECT id, dijia_profit_sharing, rent_utilities, renovation_amortization,
                       gmv, traffic_name, business_type, brand, park_store
                FROM biz_budget_achieve
                WHERE task_id=:tid AND stat_month=:sm
            """),
            {"tid": task_id, "sm": month}
        ).fetchall()
        logger.info(f"[毛利更新] 查询到 {len(rows)} 条记录")

        # 2. 计算上月月份
        year, month_str = month.split("-")
        year = int(year)
        month_int = int(month_str)
        if month_int == 1:
            prev_year = year - 1
            prev_month = 12
        else:
            prev_year = year
            prev_month = month_int - 1
        prev_month_str = f"{prev_year}-{prev_month:02d}"

        # 3. 查询上月数据
        prev_records = db.session.execute(
            text("""
                SELECT traffic_name, business_type, brand, park_store,
                       gross_profit, gmv
                FROM biz_budget_achieve
                WHERE task_id=:tid AND stat_month=:sm
            """),
            {"tid": task_id, "sm": prev_month_str}
        ).fetchall()

        prev_month_map = {}
        for r in prev_records:
            key = (r.traffic_name or "", r.business_type or "",
                   r.brand or "", r.park_store or "")
            prev_month_map[key] = {
                "gross_profit": float(r.gross_profit or 0),
                "gmv": float(r.gmv or 0),
            }
        logger.info(f"[毛利更新] 上月数据 {len(prev_month_map)} 条")

        # 4. 逐行计算并更新
        table = BizBudgetAchieve.__tablename__
        sql = text(f"""
            UPDATE {table}
            SET f_company_gross_profit = :f_company_gross_profit,
                gross_profit = :gross_profit,
                gross_profit_ratio_current = :gross_profit_ratio_current,
                gross_profit_ratio_previous = :gross_profit_ratio_previous,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = :id
        """)

        conn = db.engine.connect()
        trans = conn.begin()
        try:
            count = 0
            for row in rows:
                row_id = row.id
                dijia_profit_sharing = float(row.dijia_profit_sharing or 0)
                rent_utilities = float(row.rent_utilities or 0)
                renovation_amortization = float(row.renovation_amortization or 0)
                gmv = float(row.gmv or 0)
                traffic_name = (row.traffic_name or "").strip()
                business_type = (row.business_type or "").strip()
                brand = (row.brand or "").strip()
                park_store = (row.park_store or "").strip()

                # 2026-10 精简:f_company_gross_profit 固定为 0,不再计算
                f_company_gross_profit = 0.0

                # 2026-10 精简:统一公式,不再区分嘀加自营
                #   毛利 = 嘀加分润 - 房租水电 - 装修摊销
                gross_profit = round(
                    dijia_profit_sharing - rent_utilities - renovation_amortization, 2
                )

                # 毛利率本月
                if gmv != 0:
                    gross_profit_ratio_current = self._clamp_ratio(round(gross_profit / gmv * 100, 2))
                else:
                    gross_profit_ratio_current = 0.0

                # 毛利率上月
                prev_key = (traffic_name, business_type, brand, park_store)
                prev_data = prev_month_map.get(prev_key, {})
                prev_gross_profit = prev_data.get("gross_profit", 0)
                prev_gmv = prev_data.get("gmv", 0)
                if prev_gmv != 0:
                    gross_profit_ratio_previous = self._clamp_ratio(round(prev_gross_profit / prev_gmv * 100, 2))
                else:
                    gross_profit_ratio_previous = 0.0

                conn.execute(sql, {
                    'id': row_id,
                    'f_company_gross_profit': f_company_gross_profit,
                    'gross_profit': gross_profit,
                    'gross_profit_ratio_current': gross_profit_ratio_current,
                    'gross_profit_ratio_previous': gross_profit_ratio_previous,
                })
                count += 1

            trans.commit()
            logger.info(f"[毛利更新] 更新完成,共更新 {count} 行")
            return count
        except Exception as e:
            trans.rollback()
            logger.error(f"[毛利更新] 更新失败: {e}")
            raise
        finally:
            conn.close()

    def _update_profit_to_db(self, task_id, month, data_list):
        """只更新毛利相关字段"""
        update_columns = [
            'f_company_gross_profit', 'gross_profit',
            'gross_profit_ratio_current', 'gross_profit_ratio_previous',
        ]
        return self._execute_batch_update(task_id, month, data_list, update_columns, log_prefix="毛利")

    def _load_db_ratio_index(self, task_id, month):
        try:
            result = db.session.execute(
                text("SELECT id, traffic_name, business_type, brand, park_store, gmv_ratio FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
                {"tid": task_id, "sm": month}
            ).fetchall()

            ratio_index = {}
            for r in result:
                row_id = r[0]
                flow_name = (r[1] or "").strip()
                biz_type = (r[2] or "").strip()
                brand = (r[3] or "").strip()
                park_store = (r[4] or "").strip()
                gmv_ratio_decimal = Decimal(str(r[5])) if r[5] is not None else Decimal("0")

                key = (flow_name, biz_type, brand)
                if key not in ratio_index:
                    ratio_index[key] = []
                ratio_index[key].append((row_id, park_store, gmv_ratio_decimal))

            multi_row_count = sum(1 for v in ratio_index.values() if len(v) > 1)
            logger.info(f"[房租水电分摊] 数据库索引加载完成: 共 {len(ratio_index)} 组,其中 {multi_row_count} 组存在多行")
            return ratio_index
        except Exception as e:
            logger.warning(f"[房租水电分摊] 加载数据库比例索引失败: {e}")
            return {}

    # DEPRECATED: 此方法已被拆分,不再使用
    # 保留用于兼容,建议使用各独立更新方法
    def _write_budget_achieve(self, task_id, month, summary_data):
        """
        将汇总数据写入 biz_budget_achieve 表。
        使用业务唯一键 (task_id, stat_month, traffic_name, business_type, brand) 进行 Upsert:
          - 存在则仅更新成本相关字段(市场费、人力成本、房租水电等)
          - 不存在则新增完整记录
        """
        # 业务字段列表(仅成本相关字段在 ON DUPLICATE KEY UPDATE 时更新)
        update_columns = [
            'market_fee', 'market_fee_ratio_current', 'market_fee_ratio_previous',
            'personnel_salary', 'external_construction',
            'technician_salary', 'technician_salary_ratio',
            'marketing_team_salary', 'marketing_team_salary_ratio',
            'personnel_salary_ratio_current', 'personnel_salary_ratio_previous',
            'rent_utilities',
            'f_company_gross_profit', 'gross_profit', 
            'gross_profit_ratio_current', 'gross_profit_ratio_previous',
        ]

        def safe_float(val):
            """安全转换为 float,处理 Decimal、None、空字符串等"""
            if val is None or val == '' or val == 'nan':
                return 0.0
            if isinstance(val, Decimal):
                return float(val)
            try:
                return float(val)
            except (ValueError, TypeError):
                return 0.0

        # 构建批量参数
        params_list = []
        for idx, row in enumerate(summary_data):
            # 清理字符串字段的前后空格
            traffic_name = (row["流量方名称"] or "").strip()
            business_type = (row["业务类型"] or "").strip()
            brand = (row.get("品牌", "") or "").strip()
            
            params = {
                'task_id': task_id,
                'stat_month': month,
                'traffic_name': traffic_name,
                'business_type': business_type,
                'brand': brand,
                'is_multi_category': row.get("is_multi_category", ""),
                'entity': row.get("entity", ""),
                'park_store': row.get("park_store", ""),
                'service_provider': row.get("service_provider", ""),
                'order_count': row.get("order_count", 0),
                'gmv': safe_float(row.get("GMV", Decimal("0"))),
                'revenue': safe_float(row.get("产值", Decimal("0"))),
                'market_fee': safe_float(row.get("市场费", Decimal("0"))),
                'market_fee_ratio_current': safe_float(row.get("市场费本月占比", Decimal("0"))),
                'market_fee_ratio_previous': safe_float(row.get("市场费上月占比", Decimal("0"))),
                'personnel_salary': safe_float(row.get("人员工资", Decimal("0"))),
                'external_construction': safe_float(row.get("外援施工", Decimal("0"))),
                'technician_salary': safe_float(row.get("技师工资", Decimal("0"))),
                'technician_salary_ratio': safe_float(row.get("技师工资占比", Decimal("0"))),
                'marketing_team_salary': safe_float(row.get("营销团队工资", Decimal("0"))),
                'marketing_team_salary_ratio': safe_float(row.get("营销团队工资占比", Decimal("0"))),
                'personnel_salary_ratio_current': safe_float(row.get("人员工资本月占比", Decimal("0"))),
                'personnel_salary_ratio_previous': safe_float(row.get("人员工资上月占比", Decimal("0"))),
                'rent_utilities': safe_float(row.get("房租及水电费", Decimal("0"))),
                'f_company_gross_profit': safe_float(row.get("F公司毛利", Decimal("0"))),
                'gross_profit': safe_float(row.get("毛利", Decimal("0"))),
                'gross_profit_ratio_current': safe_float(row.get("毛利率本月", Decimal("0"))),
                'gross_profit_ratio_previous': safe_float(row.get("毛利率上月", Decimal("0"))),
                # 预留字段默认0
                'cost_gmv': 0,
                'cost_gmv_ratio_current': 0,
                'cost_gmv_ratio_previous': 0,
                'traffic_fee_gmv': 0,
                'traffic_fee_gmv_ratio_current': 0,
                'traffic_fee_gmv_ratio_previous': 0,
                'service_fee': 0,
                'service_fee_ratio_current': 0,
                'service_fee_ratio_previous': 0,
                'cost_revenue': 0,
                'traffic_fee_revenue': 0,
                'dijia_profit_sharing': 0,
                'renovation_amortization': 0,
                'store_consumables': 0,
            }
            params_list.append(params)

            # 记录前几条数据的调试日志
            if idx < 3:
                logger.info(f"[写入调试] 第{idx}条: 流量方={params['traffic_name']}, "
                           f"业务类型={params['business_type']}, 品牌={params['brand']}, "
                           f"市场费={params['market_fee']}, 人员工资={params['personnel_salary']}, "
                           f"外援施工={params['external_construction']}, 技师工资={params['technician_salary']}, "
                           f"营销团队工资={params['marketing_team_salary']}")

        # 构建 UPDATE SQL(只更新已存在的记录,不插入新记录)
        table = BizBudgetAchieve.__tablename__
        
        # 更新子句:仅更新成本相关字段
        set_clause = ', '.join([f'{col}=:{col}' for col in update_columns])
        set_clause += ', updated_at = CURRENT_TIMESTAMP'
        
        # WHERE 条件:按业务唯一键匹配
        where_columns = ['task_id', 'stat_month', 'traffic_name', 'business_type', 'brand']
        where_clause = ' AND '.join([f'{col}=:{col}' for col in where_columns])

        sql_text = text(
            f"UPDATE {table} SET {set_clause} "
            f"WHERE {where_clause}"
        )

        ratio_index = self._load_db_ratio_index(task_id, month)

        update_columns_no_ru = [c for c in update_columns if c != 'rent_utilities']
        set_clause_no_ru = ', '.join([f'{col}=:{col}' for col in update_columns_no_ru])
        set_clause_no_ru += ', updated_at = CURRENT_TIMESTAMP'
        sql_text_no_ru = text(
            f"UPDATE {table} SET {set_clause_no_ru} "
            f"WHERE {where_clause}"
        )

        # 写入诊断日志:待更新数量 + 前 3 条的 WHERE 键与目标值
        first_3 = params_list[:3]
        diag_parts = []
        for p in first_3:
            diag_parts.append(
                f"[{p['traffic_name']} | {p['business_type']} | brand={p['brand']} | F公司毛利={p['f_company_gross_profit']}]"
            )
        logger.info(f"[写入诊断] 待更新 {len(params_list)} 条,前 3 条: {'; '.join(diag_parts)}")

        # 执行批量 Update(只更新已存在的记录)
        conn = db.engine.connect()
        updated_count = 0
        try:
            trans = conn.begin()
            for params in params_list:
                bind_params = {}
                for col in where_columns + update_columns:
                    bind_params[col] = params.get(col, 0)
                if not bind_params.get('brand'):
                    bind_params['brand'] = ''

                key = (params['traffic_name'], params['business_type'], params['brand'])

                if key in ratio_index and len(ratio_index[key]) > 1:
                    rows_info = ratio_index[key]
                    brand_level_fee = Decimal(str(bind_params['rent_utilities']))

                    total_ratio = sum(r for _, _, r in rows_info)
                    # 分摊:优先使用 gmv_ratio,无比例时回退均分;
                    # 与 _parse_utility_fee 内部算法保持一致,最后一行吃掉舍入误差,保证总量守恒
                    shares = []
                    allocated = Decimal("0")
                    for i, (row_id, park_store, gmv_r) in enumerate(rows_info):
                        is_last = (i == len(rows_info) - 1)
                        if is_last:
                            share = round_2(brand_level_fee - allocated)
                        else:
                            if total_ratio > 0 and gmv_r is not None:
                                share = round_2(brand_level_fee * gmv_r)
                            else:
                                share = round_2(brand_level_fee / Decimal(str(len(rows_info))))
                        shares.append((row_id, park_store, gmv_r, share))
                        allocated += share

                    for row_id, park_store, gmv_r, share in shares:
                        conn.execute(
                            text("UPDATE biz_budget_achieve SET rent_utilities=:ru, updated_at=CURRENT_TIMESTAMP WHERE id=:id"),
                            {'ru': float(share), 'id': row_id}
                        )
                        logger.info(f"[房租水电分摊写入] id={row_id}, park_store={park_store}, gmv_ratio={gmv_r}, share_amount={float(share)}")

                    sum_after = sum(s for _, _, _, s in shares)
                    logger.info(f"[房租水电分摊验证] key={key}, brand_level_fee={float(brand_level_fee)}, sum_before={float(brand_level_fee)}, sum_after={float(sum_after)}")

                    result = conn.execute(sql_text_no_ru, bind_params)
                else:
                    result = conn.execute(sql_text, bind_params)

                if result.rowcount > 0:
                    updated_count += 1
            trans.commit()
            total = len(params_list)
            rate = updated_count / total * 100 if total > 0 else 0
            logger.info(f"[写入] Update 成功,共处理 {total} 条记录,实际更新 {updated_count} 条,成功率 {rate:.1f}%")
            if updated_count == 0:
                unique_brands = list(set(p['brand'] for p in params_list))
                unique_traffic = list(set(p['traffic_name'] for p in params_list))
                logger.warning(f"[写入诊断] 所有 {total} 条记录均未匹配更新!请检查 WHERE 条件。"
                               f"涉及品牌: {unique_brands}, 涉及流量方: {unique_traffic}")
        except Exception as e:
            trans.rollback()
            logger.error(f"[写入] Update 失败: {str(e)}")
            raise
        finally:
            conn.close()

    # ========================================================
    # 生成汇总 Excel 并上传
    # ========================================================

    def _generate_and_upload_excel(self, task_id, month, tmp_dir):
        """
        生成《预算达成数据》汇总 Excel(41 列,格式见附件模板)并上传到 OSS。

        数据来源:biz_budget_achieve 表全量读取(含上月占比/上月毛利率等历史列),
        不做任何重算 —— 表中存什么就导出什么。
        返回:OSS 文件 URL;无数据时返回 None
        """
        logger.info(f"[Excel] 开始生成预算达成数据 Excel,任务 {task_id} 月份: {month}")

        # ---------- 1. 查询当月数据(biz_budget_achieve,完整 41 列来源) ----------
        rows = (BizBudgetAchieve.query
                .filter_by(task_id=task_id, stat_month=month)
                .order_by(BizBudgetAchieve.business_type,
                          BizBudgetAchieve.traffic_name,
                          BizBudgetAchieve.brand,
                          BizBudgetAchieve.entity,
                          BizBudgetAchieve.park_store,
                          BizBudgetAchieve.service_provider)
                .all())
        if not rows:
            logger.warning(f"[Excel] 任务 {task_id} 在 biz_budget_achieve 中无数据,跳过 Excel 生成")
            return None

        # ---------- 2. 抬头与计算说明(与附件模板一致,41 列) ----------
        # (header, db_attr) —— db_attr=None 表示特殊计算列
        ORDERED = [
            ("是否为多品类", "is_multi_category"),
            ("流量方名称", "traffic_name"),
            ("业务类型", "business_type"),
            ("主体", "entity"),
            ("品牌", "brand"),
            ("园区店", "park_store"),
            ("服务商", "service_provider"),
            ("订单数", "order_count"),
            ("GMV", "gmv"),
            ("收入", "revenue"),
            ("成本\n(GMV口径)", "cost_gmv"),
            ("本月占比", "cost_gmv_ratio_current"),
            ("上月占比", "cost_gmv_ratio_previous"),
            ("流量费\n(GMV口径)", "traffic_fee_gmv"),
            ("本月占比", "traffic_fee_gmv_ratio_current"),
            ("上月占比", "traffic_fee_gmv_ratio_previous"),
            ("服务费", "service_fee"),
            ("本月占比", "service_fee_ratio_current"),
            ("上月占比", "service_fee_ratio_previous"),
            ("成本\n(收入口径)", "cost_revenue"),
            ("流量费\n(收入口径)", "traffic_fee_revenue"),
            ("嘀加分润", "dijia_profit_sharing"),
            # 2026-10 精简:移除市场费/人力成本/外援施工/技师工资/营销团队工资/门店耗材/F公司毛利 系列列
            ("房租及\n水电费", "rent_utilities"),
            ("装修摊销", "renovation_amortization"),
            ("毛利", "gross_profit"),
            ("本月毛利率", "gross_profit_ratio_current"),
            ("上月毛利率", "gross_profit_ratio_previous"),
        ]
        HEADERS = [h for h, _ in ORDERED]

        # 列分类(用于数字格式)
        # 2026-10 精简:移除已删除列对应的分类项
        AMOUNT_COLS = {'GMV', '收入', '成本(GMV口径)', '流量费(GMV口径)', '服务费',
                       '成本(收入口径)', '流量费(收入口径)', '嘀加分润', '房租及水电费',
                       '装修摊销', '毛利'}
        RATIO_COLS = {'本月占比', '上月占比', '本月毛利率', '上月毛利率'}
        INT_COLS = {'订单数'}

        # ---------- 4. 构建工作簿 ----------
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "预算达成数据"

        header_font = Font(name="微软雅黑", size=11, bold=True)
        header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
        header_font_white = Font(name="微软雅黑", size=11, bold=True, color="FFFFFF")
        cell_font = Font(name="微软雅黑", size=10)
        center_align = Alignment(horizontal="center", vertical="center", wrap_text=True)
        right_align = Alignment(horizontal="right", vertical="center")
        thin_border = Border(left=Side(style="thin"), right=Side(style="thin"),
                             top=Side(style="thin"), bottom=Side(style="thin"))

        # 行1:表头
        for c, h in enumerate(HEADERS, 1):
            cell = ws.cell(row=1, column=c, value=h)
            cell.font = header_font_white
            cell.fill = header_fill
            cell.alignment = center_align
            cell.border = thin_border

        # 列宽
        # 2026-10 精简:移除已删除列对应的列宽配置
        column_widths = {
            "是否为多品类": 10, "流量方名称": 18, "业务类型": 9, "主体": 14,
            "品牌": 8, "园区店": 18, "服务商": 14, "订单数": 8, "GMV": 14, "收入": 14,
            "成本(GMV口径)": 14, "本月占比": 11, "上月占比": 11,
            "流量费(GMV口径)": 14, "服务费": 12, "成本(收入口径)": 14, "流量费(收入口径)": 14,
            "嘀加分润": 12, "房租及水电费": 13, "装修摊销": 11,
            "毛利": 12, "本月毛利率": 11, "上月毛利率": 11,
        }

        # 写入数据行(从第 2 行开始)—— 全部直接读取表中字段,不做任何重算
        for i, r in enumerate(rows):
            row_idx = i + 2

            values = []
            for (header, attr) in ORDERED:
                # attr 均指向 biz_budget_achieve 表中已存储的字段(含 *_previous 上月列)
                values.append(getattr(r, attr))

            for c, header in enumerate(HEADERS, 1):
                raw = values[c - 1]
                cell = ws.cell(row=row_idx, column=c)
                if raw is None:
                    cell.value = ""
                elif header in AMOUNT_COLS:
                    try:
                        cell.value = float(raw)
                    except (ValueError, TypeError):
                        cell.value = 0.0
                    cell.number_format = "#,##0.00"
                elif header in RATIO_COLS:
                    # 占比/毛利率列:库中存的是已×100的百分数值(如 46.71 表示 46.71%),
                    # 用 0.00"%" 格式(仅显示追加 % 号,不缩放数值),避免 0.00% 将值放大100倍
                    try:
                        cell.value = float(raw)
                    except (ValueError, TypeError):
                        cell.value = 0.0
                    cell.number_format = '0.00"%"'
                elif header in INT_COLS:
                    try:
                        cell.value = int(raw)
                    except (ValueError, TypeError):
                        cell.value = 0
                    cell.number_format = "#,##0"
                else:
                    cell.value = "" if raw is None else str(raw)
                if header in AMOUNT_COLS or header in RATIO_COLS or header in INT_COLS:
                    cell.alignment = right_align
                else:
                    cell.alignment = center_align
                cell.font = cell_font
                cell.border = thin_border

        # ---------- 5. 追加未匹配金额汇总行 ----------
        # 映射 fee_type → ORDERED 里的 db_attr(用于定位 Excel 列)
        # 2026-10 精简:仅保留房租水电和装修摊销的未匹配追踪
        FEE_TYPE_TO_DB_ATTR = {
            'rent_utilities': 'rent_utilities',
            'renovation_amortization': 'renovation_amortization',
        }
        # 反向查 db_attr → Excel 列索引(1-based)
        db_attr_to_col = {attr: c for c, (h, attr) in enumerate(ORDERED, 1)}

        try:
            unmatched_rows = BizUnmatchedFee.query.filter_by(task_id=task_id, stat_month=month).all()
        except Exception as e_uf:
            logger.warning(f"[Excel] 查未匹配金额失败,跳过追加行: {e_uf}")
            unmatched_rows = []

        # 汇总到一个 dict(同 fee_type 可能多条 —— 用先删后插保证只有一条,这里保险用 sum)
        unmatched_by_fee = {}
        for ur in unmatched_rows:
            amt = float(ur.unmatched_amount) if ur.unmatched_amount else 0
            unmatched_by_fee[ur.fee_type] = unmatched_by_fee.get(ur.fee_type, 0) + amt

        # 只有存在非零未匹配金额才追加行
        has_any_nonzero = any(abs(v) > 0.001 for v in unmatched_by_fee.values())
        if has_any_nonzero:
            new_row_idx = len(rows) + 2  # 数据行最后一行 + 1
            ws.cell(row=new_row_idx, column=1, value="未匹配合计").font = cell_font
            ws.cell(row=new_row_idx, column=1).alignment = center_align
            ws.cell(row=new_row_idx, column=1).border = thin_border

            for fee_type, amt in unmatched_by_fee.items():
                if abs(amt) <= 0.001:
                    continue
                db_attr = FEE_TYPE_TO_DB_ATTR.get(fee_type)
                if db_attr is None:
                    continue
                col_idx = db_attr_to_col.get(db_attr)
                if col_idx is None:
                    continue
                cell = ws.cell(row=new_row_idx, column=col_idx)
                cell.value = round(amt, 2)
                cell.number_format = "#,##0.00"
                cell.font = cell_font
                cell.alignment = right_align
                cell.border = thin_border

            # 未匹配行其他列也画边框(保持视觉一致)
            for c in range(2, len(HEADERS) + 1):
                if ws.cell(row=new_row_idx, column=c).border.left.style is None:
                    cell = ws.cell(row=new_row_idx, column=c)
                    cell.border = thin_border

            logger.info(f"[Excel] 追加未匹配合计行 row={new_row_idx}, 未匹配金额汇总: {unmatched_by_fee}")
        else:
            logger.info(f"[Excel] 无未匹配金额,跳过追加行")

        for c, h in enumerate(HEADERS, 1):
            ws.column_dimensions[openpyxl.utils.get_column_letter(c)].width = column_widths.get(h, 12)

        # 冻结表头单行
        ws.freeze_panes = "A2"
        ws.row_dimensions[1].height = 30

        # 保存 Excel
        excel_path = os.path.join(tmp_dir, f"预算达成数据_{month}.xlsx")
        wb.save(excel_path)
        logger.info(f"[Excel] Excel 文件生成完成: {excel_path}({len(rows)} 行,{len(HEADERS)} 列)")

        # 上传到 OSS
        object_key = f"data-process/{datetime.now().strftime('%Y%m%d')}/budget_achieve_{month}.xlsx"
        file_url = upload_file(excel_path, object_key)
        logger.info(f"[Excel] 已上传到 OSS: {file_url}")

        return file_url

    # ========================================================
    # 辅助方法
    # ========================================================

    def _mark_task_failed(self, task_id, error_msg):
        """
        标记任务为失败状态,记录错误信息。
        """
        try:
            task = DataProcessTask.query.filter_by(id=task_id).first()
            if task:
                task.status = 'FAILED'
                task.error_msg = error_msg[:500]  # 限制长度
                db.session.commit()
                logger.info(f"[标记失败] 任务 {task_id} 已标记为失败")
        except Exception as e:
            logger.error(f"[标记失败] 更新任务失败状态时出错: {str(e)}")
            db.session.rollback()
            raise

    def _cleanup_tmp_dir(self, tmp_dir):
        """
        清理临时目录。
        处理 Windows 文件占用问题,添加重试机制。
        """
        import time
        try:
            if os.path.exists(tmp_dir):
                # 先尝试忽略错误删除
                shutil.rmtree(tmp_dir, ignore_errors=True)
                # 检查是否还存在,若存在则重试
                if os.path.exists(tmp_dir):
                    time.sleep(0.5)
                    shutil.rmtree(tmp_dir, ignore_errors=True)
                if os.path.exists(tmp_dir):
                    # 第三次尝试
                    time.sleep(1)
                    shutil.rmtree(tmp_dir, ignore_errors=True)
                
                if not os.path.exists(tmp_dir):
                    logger.info(f"[清理] 临时目录已清理: {tmp_dir}")
                else:
                    logger.warning(f"[清理] 临时目录仍被占用,跳过: {tmp_dir}")
        except Exception as e:
            logger.warning(f"[清理] 清理临时目录时出错: {str(e)}")


# ============================================================
# 便捷函数
# ============================================================

def create_processor(app=None):
    """
    创建数据处理器实例。
    """
    return DataProcessor(app)