processor.py 124 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
# -*- 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, db
from oss_utils import download_file, upload_file
from config import Config

# 配置日志
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业务

# 必需的表单类型(仅下载这些文件)
REQUIRED_FORM_TYPES = ['市场费总表', '人力成本统计表', '外施施工费用表', '房租水电费用表']

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

# 市场费 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'},
    {'pattern': '^龙南$', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'},
    # 2.1 业务:权益、续保
    {'pattern': '权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'},
    {'pattern': '续保', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'},
    # 2.3 业务:延保
    {'pattern': '延保', 'biz_type': BIZ_TYPE_2_3, 'fee_col': 'market_fee'},
]

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

# 品牌关键词映射
WENJIE_KEYWORDS = ["问界"]
HARMONY_KEYWORDS = ["享界", "智界", "尊界", "尚界"]

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

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

def strip_if_dplus(name):
    """返回字符串(保留 D+ 前缀)。"""
    return str(name or '')

def load_alias_maps():
    """从 merchant_4s(流量方字典表)与 merchant_yq(园区店字典表)加载 别名→标准名 映射。
    结果缓存到模块级 _ALIAS_MAPS,整个进程只加载一次。
    """
    global _ALIAS_MAPS
    if _ALIAS_MAPS:
        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"[别名映射] 加载完成: 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)
                decrypted = office_file.decrypt()

                # 写入临时文件
                tmp_fd, tmp_path = tempfile.mkstemp(suffix='.xlsx', prefix='decrypted_')
                with os.fdopen(tmp_fd, 'wb') as tmp_f:
                    tmp_f.write(decrypted)

                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 → 通过字符串中转,避免浮点精度丢失
      - 其他 → 尝试转换,失败则返回 0
    """
    if value is None:
        return Decimal("0")
    if isinstance(value, float) and math.isnan(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 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 identify_brand(model_text):
    """
    根据车型文本识别品牌。
    规则:
      - 含 "问界" → 问界
      - 含 "享界/智界/尊界/尚界" → 鸿蒙
      - 无车型信息 → 返回 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 "鸿蒙"
    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)
          settlement_map: {(流量方名称, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal, 
               "服务费": Decimal, "嘀加分润": Decimal, "服务商": str, "装修摊销": Decimal, "门店耗材": Decimal,
               "gmv_ratio": float|None, "gmv_ratio_park": float|None}}
          park_ratio_map: {(业务类型, 园区店): gmv_ratio_park}
        """
        logger.info(f"[GMV数据] 从数据库获取 task_id={task_id}, stat_month={stat_month} 的 GMV 数据")
        settlement_map = {}
        try:
            records = db.session.query(BizBudgetAchieve).filter(
                BizBudgetAchieve.task_id == task_id,
                BizBudgetAchieve.stat_month == stat_month
            ).all()
            
            if not records:
                logger.warning(f"[GMV数据] 数据库中无 task_id={task_id}, stat_month={stat_month} 的记录")
                return settlement_map, {}
            
            for r in records:
                flow_name = (r.traffic_name or "").strip()
                biz_type = (r.business_type or "").strip()
                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_val = to_standard((r.park_store or "").strip(), 'yq')
                
                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": ""
                    }
                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  # 园区店直接覆盖
            
            # 直接查询比例数据(不用ORM对象属性名冲突)
            try:
                ratio_records = db.session.execute(
                    text("SELECT traffic_name, business_type, brand, gmv_ratio, gmv_ratio_park FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm")
                ).params(tid=task_id, sm=stat_month).fetchall()
                for rr in ratio_records:
                    flow_n = (rr[0] or "").strip()
                    bt = (rr[1] or "").strip()
                    br = (rr[2] or "").strip()
                    key = (flow_n, bt, br)
                    if key in settlement_map:
                        settlement_map[key]["gmv_ratio"] = float(rr[3]) if rr[3] is not None else None
                        settlement_map[key]["gmv_ratio_park"] = float(rr[4]) if rr[4] is not None else None
            except Exception as e2:
                logger.warning(f"[GMV数据] 比例数据查询失败: {str(e2)}")

            # 构建 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")
                ).params(tid=task_id, sm=stat_month).fetchall()
                for pr in park_ratio_records:
                    bt = (pr[0] or "").strip()
                    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_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")
        except Exception as e:
            logger.error(f"[GMV数据] 查询失败: {str(e)}")
        
        return settlement_map, park_ratio_map

    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 的任务列表。
        返回:任务列表(按创建时间升序)
        """
        logger.info("[扫描] 开始扫描待处理任务...")
        tasks = DataProcessTask.query.filter(
            DataProcessTask.status == 'AA',
            DataProcessTask.is_deleted == 0
        ).order_by(DataProcessTask.created_at.asc()).all()
        logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务")
        return tasks

    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()

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

        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")

        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
            settlement_map, park_ratio_map = self._fetch_gmv_from_db(task.id, task.month)
            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 = []
            if '市场费总表' in downloaded_files:
                market_results = self._parse_market_fee(downloaded_files['市场费总表'], settlement_map)
                logger.info(f"[处理任务] 市场费解析完成,共 {len(market_results)} 条记录")

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

            # 解析人力成本
            labor_results = []
            if '人力成本统计表' in downloaded_files:
                labor_results = self._parse_labor_cost(downloaded_files['人力成本统计表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map)
                logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 条记录")

            # 解析房租水电施工费
            utility_results = []
            if '房租水电费用表' in downloaded_files:
                utility_results = self._parse_utility_fee(downloaded_files['房租水电费用表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map)
                logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录")
            logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s")

            # ========== 步骤 d: 执行成本计算 ==========
            step_d_start = time.time()
            logger.info("[处理任务] 步骤 d: 执行成本计算...")
            
            # 调试日志:显示解析结果的样本数据
            if market_results:
                sample = market_results[0]
                logger.info(f"[调试] 市场费样本: 流量方={sample.get('流量方名称')}, 业务={sample.get('业务类型')}, 市场费={sample.get('市场费')}")
            if wage_results:
                sample = wage_results[0]
                logger.info(f"[调试] 外援施工费样本: 流量方={sample.get('流量方名称')}, 业务={sample.get('业务类型')}, 外援施工费={sample.get('外援施工费')}")
            if labor_results:
                sample = labor_results[0]
                logger.info(f"[调试] 人力成本样本: 流量方={sample.get('流量方名称')}, 业务={sample.get('业务类型')}, 技师工资={sample.get('技师工资')}, 营销团队={sample.get('营销团队工资')}")
            
            # 查询上月历史数据用于计算上月占比
            prev_month_data = self._fetch_previous_month_data(task.id, task.month)
            
            summary_data = self._build_cost_summary(
                settlement_data, market_results, wage_results, labor_results, utility_results, prev_month_data,
                settlement_map=settlement_map, park_ratio_map=park_ratio_map
            )
            logger.info(f"[处理任务] 成本计算完成,共 {len(summary_data)} 条汇总记录")
            logger.info(f"[处理任务] 步骤 d 完成, 耗时: {time.time() - step_d_start:.2f}s")
            
            # 调试日志:显示汇总结果的样本数据
            if summary_data:
                sample = summary_data[0]
                logger.info(f"[调试] 汇总样本: 流量方={sample.get('流量方名称')}, 业务={sample.get('业务类型')}, "
                           f"市场费={sample.get('市场费')}, 外援施工={sample.get('外援施工')}, "
                           f"技师工资={sample.get('技师工资')}, 营销团队={sample.get('营销团队工资')}, "
                           f"人员工资={sample.get('人员工资')}")

            # ========== 步骤 e: 将结果写入 biz_budget_achieve 表 ==========
            step_e_start = time.time()
            logger.info("[处理任务] 步骤 e: 写入预算达成表...")
            self._write_budget_achieve(task.id, task.month, summary_data)
            logger.info(f"[处理任务] 已写入 {len(summary_data)} 条预算达成记录")
            logger.info(f"[处理任务] 步骤 e 完成, 耗时: {time.time() - step_e_start:.2f}s")

            # ========== 步骤 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):
        """
        根据 GMV 数据对市场费进行品牌分摊。
        规则:
          1. 同一流量方+业务类型下,未知品牌的费用按已知品牌的 GMV 占比分摊
          2. 同一流量方+业务类型+品牌有多条记录时,先汇总再按 GMV 比例分摊
        参数:
          - records: List[dict],原始记录列表,每条包含 {流量方名称, 业务类型, 品牌, 市场费}
          - settlement_map: {(流量方, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal}}
        返回:List[dict],分摊后的记录列表
        """
        if not records:
            return []
        
        # 按 (流量方, 业务类型) 分组
        groups = defaultdict(list)
        for r in records:
            key = (r["流量方名称"], r["业务类型"])
            groups[key].append(r)
        
        result = []
        for (flow, biz), group_records in groups.items():
            # 按品牌汇总费用
            brand_fees = defaultdict(Decimal)  # {品牌: 费用合计}
            brand_records = defaultdict(list)  # {品牌: [原始记录列表]}
            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
                    brand_records[brand].append(r)
            
            # 如果有未知品牌费用且存在已知品牌,进行 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())
                
                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
                    
                    # 尾差归并到第一个品牌
                    allocated_total = sum(brand_fees.values()) - sum(
                        Decimal(str(r.get("市场费", 0))) for r in group_records if r.get("品牌") == "未知品牌"
                    )
                    diff = unknown_brand_fee - (brand_fees[list(brand_fees.keys())[0]] - (brand_fees[list(brand_fees.keys())[0]] - allocated_total))
                    # 简化处理:计算分摊后的实际总和与未知品牌费用的差额,加到第一个品牌
                    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
                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
            
            # 输出结果
            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),
                })
        
        logger.info(f"[市场费分摊] GMV 分摊完成,共 {len(result)} 条记录")
        return result

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

    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 []

        if settlement_map is None:
            settlement_map = {}

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

        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]
            
            # 调试日志:显示所有列名
            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}")

            # 查找关键列 - 支持多种列名模式
            col_flow = find_column(df, "流量方-流量方", "流量方名称", "流量方", "门店", "服务商")
            col_fee_market = find_column(df, "市场费")
            col_fee_total = find_column(df, "市场费总额", "市场费合计")
            col_model = find_column(df, "车型", "商品名称", "产品名称")
            col_category = find_column(df, "商品类别", "类别", "业务类别")

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

            if not col_fee:
                logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列 (fee_col_type={fee_col_type})")
                continue

            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 = sheet_biz_type

                # 取费
                fee = safe_decimal(row[col_fee])

                if fee == 0:
                    continue

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

                # 2.3→2.1 归属规则:商品类别=权益服务/延保-原厂权益 归属2.1
                if biz_type == BIZ_TYPE_2_3 and col_category:
                    category = str(row[col_category]).strip() if pd.notna(row[col_category]) else ""
                    if category in ["权益服务", "延保-原厂权益"]:
                        biz_type = BIZ_TYPE_2_1
                        logger.debug(f"[市场费] 2.3→2.1 归属: flow={flow_name}, category={category}")

                # 使用标准名映射
                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)

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

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

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

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

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

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

        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:
            # 回退:尝试找第一个 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))
            logger.info(f"[外援施工费] 第{i}行: {row_text[:120]}")
            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 []

        raw_records = []
        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()

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

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

            fee = safe_decimal(row[col_total])
            if fee == 0:
                continue

            raw_records.append({
                "流量方名称": std_source,
                "原始名称": flow_source,
                "业务类型": BIZ_TYPE_1_1,
                "外援施工费": fee,
            })

        if not raw_records:
            logger.info("[外援施工费] 无有效数据")
            return []

        logger.info(f"[外援施工费] 解析到 {len(raw_records)} 条记录")

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

        result = []
        for (flow, biz), records in grouped.items():
            total_fee = sum(r["外援施工费"] for r in records)

            # 优先从 settlement_map 查找 gmv_ratio 进行分摊
            db_ratio = None
            if 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

            if db_ratio is not None:
                logger.info(f"[外援施工费分摊] 流量方匹配成功,使用 gmv_ratio={db_ratio}")
                result.append({
                    "流量方名称": flow,
                    "业务类型": biz,
                    "外援施工费": round_2(total_fee * Decimal(str(db_ratio))),
                })
            else:
                logger.warning(f"[外援施工费分摊] 流量方匹配失败,使用原始金额")
                result.append({
                    "流量方名称": flow,
                    "业务类型": biz,
                    "外援施工费": round_2(total_fee),
                })

        logger.info(f"[外援施工费] 汇总后 {len(result)} 条记录")
        if result:
            logger.info(f"[外援施工费] 预览前3条: {result[:3]}")
        return result

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

    def _parse_labor_cost(self, file_path, settlement_map=None, park_ratio_map=None):
        """
        解析人力成本表。
        规则:
          - 仅检核=TRUE的行参与计算
          - 1.1业务:岗位=贴膜技师→技师工资;其他→营销团队工资
          - 2.1/2.3业务:全部→营销团队工资
          - 匹配策略:先用"入驻门店"直接匹配settlement_map的流量方名称
          - 回退策略:匹配失败时用"入驻门店"标准化为园区店名,查找关联流量方,按比例分摊
        返回:List[dict],每行 {流量方名称, 业务类型, 技师工资, 营销团队工资}
        """
        logger.info(f"[人力成本] 解析文件: {file_path}")

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

        if settlement_map is None:
            settlement_map = {}

        # 构建 settlement_map 的索引
        flow_names_set = set()  # 所有流量方名称
        park_to_flows = defaultdict(list)  # park_store -> [(flow_name, biz_type)]
        # 每个 (流量方, 业务类型) 在园区店内的 GMV 占比(已入库 gmv_ratio_park)
        # 按 (park_store, flow_name, biz_type) 聚合求和,兼容多品牌行
        _park_ratio_raw = defaultdict(lambda: defaultdict(Decimal))
        for (flow_name, biz_type, brand), data in settlement_map.items():
            flow_names_set.add(flow_name)
            ps = data.get("park_store", "")
            if ps:
                park_to_flows[ps].append((flow_name, biz_type))
                ratio = data.get("gmv_ratio_park")
                if ratio is not None:
                    _park_ratio_raw[ps][(flow_name, biz_type)] += Decimal(str(ratio))

        # park_to_ratio: key=ps or (bt,ps) or (ps, flow, bt) -> ratio
        park_to_ratio = {}
        # (park_store, flow, biz_type) 级最精细
        for ps, inner in _park_ratio_raw.items():
            for (fn, bt), total in inner.items():
                park_to_ratio[(ps, fn, bt)] = float(total)
                park_to_ratio[(bt, ps)] = float(total)  # 便于回退
            # park_store 级取任意一个(通常 park 下所有 flow 的 ratio 语义一致,
            # 这里仅作兜底,真正分摊按 (ps, flow, bt) 精确匹配)
            if inner:
                first_ratio = next(iter(inner.values()))
                park_to_ratio[ps] = float(first_ratio)

        # 如果有 park_ratio_map,合并进去(兜底补充)
        if park_ratio_map:
            for (bt, ps), ratio in park_ratio_map.items():
                key = (bt, ps)
                if key not in park_to_ratio:
                    park_to_ratio[key] = ratio
                if ps not in park_to_ratio:
                    park_to_ratio[ps] = ratio

        logger.info(f"[人力成本] settlement_map 索引: {len(flow_names_set)} 个流量方, {len(park_to_flows)} 个园区店")

        # 解密并读取 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 []

        raw_records = []
        direct_match_count = 0
        park_match_count = 0
        park_fail_count = 0
        park_allocated_total = Decimal("0")
        failed_count = 0
        failed_stores = []

        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_gmv = find_column(df, "GMV", "产值")

            # 检核列 —— 优先使用 AF 列(索引 31)
            col_check = None
            if len(df.columns) > 31:
                col_check = df.columns[31]
                logger.info(f"[人力成本] 检核列: 使用 AF 列 (索引 31), 列名='{col_check}'")
            else:
                logger.warning(f"[人力成本] 列数不足 32 列 ({len(df.columns)}), 回退到列名查找")
                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}, "
                       f"业务归属={col_biz}, 岗位={col_position}, 薪资={col_salary}, "
                       f"检核={col_check}")

            # 用于直接匹配的流量方名称集合(已标准化)
            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

            total_rows = len(df)
            check_passed = 0
            check_skipped = 0

            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

                # 获取岗位
                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

                # ---------- 一级匹配:直接匹配 ----------
                if std_store_name in std_flow_names_set:
                    # 直接匹配成功
                    original_flow = std_to_original_flow.get(std_store_name, std_store_name)
                    raw_records.append({
                        "流量方名称": original_flow,
                        "业务类型": biz_type or "未知",
                        "技师工资": technician_salary,
                        "营销团队工资": marketing_salary,
                        "匹配方式": "direct",
                    })
                    direct_match_count += 1
                else:
                    # ---------- 二级回退:园区店匹配 ----------
                    ps = to_standard(store_name, 'yq')
                    if ps in park_to_flows:
                        related_flows = park_to_flows[ps]
                        logger.info(f"[园区店回退] 入驻门店='{store_name}' → park_store='{ps}', 命中{len(related_flows)}个流量方")

                        matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type]
                        if matching_flows:
                            # 先按 (ps, flow, biz) 精确取已入库 gmv_ratio_park,
                            # 对每个命中流量方使用其自身在园区店内的 GMV 占比分摊;
                            # 未命中比例的流量方参与"剩余金额"均分,保证金额守恒。
                            any_ratio_found = False
                            allocated_tech = Decimal("0")
                            allocated_mkt = Decimal("0")
                            ratio_hit_flows = []
                            for flow_name, flow_biz in matching_flows:
                                key_fine = (ps, flow_name, flow_biz)
                                r_val = park_to_ratio.get(key_fine)
                                if r_val is None:
                                    r_val = park_to_ratio.get((flow_biz, ps))
                                if r_val is None:
                                    r_val = park_to_ratio.get(ps)
                                if r_val is None:
                                    continue
                                any_ratio_found = True
                                r = Decimal(str(r_val))
                                tech_share = round_2(technician_salary * r)
                                mkt_share = round_2(marketing_salary * r)
                                allocated_tech += tech_share
                                allocated_mkt += mkt_share
                                ratio_hit_flows.append((flow_name, flow_biz, tech_share, mkt_share))
                                logger.debug(f"[园区店回退] 流量方={flow_name}, 业务={flow_biz}, "
                                           f"gmv_ratio_park={r}, 技师工资={tech_share}, 营销团队={mkt_share}")
                            # 先写入命中比例的流量方
                            for flow_name, flow_biz, tech_share, mkt_share in ratio_hit_flows:
                                raw_records.append({
                                    "流量方名称": flow_name,
                                    "业务类型": flow_biz,
                                    "技师工资": tech_share,
                                    "营销团队工资": mkt_share,
                                    "匹配方式": "park_ratio_db",
                                })
                            if any_ratio_found:
                                # 剩余流量方按剩余金额均分,保证总额守恒
                                missing_flows = [(fn, fb) for (fn, fb) in matching_flows
                                                 if (fn, fb) not in {(x[0], x[1]) for x in ratio_hit_flows}]
                                if missing_flows:
                                    remain_tech = technician_salary - allocated_tech
                                    remain_mkt = marketing_salary - allocated_mkt
                                    n = len(missing_flows)
                                    for flow_name, flow_biz in missing_flows:
                                        tech_share = round_2(remain_tech / n)
                                        mkt_share = round_2(remain_mkt / n)
                                        raw_records.append({
                                            "流量方名称": flow_name,
                                            "业务类型": flow_biz,
                                            "技师工资": tech_share,
                                            "营销团队工资": mkt_share,
                                            "匹配方式": "park_ratio_db",
                                        })
                                park_match_count += 1
                                park_allocated_total += allocated_tech + allocated_mkt
                                logger.info(f"[园区店回退] park_ratio_db分摊成功: park_store='{ps}', "
                                           f"命中{len(ratio_hit_flows)}个流量方, 技师工资分摊={allocated_tech}, "
                                           f"营销团队分摊={allocated_mkt}")
                            else:
                                # 无比例信息,全部平均分摊
                                n = len(matching_flows)
                                tech_share_each = technician_salary / n
                                mkt_share_each = marketing_salary / n
                                avg_allocated_tech = Decimal("0")
                                avg_allocated_mkt = Decimal("0")
                                for flow_name, flow_biz in matching_flows:
                                    t_share = round_2(tech_share_each)
                                    m_share = round_2(mkt_share_each)
                                    avg_allocated_tech += t_share
                                    avg_allocated_mkt += m_share
                                    raw_records.append({
                                        "流量方名称": flow_name,
                                        "业务类型": flow_biz,
                                        "技师工资": t_share,
                                        "营销团队工资": m_share,
                                        "匹配方式": "park_avg",
                                    })
                                park_match_count += 1
                                park_allocated_total += avg_allocated_tech + avg_allocated_mkt
                                logger.info(f"[园区店回退] park_avg平均分摊: park_store='{ps}', "
                                           f"共{n}个流量方, 技师工资={avg_allocated_tech}, 营销团队={avg_allocated_mkt}")
                        else:
                            park_fail_count += 1
                            failed_count += 1
                            logger.warning(f"[园区店回退] park_store='{ps}' 无匹配业务类型={biz_type}的流量方, "
                                           f"入驻门店='{store_name}'")
                            if len(failed_stores) < 10:
                                failed_stores.append(store_name)
                    else:
                        # 匹配失败
                        park_fail_count += 1
                        failed_count += 1
                        logger.warning(f"[园区店回退] 入驻门店='{store_name}' 归一化后 park_store='{ps}' "
                                       f"未命中任何园区店, 无法分摊")
                        if len(failed_stores) < 10:
                            failed_stores.append(store_name)

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

        # 检核过滤统计日志
        logger.info(f"[人力成本] 检核过滤: 总行数={total_rows}, 通过={check_passed}, 过滤掉={check_skipped}")

        # 日志汇总
        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:
            logger.info("[人力成本] 无有效数据")
            return []

        # 按 (流量方名称, 业务类型) 汇总
        aggregated = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
        for r in raw_records:
            key = (r["流量方名称"], r["业务类型"])
            aggregated[key]["技师工资"] += r["技师工资"]
            aggregated[key]["营销团队工资"] += r["营销团队工资"]

        result = []
        for (flow, biz), salaries in aggregated.items():
            result.append({
                "流量方名称": flow,
                "业务类型": biz,
                "技师工资": round_2(salaries["技师工资"]),
                "营销团队工资": round_2(salaries["营销团队工资"]),
            })

        # 计算总量守恒
        total_input = sum(
            technician_salary + marketing_salary
            for r in raw_records
            for technician_salary, marketing_salary in [(r["技师工资"], r["营销团队工资"])]
        )
        total_output = sum(
            r["技师工资"] + r["营销团队工资"]
            for r in result
        )
        logger.info(f"[人力成本] 总量校验: 原始输入={total_input}, 输出汇总={total_output}, 差值={total_input - total_output}")

        logger.info(f"[人力成本] 解析完成,共 {len(result)} 条记录")
        return result

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

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

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

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

        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_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", "产值")

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

                target = str(target).strip()

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

                # 仅统计 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:
                        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:
                    continue

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

                # 判断是否为园区店
                is_park_store = "园区" in std_target or "园区店" in std_target

                raw_records.append({
                    "流量方名称": std_target,
                    "原始名称": target,
                    "业务类型": BIZ_TYPE_1_1,
                    "房租及水电费": total_fee,
                    "gmv": gmv,
                    "is_park_store": is_park_store,
                })

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

        # 按 (流量方, 业务类型) 分组
        # 先汇总非园区店数据
        direct_grouped = defaultdict(lambda: {"房租及水电费": Decimal("0"), "gmv_sum": Decimal("0")})
        for r in raw_records:
            if r["is_park_store"]:
                continue
            key = (r["流量方名称"], r["业务类型"])
            direct_grouped[key]["房租及水电费"] += r["房租及水电费"]
            direct_grouped[key]["gmv_sum"] += r["gmv"]

        # 汇总园区店数据
        park_store_grouped = defaultdict(lambda: Decimal("0"))
        for r in raw_records:
            if not r["is_park_store"]:
                continue
            key = (r["流量方名称"], r["业务类型"])
            park_store_grouped[key] += r["房租及水电费"]

        # 构建结果
        result = []
        for (flow, biz), data in direct_grouped.items():
            result.append({
                "流量方名称": flow,
                "业务类型": biz,
                "房租及水电费": round_2(data["房租及水电费"]),
            })

        # 园区店回退匹配
        # 检查 direct_grouped 中没有的流量方,使用园区店数据
        matched_park_stores = set()
        for (flow, biz) in direct_grouped.keys():
            for (park_flow, park_biz) in park_store_grouped.keys():
                if park_biz == biz and park_flow in flow:
                    matched_park_stores.add((park_flow, park_biz))

        # 未直接匹配的流量方,使用园区店数据(按GMV分摊)
        for (park_flow, biz), fee in park_store_grouped.items():
            if (park_flow, biz) not in matched_park_stores:
                # 查找使用该园区店的流量方
                related_flows = []
                for (flow, flow_biz) in direct_grouped.keys():
                    if flow_biz == biz and park_flow in flow:
                        related_flows.append(flow)

                if related_flows:
                    # 尝试使用数据库比例
                    db_ratio = None
                    ratio_source = None
                    if settlement_map:
                        for flow in related_flows:
                            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"]
                                    ratio_source = "settlement"
                                    break
                            if db_ratio is not None:
                                break

                    if db_ratio is None and park_ratio_map:
                        pr_key = (biz, park_flow)
                        if pr_key in park_ratio_map:
                            db_ratio = park_ratio_map[pr_key]
                            ratio_source = "park"

                    if db_ratio is not None:
                        if ratio_source == "settlement":
                            logger.info(f"[房租水电分摊] 流量方匹配成功,使用 gmv_ratio={db_ratio}")
                        else:
                            logger.info(f"[房租水电分摊] 流量方匹配失败,尝试园区店匹配,使用 gmv_ratio_park={db_ratio}")
                        for flow in related_flows:
                            if (flow, biz) in direct_grouped:
                                share = fee * db_ratio

                                found = False
                                for r in result:
                                    if r["流量方名称"] == flow and r["业务类型"] == biz:
                                        r["房租及水电费"] = round_2(r["房租及水电费"] + share)
                                        found = True
                                        break
                                if not found:
                                    result.append({
                                        "流量方名称": flow,
                                        "业务类型": biz,
                                        "房租及水电费": round_2(share),
                                    })
                    else:
                        logger.warning("[房租水电分摊] 比例缺失,降级为Excel计算")
                        # 按流量方的GMV占比分摊园区店费用
                        total_gmv = sum(direct_grouped[(f, biz)]["gmv_sum"] for f in related_flows if (f, biz) in direct_grouped)
                        for flow in related_flows:
                            if (flow, biz) in direct_grouped:
                                flow_gmv = direct_grouped[(flow, biz)]["gmv_sum"]
                                if total_gmv > 0 and flow_gmv > 0:
                                    ratio = flow_gmv / total_gmv
                                    share = fee * ratio
                                else:
                                    # 无GMV信息,平均分摊
                                    n = len(related_flows)
                                    share = fee / n

                                # 累加
                                found = False
                                for r in result:
                                    if r["流量方名称"] == flow and r["业务类型"] == biz:
                                        r["房租及水电费"] = round_2(r["房租及水电费"] + share)
                                        found = True
                                        break
                                if not found:
                                    result.append({
                                        "流量方名称": flow,
                                        "业务类型": biz,
                                        "房租及水电费": round_2(share),
                                    })
                else:
                    # 无关联流量方,直接输出园区店数据
                    result.append({
                        "流量方名称": park_flow,
                        "业务类型": biz,
                        "房租及水电费": round_2(fee),
                        "__park_store__": True,
                    })

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

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

    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):
        """
        生成成本汇总表。
        综合结算数据、市场费、外援施工费、人力成本、房租水电施工费,
        按流量方/业务类型/品牌维度汇总各项费用,并计算占比。
        返回:List[dict],每条记录对应 biz_budget_achieve 的一行
        """
        _seen_sp = set()
        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 ""))

        # 外援施工费
        for r in wage_results:
            all_keys.add((r["流量方名称"], r["业务类型"], ""))

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

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

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

        # ---------- 预先按 (流量方, 业务类型) 聚合无品牌的费用 ----------
        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}")

        wage_agg = defaultdict(lambda: Decimal("0"))
        for w in wage_results:
            key = (w["流量方名称"].strip(), w["业务类型"].strip())
            wage_agg[key] += w["外援施工费"]

        utility_agg = defaultdict(lambda: Decimal("0"))
        for u in utility_results:
            if u.get("__park_store__"):
                continue
            key = (u["流量方名称"].strip(), u["业务类型"].strip())
            utility_agg[key] += u["房租及水电费"]

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

        for flow_name, biz_type, brand in sorted(all_keys):
            # 清理空格
            flow_name = flow_name.strip() if flow_name else ""
            biz_type = biz_type.strip() if biz_type else ""
            brand = brand.strip() if brand 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,
                "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("品牌", "")
                if (m["流量方名称"] == flow_name
                        and m["业务类型"] == biz_type
                        and (m_brand == brand or not brand or not m_brand)):
                    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}")

            # 计算本品牌的分摊比例 —— 优先使用已入库 gmv_ratio
            flow_biz_ratio = Decimal("1")
            ratio_source = "gmv_calc"  # 记录比例来源
            db_ratio = gmv_lookup[settle_key].get("gmv_ratio") if settle_key in gmv_lookup else None
            if db_ratio is None:
                # 尝试无品牌版本
                nk = (flow_name, biz_type, "")
                if nk in gmv_lookup:
                    db_ratio = gmv_lookup[nk].get("gmv_ratio")
            if db_ratio is not None:
                flow_biz_ratio = Decimal(str(float(db_ratio)))
                ratio_source = "db_gmv_ratio"
                logger.debug(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"
                logger.debug(f"[比例来源] 回退 GMV 计算分摊 ratio={flow_biz_ratio} (流量方={flow_name}, 业务={biz_type}, 品牌={brand})")

            # --- 外援施工费(按 GMV 占比分摊)---
            wage_key = (flow_name, biz_type)
            if wage_key in wage_agg:
                row["外援施工"] += round_2(wage_agg[wage_key] * flow_biz_ratio)

            # --- 人力成本(单品牌全额,多品牌按 GMV 占比分摊)---
            labor_key = (flow_name, biz_type)
            if labor_key in labor_agg:
                if brand_count <= 1:
                    # 单品牌:全额分配,不分摊
                    row["技师工资"] += labor_agg[labor_key]["技师工资"]
                    row["营销团队工资"] += labor_agg[labor_key]["营销团队工资"]
                    logger.debug(f"[人力成本分配] 单品牌全额: 流量方={flow_name}, 业务={biz_type}, "
                               f"品牌={brand}, 技师工资={labor_agg[labor_key]['技师工资']}, "
                               f"营销团队={labor_agg[labor_key]['营销团队工资']}")
                else:
                    # 多品牌:按 GMV 占比分摊
                    tech_share = round_2(labor_agg[labor_key]["技师工资"] * flow_biz_ratio)
                    mkt_share = round_2(labor_agg[labor_key]["营销团队工资"] * flow_biz_ratio)
                    row["技师工资"] += tech_share
                    row["营销团队工资"] += mkt_share
                    logger.debug(f"[人力成本分配] 多品牌分摊: 流量方={flow_name}, 业务={biz_type}, "
                               f"品牌={brand}, 分摊比例={flow_biz_ratio}, "
                               f"技师工资分摊={tech_share}, 营销团队分摊={mkt_share}")

            # --- 房租水电(按 GMV 占比分摊)---
            utility_key = (flow_name, biz_type)
            if utility_key in utility_agg:
                row["房租及水电费"] += round_2(utility_agg[utility_key] * flow_biz_ratio)

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

            # ---------- 计算占比 ----------
            # 市场费本月占比 = 市场费/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["技师工资"], revenue)
            # 营销团队工资占比 = 营销团队工资/产值*100%
            row["营销团队工资占比"] = pct(row["营销团队工资"], revenue)
            # 人员工资本月占比 = 人员工资/产值*100%
            row["人员工资本月占比"] = pct(row["人员工资"], revenue)
            
            # 人员工资上月占比 - 从历史数据查询
            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"]

            # ---------- 计算毛利相关字段 ----------
            # F公司毛利 - 仅服务商=嘀加自营时计算
            sp = (service_provider or "").strip()
            is_dijia_self = "嘀加自营" in sp
            if sp and sp not in _seen_sp:
                _seen_sp.add(sp)
                logger.info(f"[毛利计算] 服务商类型: '{sp}', 含嘀加自营={is_dijia_self}")
            f_company_gross_profit = Decimal("0")
            if is_dijia_self:
                f_company_gross_profit = service_fee - row["人员工资"]
                f_company_gross_profit = round_2(f_company_gross_profit)
            row["F公司毛利"] = f_company_gross_profit
            
            # 毛利计算
            # 服务商=嘀加自营时:毛利 = 嘀加分润 - 市场费 - 房租水电 - 装修摊销 - 门店耗材 + F公司毛利
            # 服务商≠嘀加自营时:毛利 = 嘀加分润 - 市场费 - 房租水电 - 装修摊销 - 门店耗材
            if is_dijia_self:
                gross_profit = dijia_profit - row["市场费"] - row["房租及水电费"] - renovation - consumables + f_company_gross_profit
            else:
                gross_profit = dijia_profit - row["市场费"] - row["房租及水电费"] - renovation - consumables
            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"))

            # 四舍五入所有金额
            for key in ["市场费", "外援施工", "技师工资", "营销团队工资", "人员工资", 
                        "房租及水电费", "F公司毛利", "毛利"]:
                row[key] = round_2(row[key])

            summary.append(row)

        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"]

                # 优先使用数据库中的 gmv_ratio
                db_ratio = None
                if settlement_map:
                    for (fn, bt, br), sv in settlement_map.items():
                        if fn == s["流量方名称"] 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))
                    logger.info(f"[成本汇总分摊] 使用数据库比例 流量方={s['流量方名称']} gmv_ratio={db_ratio}")
                elif biz_total_gmv[biz] > 0 and gmv > 0:
                    brand_ratio = gmv / biz_total_gmv[biz]
                else:
                    logger.warning(f"[成本汇总分摊] 比例缺失且无GMV数据,流量方={s['流量方名称']}")

                if biz in park_utility_agg:
                    s["房租及水电费"] += round_2(park_utility_agg[biz] * brand_ratio)

            # 重新计算占比和毛利(使用与主循环一致的公式)
            for s in summary:
                gmv = s["GMV"]
                revenue = s["产值"]
                s["市场费本月占比"] = pct(s["市场费"], gmv)
                s["技师工资占比"] = pct(s["技师工资"], revenue)
                s["营销团队工资占比"] = pct(s["营销团队工资"], revenue)
                s["人员工资本月占比"] = pct(s["人员工资"], revenue)
                
                # 重新计算 F公司毛利 和 毛利(使用正确公式)
                sp_recalc = (s.get("服务商", "") or "").strip()
                is_dijia_self = "嘀加自营" in sp_recalc
                f_company_gp = Decimal("0")
                if is_dijia_self:
                    svc_fee = s.get("服务费", Decimal("0"))
                    f_company_gp = round_2(svc_fee - s["人员工资"])
                s["F公司毛利"] = f_company_gp
                
                dijia_profit_sharing = s.get("嘀加分润", Decimal("0"))
                renovation_amort = s.get("装修摊销", Decimal("0"))
                store_consum = s.get("门店耗材", Decimal("0"))
                
                if is_dijia_self:
                    gp = dijia_profit_sharing - s["市场费"] - s["房租及水电费"] - renovation_amort - store_consum + f_company_gp
                else:
                    gp = dijia_profit_sharing - s["市场费"] - s["房租及水电费"] - renovation_amort - store_consum
                s["毛利"] = round_2(gp)
                s["毛利率本月"] = pct(gp, gmv)

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

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

    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}"
        )

        # 写入诊断日志:待更新数量 + 前 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:
                # 构建命名字典参数(包含 WHERE 和 SET 所需的所有字段)
                bind_params = {}
                for col in where_columns + update_columns:
                    bind_params[col] = params.get(col, 0)
                # brand 为空字符串时需要特殊处理
                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"[写入] 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"),
            ("市场费", "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"),
            ("房租及\n水电费", "rent_utilities"),
            ("装修摊销", "renovation_amortization"),
            ("门店耗材", "store_consumables"),
            ("F公司毛利", "f_company_gross_profit"),
            ("毛利", "gross_profit"),
            ("本月毛利率", "gross_profit_ratio_current"),
            ("上月毛利率", "gross_profit_ratio_previous"),
        ]
        HEADERS = [h for h, _ in ORDERED]

        # 列分类(用于数字格式)
        AMOUNT_COLS = {'GMV', '收入', '成本(GMV口径)', '流量费(GMV口径)', '服务费',
                       '成本(收入口径)', '流量费(收入口径)', '嘀加分润', '市场费', '人员工资',
                       '外援施工', '技师工资', '营销团队工资', '房租及水电费', '装修摊销', '门店耗材',
                       'F公司毛利', '毛利'}
        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

        # 列宽
        column_widths = {
            "是否为多品类": 10, "流量方名称": 18, "业务类型": 9, "主体": 14,
            "品牌": 8, "园区店": 18, "服务商": 14, "订单数": 8, "GMV": 14, "收入": 14,
            "成本(GMV口径)": 14, "本月占比": 11, "上月占比": 11,
            "流量费(GMV口径)": 14, "服务费": 12, "成本(收入口径)": 14, "流量费(收入口径)": 14,
            "嘀加分润": 12, "市场费": 12, "人员工资": 12, "外援施工": 11, "技师工资": 11,
            "技师工资占比": 12, "营销团队工资": 13, "营销团队工资占比": 14,
            "房租及水电费": 13, "装修摊销": 11, "门店耗材": 11,
            "F公司毛利": 12, "毛利": 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:
                    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

        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)