endpoints.py 70.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 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
# -*- coding: utf-8 -*-
"""
文件名: app/api/endpoints.py
职责: 定义 FastAPI 路由接口,处理前端请求并调用 Service 层逻辑。
注意: 不要删除这个注释。
"""

import glob, os, re
from datetime import datetime
from fastapi import APIRouter, HTTPException, Query, UploadFile, File, Form, BackgroundTasks
from fastapi.responses import FileResponse
from typing import Optional
from app.services.etl_service import ETLService
from app.services.excel_service import ExcelService
from app.services.analysis_service import AnalysisService
from app.services.harmony_analysis_service import HarmonyAnalysisService, _find_latest_template
from app.services.strategy_service import StrategyService, get_task_state
from app.services.upload_service import (
    import_store_guarantee, import_oem_delivery, get_upload_history,
)
from app.services.file_naming import (
    build_filename,
    build_store_filename,
    build_factory_filename,
    build_analysis_output_filename,
    ensure_unique_filename
)
from app.core.scheduler import SchedulerManager
import os
import shutil
import logging

logger = logging.getLogger("app.api")
router = APIRouter()

# 统一上传基础目录,所有文件按日期目录分级存放
UPLOAD_BASE = "temp_uploads"
os.makedirs(UPLOAD_BASE, exist_ok=True)

# 临时目录,用于存放未正式保存的文件
DRAFT_BASE = os.path.join(UPLOAD_BASE, "drafts")
os.makedirs(DRAFT_BASE, exist_ok=True)


def _date_path(filename: str, category: str = "") -> str:
    """生成文件路径: 
    - 如果 category="drafts",则存放在 temp_uploads/drafts/filename
    - 否则存放在 temp_uploads/category/YYYYMMDD/filename
    """
    if category == "drafts":
        target_dir = DRAFT_BASE
    else:
        today = datetime.now().strftime("%Y%m%d")
        target_dir = os.path.join(UPLOAD_BASE, category, today) if category else os.path.join(UPLOAD_BASE, today)
    
    os.makedirs(target_dir, exist_ok=True)
    return os.path.join(target_dir, filename)


def _find_file(filename: str) -> Optional[str]:
    """在 temp_uploads 下递归查找指定文件名,返回完整路径或 None"""
    for root, _dirs, files in os.walk(UPLOAD_BASE):
        if filename in files:
            return os.path.join(root, filename)
    return None

XLSX_DIR = os.path.join("app", "templates", "xlsx")

@router.post("/data/upload")
async def upload_data(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(...),
    table_name: Optional[str] = Form(None),
    upload_type: Optional[str] = Form(None),
    version_tag: Optional[str] = Form(None)
):
    """上传 Excel 并导入。支持 ODS 固定表或动态分析表。"""
    # 记录接收到的参数,方便调试 422 错误
    logger.info(f"Upload request received: filename={file.filename}, table_name={table_name}, upload_type={upload_type}, tag={version_tag}")
    
    file_path = _date_path(file.filename, category="drafts")
    try:
        # 1. 保存临时文件
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        
        # 2. 判断同步模式
        if table_name and table_name.strip() != "" and table_name.startswith("ods_"):
            # ODS 固定表模式
            rows = await ExcelService.upload_to_ods(file_path, table_name)
            # 处理完后删除文件
            if os.path.exists(file_path): os.remove(file_path)
            return {
                "status": "success",
                "message": f"成功导入 {rows} 行数据到 {table_name}",
                "rows": rows
            }
        else:
            # 动态分析模式
            if not upload_type:
                if os.path.exists(file_path): os.remove(file_path)
                raise HTTPException(status_code=400, detail="智能分析模式下必须选择'分析数据类型'")

            # 使用后台任务处理 LLM 分析和导入
            background_tasks.add_task(
                ExcelService.process_dynamic_upload, 
                file_path, file.filename, upload_type, version_tag
            )
            return {
                "status": "success",
                "message": f"文件 {file.filename} 已上传,正在使用 LLM 进行结构分析并导入后台,请稍后在数据目录查看结果。",
                "upload_type": upload_type
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Upload processing failed: {e}", exc_info=True)
        if os.path.exists(file_path): os.remove(file_path)
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/etl/status")
async def get_etl_status():
    """获取数据同步状态"""
    try:
        return await ETLService.get_sync_status()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/etl/history")
async def get_etl_history(
    task_id: str = Query(None), 
    limit: int = Query(10),
    task_pattern: str = Query(None)
):
    """获取执行历史
    
    - task_id: 精确匹配
    - task_pattern: LIKE 模糊匹配,如 '%_ods_sync' 匹配所有 ODS 同步任务
    """
    try:
        return await ETLService.get_etl_history(task_id=task_id, limit=limit, task_pattern=task_pattern)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/etl/scheduler-config")
async def get_scheduler_config(task_id: str = "sync_ods_data"):
    """获取定时任务配置"""
    try:
        # 从 SchedulerManager 获取作业信息
        job = SchedulerManager._scheduler.get_job(task_id)
        if not job:
            return {"task_id": task_id, "status": "not_found"}
        
        return {
            "task_id": job.id,
            "next_run_time": str(job.next_run_time),
            "trigger": str(job.trigger),
            "status": "active"
        }
    except Exception as e:
        return {"task_id": task_id, "status": "error", "detail": str(e)}

@router.post("/etl/run-ods")
async def run_ods_sync(background_tasks: BackgroundTasks, source_table: str = None):
    """手动触发 ODS 同步 (后台异步执行)"""
    try:
        # 使用 BackgroundTasks 异步运行同步任务,防止阻塞主线程
        background_tasks.add_task(ETLService.run_ods_sync, source_table, "manual_ods_sync")
        return {
            "status": "success", 
            "message": "ODS 同步任务已在后台启动,请查看执行历史获取进度。"
        }
    except Exception as e:
        logger.error(f"Failed to start background ODS sync: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/etl/run-dw")
async def run_dw_sync(
    background_tasks: BackgroundTasks, 
    layer: str = Form(None),
    start_date: str = Form(None),
    end_date: str = Form(None),
    full_sync: str = Form(None)
):
    """手动触发 DWS/DWM/DWA 加工 (后台异步执行)
    - 默认增量同步(最近一天)
    - full_sync=true 时全量覆盖
    - 指定 start_date/end_date 时按日期范围处理
    - 参数支持 Form 或 Query 方式传递
    """
    try:
        if not layer:
            raise HTTPException(status_code=400, detail="缺少必要参数: layer")
        task_id = f"manual_{layer.lower()}_sync"
        background_tasks.add_task(ETLService.run_dw_sync, layer, start_date, end_date, task_id, full_sync)
        return {
            "status": "success", 
            "message": f"{layer} 加工任务已在后台启动,请查看执行历史获取进度。"
        }
    except Exception as e:
        logger.error(f"Failed to start background {layer} sync: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/etl/run-dw")
async def run_dw_sync_get(
    background_tasks: BackgroundTasks,
    layer: str = Query(...),
    start_date: str = Query(None),
    end_date: str = Query(None),
    full_sync: str = Query(None)
):
    """GET 方式触发 DWS/DWM/DWA 加工 (支持 Query 参数)
    - 用法: GET /api/etl/run-dw?layer=DWS&full_sync=true
    """
    try:
        task_id = f"manual_{layer.lower()}_sync"
        background_tasks.add_task(ETLService.run_dw_sync, layer, start_date, end_date, task_id, full_sync)
        return {
            "status": "success",
            "message": f"{layer} 加工任务已在后台启动,请查看执行历史获取进度。"
        }
    except Exception as e:
        logger.error(f"Failed to start background {layer} sync: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ==================== 数据分析接口 ====================

XLSX_DIR = os.path.join("app", "templates", "xlsx")

def _find_latest_wenjie_template():
    """返回最新的问界门店数据模板(最大序号),无带序号文件时回退到默认"""
    max_no = 0
    for f in glob.glob(os.path.join(XLSX_DIR, "门店数据-问界-模板[0-9][0-9][0-9].xlsx")):
        m = re.search(r"门店数据-问界-模板(\d{3})\.xlsx", os.path.basename(f))
        if m:
            max_no = max(max_no, int(m.group(1)))
    if max_no > 0:
        return os.path.join(XLSX_DIR, f"门店数据-问界-模板{max_no:03d}.xlsx")
    # 回退到默认模板
    fallback = os.path.join(XLSX_DIR, "门店数据-问界-模板001.xlsx")
    if os.path.exists(fallback):
        return fallback
    return None


def _load_store_df_from_batch(batch_no: str) -> "pd.DataFrame":
    """从DB加载门店兜底配置批次,返回可直接用于build_report的DataFrame"""
    from app.services.upload_service import _get_conn
    import pandas as pd

    conn = _get_conn()
    try:
        with conn.cursor() as cur:
            cur.execute("SELECT id FROM upload_batch WHERE batch_no=%s AND data_type='store_guarantee'", (batch_no,))
            batch = cur.fetchone()
            if not batch:
                raise HTTPException(status_code=404, detail=f"批次 {batch_no} 不存在")

            cur.execute(
                """SELECT store_name, guarantee_target, guarantee_type,
                   special_case_1, special_case_2,
                   ew_conversion_rate, ax_conversion_rate, battery_conversion_rate,
                   ew_compensation, ax_compensation, battery_compensation,
                   guarantee_end_date
                   FROM store_guarantee_config WHERE batch_id=%s""",
                (batch["id"],))
            rows = cur.fetchall()
            if not rows:
                raise HTTPException(status_code=400, detail="批次中无数据")

        df = pd.DataFrame(rows)
        df['门店名'] = df['store_name']
        df['兜底指标'] = df['guarantee_target']
        df['兜底类型'] = df['guarantee_type']
        df['特殊情况1'] = df['special_case_1']
        df['特殊情况2'] = df['special_case_2']
        df['达标转化率_整车延保'] = df['ew_conversion_rate']
        df['达标转化率_安心包'] = df['ax_conversion_rate']
        df['达标转化率_电池'] = df['battery_conversion_rate']
        df['每单赔付金额_整车'] = df['ew_compensation']
        df['每单赔付金额_安心包'] = df['ax_compensation']
        df['每单赔付金额_电池'] = df['battery_compensation']
        df['兜底截止日期'] = df['guarantee_end_date']
        return df
    finally:
        conn.close()


def _format_factory_sheet_name(start: str, end: str) -> str:
    """将 yyyy-MM-dd 日期范围格式化为 sheet 名,如 626-722"""
    from datetime import datetime
    s = datetime.strptime(str(start)[:10], "%Y-%m-%d")
    e = datetime.strptime(str(end)[:10], "%Y-%m-%d")
    return f"{s.month}{s.day:02d}-{e.month}{e.day:02d}"


def _is_ecology_period(start: str, period_type: str = "") -> bool:
    """判断主机厂数据周期是否为生态月"""
    pt = (period_type or "").strip().lower()
    if pt == "ecology":
        return True
    if pt == "nature":
        return False
    if start and len(str(start)) >= 10:
        return int(str(start)[8:10]) >= 20
    return False


def _oem_rows_to_factory_df(rows) -> "pd.DataFrame":
    import pandas as pd
    df = pd.DataFrame(rows)
    df['门店名'] = df['store_name']
    df['厅店代码'] = df['store_code']
    if 'store_short_name' in df.columns:
        df['厅店简称'] = df['store_short_name'].fillna('')
    if 'enabler' in df.columns:
        df['赋能商'] = df['enabler'].fillna('')
    df['区域(省)'] = df['province']
    df['交付数'] = pd.to_numeric(df['delivery_count'], errors='coerce').fillna(0)
    df['整车延保采购数'] = pd.to_numeric(df['ew_purchase_count'], errors='coerce').fillna(0)
    df['安心包采购数'] = pd.to_numeric(df['ax_purchase_count'], errors='coerce').fillna(0)
    df['电池延保采购数'] = pd.to_numeric(df['battery_purchase_count'], errors='coerce').fillna(0)
    df['轮胎险采购数'] = pd.to_numeric(df['tire_purchase_count'], errors='coerce').fillna(0)
    if 'worry_free_purchase_count' in df.columns:
        df['无忧套餐采购数'] = pd.to_numeric(df['worry_free_purchase_count'], errors='coerce').fillna(0)
    else:
        df['无忧套餐采购数'] = 0
    if 'unit_value_per_vehicle' in df.columns:
        df['单车产值'] = pd.to_numeric(df['unit_value_per_vehicle'], errors='coerce').fillna(0)
    else:
        df['单车产值'] = 0
    return df.drop_duplicates(subset=["门店名"], keep="first")


def _load_oem_factory_from_batch(batch_no: str) -> tuple:
    """从DB加载OEM交付批次,按 excel_sheet_name / period_type 拆成多 Sheet。

    返回 ({sheet_name: DataFrame}, batch_meta),其中 meta 含:
      sheets: [{name, period_type, data_period_start, data_period_end, total}, ...]
      has_ecology / has_nature
    """
    from collections import OrderedDict
    from app.services.upload_service import _get_conn, _infer_oem_sheet_period

    conn = _get_conn()
    try:
        with conn.cursor() as cur:
            cur.execute(
                """SELECT id, data_period_start, data_period_end, period_type
                   FROM upload_batch
                   WHERE batch_no=%s AND data_type='oem_delivery' AND status != 3""",
                (batch_no,),
            )
            batch = cur.fetchone()
            if not batch:
                raise HTTPException(status_code=404, detail=f"批次 {batch_no} 不存在")

            cur.execute(
                """SELECT store_code, store_name, store_short_name, province, enabler,
                   delivery_count, ew_purchase_count, ax_purchase_count,
                   battery_purchase_count, tire_purchase_count,
                   worry_free_purchase_count, unit_value_per_vehicle,
                   excel_sheet_name, period_type,
                   data_period_start, data_period_end
                   FROM oem_delivery_data WHERE batch_id=%s
                   ORDER BY id""",
                (batch["id"],),
            )
            rows = cur.fetchall()
            if not rows:
                return {}, {}

        batch_start = str(batch.get("data_period_start") or "")[:10]
        batch_end = str(batch.get("data_period_end") or "")[:10]
        batch_pt = (batch.get("period_type") or "").strip().lower()

        groups = OrderedDict()
        for r in rows:
            sn = (r.get("excel_sheet_name") or "").strip()
            key = sn or "__default__"
            groups.setdefault(key, []).append(r)

        sheets = {}
        sheet_metas = []
        for key, group_rows in groups.items():
            first = group_rows[0]
            pt = (first.get("period_type") or "").strip().lower()
            start = str(first.get("data_period_start") or "")[:10]
            end = str(first.get("data_period_end") or "")[:10]

            if key == "__default__":
                name = (
                    _format_factory_sheet_name(start or batch_start, end or batch_end)
                    if (start or batch_start) and (end or batch_end)
                    else batch_no
                )
                if not pt:
                    pt = "ecology" if _is_ecology_period(start or batch_start, batch_pt) else "nature"
                if not start:
                    start = batch_start
                if not end:
                    end = batch_end
            else:
                name = key
                if not pt or not start or not end:
                    inferred_pt, inferred_start, inferred_end = _infer_oem_sheet_period(name)
                    pt = pt or inferred_pt
                    start = start or inferred_start
                    end = end or inferred_end
                if not pt:
                    pt = "ecology" if _is_ecology_period(start, batch_pt) else "nature"

            # 同名冲突时加后缀
            final_name = name
            if final_name in sheets:
                final_name = f"{name}_{len(sheets) + 1}"

            sheets[final_name] = _oem_rows_to_factory_df(group_rows)
            sheet_metas.append({
                "name": final_name,
                "period_type": pt,
                "data_period_start": start,
                "data_period_end": end,
                "total": len(group_rows),
            })

        meta = {
            "period_type": batch_pt,
            "data_period_start": batch_start,
            "data_period_end": batch_end,
            "sheets": sheet_metas,
            "has_ecology": any(s["period_type"] == "ecology" for s in sheet_metas),
            "has_nature": any(s["period_type"] == "nature" for s in sheet_metas),
        }
        return sheets, meta
    finally:
        conn.close()


def _split_factory_sheets_by_period(sheets: dict, meta: dict) -> tuple:
    """按 sheet meta 拆成 ecology_factory / nature_factory。"""
    ecology_factory = {}
    nature_factory = {}
    sheet_meta_map = {s["name"]: s for s in (meta.get("sheets") or [])}

    if meta.get("has_ecology") and meta.get("has_nature"):
        for sn, df in sheets.items():
            pt = (sheet_meta_map.get(sn) or {}).get("period_type") or ""
            if pt == "ecology":
                ecology_factory[sn] = df
            else:
                nature_factory[sn] = df
        return ecology_factory, nature_factory

    if len(sheets) > 1:
        # 多 Sheet 但未标齐:交给 build_report 按 sheet 名自动拆分
        return sheets, {}

    if _is_ecology_period(meta.get("data_period_start"), meta.get("period_type")):
        return sheets, {}
    return {}, sheets

def _load_oem_factory_by_period(brand: str, start: str, end: str, period_type: str = "") -> dict:
    """按数据周期从DB查找主机厂批次并加载"""
    from app.services.upload_service import _get_conn

    if not start or not end:
        return {}
    conn = _get_conn()
    try:
        with conn.cursor() as cur:
            cur.execute(
                """SELECT batch_no FROM upload_batch
                   WHERE brand=%s AND data_type='oem_delivery' AND status != 3
                   AND data_period_start=%s AND data_period_end=%s
                   AND IFNULL(period_type,'')=%s
                   ORDER BY id DESC LIMIT 1""",
                (brand, start[:10], end[:10], period_type or ""),
            )
            row = cur.fetchone()
            if not row and period_type:
                cur.execute(
                    """SELECT batch_no FROM upload_batch
                       WHERE brand=%s AND data_type='oem_delivery' AND status != 3
                       AND data_period_start=%s AND data_period_end=%s
                       ORDER BY id DESC LIMIT 1""",
                    (brand, start[:10], end[:10]),
                )
                row = cur.fetchone()
        if not row:
            return {}
        sheets, _ = _load_oem_factory_from_batch(row["batch_no"])
        return sheets
    finally:
        conn.close()


@router.get("/analysis/template/{template_type}")
async def download_analysis_template(template_type: str):
    """下载分析模板文件"""
    template_map = {
        # store 使用动态查找最新带序号的模板
        "factory": "主机厂数据-问界-模板002.xlsx",
        "output": "输出模板-问界-模板002.xlsx",
    }

    if template_type == "store":
        file_path = _find_latest_wenjie_template()
        if not file_path:
            raise HTTPException(status_code=404, detail="门店数据模板文件不存在")
        filename = os.path.basename(file_path)
    else:
        filename = template_map.get(template_type)
        if not filename:
            raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")
        # 查找模板文件
        search_paths = [
            os.path.join(XLSX_DIR, filename),
            os.path.join("docs", "test-demos", filename),
        ]
        file_path = None
        for p in search_paths:
            if os.path.exists(p):
                file_path = p
                break
        if not file_path:
            raise HTTPException(status_code=404, detail=f"模板文件不存在: {filename}")

    return FileResponse(file_path, filename=filename,
                        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")


_analysis_store_file = None  # 缓存门店文件路径
_analysis_factory_file = None  # 缓存合并主机厂文件(多 sheet,兼容旧逻辑)
_analysis_ecology_factory_file = None
_analysis_nature_factory_file = None


def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str:
    """构建带日期范围的文件名: 
    - 如果提供日期,则按正式命名规范整理
    - 否则返回带前缀和时间戳的临时名称
    """
    # 只有在提供日期范围时才应用正式命名规范
    if start_date and end_date:
        if "store" in prefix and "harmony" not in prefix:
            return build_store_filename("问界", start_date, end_date)
        elif "ecology" in prefix:
            return build_factory_filename("问界", "生态月", start_date, end_date)
        elif "nature" in prefix:
            return build_factory_filename("问界", "自然月", start_date, end_date)
        elif "harmony_store" in prefix:
            return build_store_filename("鸿蒙", start_date, end_date)
        elif "harmony_factory" in prefix:
            return build_factory_filename("鸿蒙", "", start_date, end_date)
    
    # 没有日期范围时,使用临时命名方式
    stem, ext = os.path.splitext(original_name)
    ts = datetime.now().strftime("%H%M%S")
    return f"{prefix}_{stem}_{ts}{ext}"


@router.post("/analysis/upload")
async def analysis_upload(
    store_file: Optional[UploadFile] = File(None),
    factory_file: Optional[UploadFile] = File(None),
    ecology_factory_file: Optional[UploadFile] = File(None),
    nature_factory_file: Optional[UploadFile] = File(None),
    ecology_start_date: str = Form(None),
    ecology_end_date: str = Form(None),
    nature_start_date: str = Form(None),
    nature_end_date: str = Form(None),
):
    """上传门店数据、主机厂数据(生态月/自然月可分开上传,也支持多 sheet 合并文件)"""
    global _analysis_store_file, _analysis_factory_file
    global _analysis_ecology_factory_file, _analysis_nature_factory_file
    result = {"status": "success", "messages": []}

    if store_file and store_file.filename:
        fname = _build_dated_filename(store_file.filename, "analysis_store")
        file_path = _date_path(fname, category="drafts")
        with open(file_path, "wb") as f:
            shutil.copyfileobj(store_file.file, f)
        _analysis_store_file = file_path
        result["messages"].append(f"门店列表已上传: {store_file.filename}")

    def _save_factory_upload(upload_file, prefix, start_date, end_date):
        global _analysis_ecology_factory_file, _analysis_nature_factory_file, _analysis_factory_file
        fname = _build_dated_filename(upload_file.filename, prefix, start_date, end_date)
        cat = "analysis" if (start_date and end_date) else "drafts"
        file_path = _date_path(fname, category=cat)
        with open(file_path, "wb") as f:
            shutil.copyfileobj(upload_file.file, f)
        if prefix == "analysis_factory_ecology":
            _analysis_ecology_factory_file = file_path
        elif prefix == "analysis_factory_nature":
            _analysis_nature_factory_file = file_path
        else:
            _analysis_factory_file = file_path
        return file_path

    if ecology_factory_file and ecology_factory_file.filename:
        _save_factory_upload(
            ecology_factory_file, "analysis_factory_ecology",
            ecology_start_date, ecology_end_date,
        )
        result["messages"].append(f"生态月主机厂数据已上传: {ecology_factory_file.filename}")

    if nature_factory_file and nature_factory_file.filename:
        _save_factory_upload(
            nature_factory_file, "analysis_factory_nature",
            nature_start_date, nature_end_date,
        )
        result["messages"].append(f"自然月主机厂数据已上传: {nature_factory_file.filename}")

    if factory_file and factory_file.filename:
        file_path = _save_factory_upload(
            factory_file, "analysis_factory", ecology_start_date, ecology_end_date,
        )
        try:
            import pandas as pd
            sheets = pd.read_excel(file_path, sheet_name=None)
            result["factory_info"] = {
                "path": file_path,
                "sheets": list(sheets.keys()),
                "sheet_count": len(sheets),
            }
        except Exception as e:
            result["factory_info"] = {"path": file_path, "error": str(e)}
        result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")

    if not result["messages"]:
        raise HTTPException(status_code=400, detail="请至少上传一个文件")

    return result


@router.post("/analysis/save-batch")
async def analysis_save_batch(
    file_type: str = Form(...),  # "store", "ecology", "nature", "factory"
    file: UploadFile = File(...),
    period_start: str = Form(""),
    period_end: str = Form(""),
    period_type: str = Form(""),  # ecology / nature,仅 oem 使用
    brand: str = Form("问界"),
):
    """将分析页面上传的文件保存为历史批次,便于下次复用"""
    if file_type not in ("store", "factory", "ecology", "nature"):
        raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory/ecology/nature")
    if not file.filename:
        raise HTTPException(status_code=400, detail="请选择文件")

    # 保存为历史时,按命名规范整理文件名
    if file_type == "store":
        formal_name = build_store_filename(brand, period_start, period_end)
        oem_period_type = ""
    else:
        oem_period_type = period_type or ("ecology" if file_type == "ecology" else "nature" if file_type == "nature" else "")
        formal_name = build_factory_filename(brand, oem_period_type, period_start, period_end)
    
    # 确保文件名唯一并保存到 batch 目录
    file_path = _date_path(formal_name, category="batch")
    file_path = ensure_unique_filename(os.path.dirname(file_path), os.path.basename(file_path))
    file_path = os.path.join(os.path.dirname(file_path), os.path.basename(file_path)) # ensure_unique_filename returns name only or path? 
    # Let's check ensure_unique_filename definition in file_naming.py
    try:
        with open(file_path, "wb") as f:
            shutil.copyfileobj(file.file, f)
        file_size = os.path.getsize(file_path)

        if file_type == "store":
            from app.services.upload_service import import_store_guarantee
            today = datetime.now().strftime("%Y-%m-%d")
            result = import_store_guarantee(
                file_path=file_path,
                original_filename=os.path.basename(file_path),
                brand=brand,
                data_period_start=today,
                data_period_end=today,
                file_size=file_size,
                remark=file_path
            )
        else:
            from app.services.upload_service import import_oem_delivery
            result = import_oem_delivery(
                file_path=file_path,
                original_filename=os.path.basename(file_path),
                brand=brand,
                data_period_start=period_start or "",
                data_period_end=period_end or "",
                period_type=oem_period_type,
                file_size=file_size,
                remark=file_path
            )

        return {"status": "success", "data": result}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Save batch failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"保存批次失败: {str(e)}")
    finally:
        if os.path.exists(file_path):
            os.remove(file_path)


@router.post("/analysis/generate")
async def analysis_generate(
    background_tasks: BackgroundTasks,
    ecology_start_date: str = Form(None),
    ecology_end_date: str = Form(None),
    nature_start_date: str = Form(None),
    nature_end_date: str = Form(None),
    store_batch_no: str = Form(None),
    factory_batch_no: str = Form(None),
    ecology_factory_batch_no: str = Form(None),
    nature_factory_batch_no: str = Form(None),
):
    """根据已上传的数据或历史批次生成生态系数分析报表"""
    global _analysis_store_file, _analysis_factory_file
    global _analysis_ecology_factory_file, _analysis_nature_factory_file

    # 加载store_df:优先批次DB数据,其次文件,最后默认模板
    if store_batch_no:
        store_df = _load_store_df_from_batch(store_batch_no)
    elif _analysis_store_file and os.path.exists(_analysis_store_file):
        store_df = AnalysisService.read_store_list(_analysis_store_file)
    else:
        default_store = _find_latest_wenjie_template()
        if os.path.exists(default_store):
            _analysis_store_file = default_store
            store_df = AnalysisService.read_store_list(_analysis_store_file)
        else:
            raise HTTPException(status_code=400, detail="请先上传门店列表文件")

    # 加载主机厂数据:批次 / 文件 / 按日期从DB补全
    ecology_factory = {}
    nature_factory = {}

    if ecology_factory_batch_no:
        sheets, _ = _load_oem_factory_from_batch(ecology_factory_batch_no)
        ecology_factory.update(sheets)
    if nature_factory_batch_no:
        sheets, _ = _load_oem_factory_from_batch(nature_factory_batch_no)
        nature_factory.update(sheets)

    # 兼容旧版单批次选择(含多 Sheet 生态+自然)
    if factory_batch_no and not ecology_factory_batch_no and not nature_factory_batch_no:
        sheets, meta = _load_oem_factory_from_batch(factory_batch_no)
        eco_part, nat_part = _split_factory_sheets_by_period(sheets, meta)
        ecology_factory.update(eco_part)
        nature_factory.update(nat_part)
        # 若日期未传,从 sheet meta 回填
        for s in meta.get("sheets") or []:
            if s.get("period_type") == "ecology":
                if not ecology_start_date and s.get("data_period_start"):
                    ecology_start_date = s["data_period_start"]
                if not ecology_end_date and s.get("data_period_end"):
                    ecology_end_date = s["data_period_end"]
            elif s.get("period_type") == "nature":
                if not nature_start_date and s.get("data_period_start"):
                    nature_start_date = s["data_period_start"]
                if not nature_end_date and s.get("data_period_end"):
                    nature_end_date = s["data_period_end"]

    if _analysis_ecology_factory_file and os.path.exists(_analysis_ecology_factory_file):
        ecology_factory = AnalysisService.read_factory_data(_analysis_ecology_factory_file)
    if _analysis_nature_factory_file and os.path.exists(_analysis_nature_factory_file):
        nature_factory = AnalysisService.read_factory_data(_analysis_nature_factory_file)

    if _analysis_factory_file and os.path.exists(_analysis_factory_file):
        if not ecology_factory and not nature_factory:
            ecology_factory = AnalysisService.read_factory_data(_analysis_factory_file)
        elif not ecology_factory:
            ecology_factory = AnalysisService.read_factory_data(_analysis_factory_file)
        elif not nature_factory:
            nature_factory = AnalysisService.read_factory_data(_analysis_factory_file)

    if ecology_start_date and ecology_end_date and not ecology_factory:
        ecology_factory = _load_oem_factory_by_period(
            "问界", ecology_start_date, ecology_end_date, "ecology")
    if nature_start_date and nature_end_date and not nature_factory:
        nature_factory = _load_oem_factory_by_period(
            "问界", nature_start_date, nature_end_date, "nature")

    if not ecology_factory and not nature_factory:
        raise HTTPException(status_code=400, detail="请上传或选择主机厂数据文件")

    try:
        output_path = AnalysisService.build_report(
            store_df,
            ecology_factory=ecology_factory,
            nature_factory=nature_factory,
            ecology_start=ecology_start_date or None,
            ecology_end=ecology_end_date or None,
            nature_start=nature_start_date or None,
            nature_end=nature_end_date or None
        )

        # 统计信息
        ecology_stores = store_df[store_df["兜底截止日期"].apply(AnalysisService._is_ecology_deadline)]
        nature_stores = store_df[~store_df["兜底截止日期"].apply(AnalysisService._is_ecology_deadline)]

        return {
            "status": "success",
            "message": "分析报表已生成",
            "file_path": output_path,
            "download_url": f"api/analysis/download?file={os.path.basename(output_path)}",
            "ecology_store_count": len(ecology_stores),
            "nature_store_count": len(nature_stores),
            "factory_sheets": list(ecology_factory.keys()) + list(nature_factory.keys()),
        }
    except Exception as e:
        logger.error(f"Analysis generate failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")


@router.get("/analysis/download")
async def analysis_download(file: str = Query(None)):
    """下载生成的分析报表,支持指定文件名"""
    if file:
        file_path = _find_file(file)
        if not file_path:
            raise HTTPException(status_code=404, detail="指定的报表文件不存在")
        return FileResponse(
            file_path, filename=file,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )

    # 无指定时返回最新文件
    output_files = sorted(
        [os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
         for f in fs if f.startswith("问界生态系数分析") and f.endswith(".xlsx")],
        key=lambda f: os.path.getmtime(f),
        reverse=True
    )
    if not output_files:
        raise HTTPException(status_code=404, detail="未找到分析报表,请先生成")

    file_path = output_files[0]
    return FileResponse(
        file_path,
        filename=output_files[0],
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    )


# ==================== 分析预览接口 ====================

@router.post("/analysis/preview-file")
async def analysis_preview_file(
    file_type: str = Form(...),  # "store" or "factory" or "ecology" or "nature"
    file: UploadFile = File(...),
):
    """上传分析文件并返回解析后的预览数据(factory 类型返回多 sheet)"""
    import pandas as pd
    file_path = _date_path(f"_preview_{file.filename}", category="drafts")
    try:
        with open(file_path, "wb") as f:
            shutil.copyfileobj(file.file, f)

        if file_type == "store":
            df = AnalysisService.read_store_list(file_path)
            rows = df.head(100).fillna("").to_dict(orient="records")
            columns = list(df.columns)
            return {"status": "success", "data": {"columns": columns, "rows": rows, "total": len(df)}}

        data = AnalysisService.read_factory_data(file_path)
        from app.services.upload_service import _infer_oem_sheet_period
        sheets_payload = {}
        sheet_metas = []
        for name, df in data.items():
            sheets_payload[name] = {
                "columns": list(df.columns),
                "rows": df.head(100).fillna("").to_dict(orient="records"),
                "total": len(df),
            }
            pt, start, end = _infer_oem_sheet_period(str(name))
            sheet_metas.append({
                "name": name,
                "period_type": pt,
                "data_period_start": start,
                "data_period_end": end,
                "total": len(df),
            })
        return {
            "status": "success",
            "data": {
                "sheets": sheets_payload,
                "sheet_names": list(sheets_payload.keys()),
                "sheet_metas": sheet_metas,
                "has_ecology": any(s["period_type"] == "ecology" for s in sheet_metas),
                "has_nature": any(s["period_type"] == "nature" for s in sheet_metas),
            },
        }
    except Exception as e:
        logger.error(f"Analysis preview file failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"文件解析失败: {str(e)}")
    finally:
        if os.path.exists(file_path):
            os.remove(file_path)


@router.get("/analysis/batch-data")
async def analysis_batch_data(batch_no: str = Query(...)):
    """获取历史批次数据用于右侧预览;主机厂多 Sheet 时按生态/自然月分 Tab 返回"""
    import decimal
    import datetime as dt
    from app.services.upload_service import _get_conn

    conn = _get_conn()
    try:
        with conn.cursor() as cur:
            cur.execute(
                """SELECT id, batch_no, data_type, period_type,
                          data_period_start, data_period_end, file_name
                   FROM upload_batch
                   WHERE batch_no = %s AND status != 3""",
                (batch_no,),
            )
            batch = cur.fetchone()
            if not batch:
                raise HTTPException(status_code=404, detail="批次不存在")

            batch_id = batch["id"]
            data_type = batch["data_type"]

            if data_type == "store_guarantee":
                cur.execute(
                    """SELECT store_name, brand, guarantee_target, province, city,
                       direct_sale, area_supervision, flight_supervision, online_supervision,
                       guarantee_type, special_case_1, special_case_2,
                       ew_conversion_rate, ax_conversion_rate, battery_conversion_rate,
                       ew_compensation, ax_compensation, battery_compensation,
                       guarantee_end_date
                       FROM store_guarantee_config WHERE batch_id = %s""",
                    (batch_id,),
                )
                rows = cur.fetchall()
                columns = list(rows[0].keys()) if rows else []

                clean_rows = []
                for r in rows:
                    clean = {}
                    for k, v in r.items():
                        if isinstance(v, decimal.Decimal):
                            clean[k] = float(v)
                        elif isinstance(v, (dt.date, dt.datetime)):
                            clean[k] = str(v)
                        elif v is None:
                            clean[k] = ""
                        else:
                            clean[k] = v
                    clean_rows.append(clean)

                return {
                    "status": "success",
                    "data": {
                        "columns": columns,
                        "rows": clean_rows,
                        "total": len(rows),
                        "period_type": batch.get("period_type") or "",
                        "data_period_start": str(batch.get("data_period_start") or "")[:10],
                        "data_period_end": str(batch.get("data_period_end") or "")[:10],
                        "file_name": batch.get("file_name") or "",
                    },
                }
    finally:
        conn.close()

    # 主机厂:按 Sheet / period_type 拆分预览(与上传预览结构一致)
    sheets, meta = _load_oem_factory_from_batch(batch_no)
    sheets_payload = {}
    for name, df in sheets.items():
        preview_df = df.head(100).fillna("")
        sheets_payload[name] = {
            "columns": list(preview_df.columns),
            "rows": preview_df.astype(object).to_dict(orient="records"),
            "total": len(df),
        }

    sheet_names = list(sheets_payload.keys())
    first = sheets_payload[sheet_names[0]] if sheet_names else {"columns": [], "rows": [], "total": 0}
    total_all = sum(p["total"] for p in sheets_payload.values())

    return {
        "status": "success",
        "data": {
            "sheets": sheets_payload,
            "sheet_names": sheet_names,
            "sheet_metas": meta.get("sheets") or [],
            # 兼容鸿蒙等单表预览:同时返回首个 Sheet 的扁平结构
            "columns": first.get("columns") or [],
            "rows": first.get("rows") or [],
            "total": total_all,
            "period_type": meta.get("period_type") or "",
            "data_period_start": meta.get("data_period_start") or "",
            "data_period_end": meta.get("data_period_end") or "",
            "file_name": (batch.get("file_name") if batch else "") or "",
            "has_ecology": bool(meta.get("has_ecology")),
            "has_nature": bool(meta.get("has_nature")),
        },
    }


# ==================== 鸿蒙生态分析接口 ====================

@router.get("/harmony/template/{template_type}")
async def download_harmony_template(template_type: str):
    """下载鸿蒙分析模板文件(自动使用最新版本)"""
    prefix_map = {
        "store": "门店数据-鸿蒙-模板",
        "factory": "主机厂数据-鸿蒙-模板",
        "output": "输出模板-鸿蒙-模板",
    }
    prefix = prefix_map.get(template_type)
    if not prefix:
        raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")

    try:
        file_path = _find_latest_template(prefix)
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail=f"未找到类型为 {template_type} 的模板文件")

    filename = os.path.basename(file_path)
    return FileResponse(file_path, filename=filename,
                        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")


_harmony_store_file = None
_harmony_factory_file = None


@router.post("/harmony/preview-file")
async def harmony_preview_file(
    file_type: str = Form(...),  # "store" or "factory"
    file: UploadFile = File(...),
):
    """上传鸿蒙分析文件并返回解析后的预览数据(单表结构)"""
    file_path = _date_path(f"_preview_{file.filename}", category="drafts")
    try:
        with open(file_path, "wb") as f:
            shutil.copyfileobj(file.file, f)

        if file_type == "store":
            df = HarmonyAnalysisService.read_store_list(file_path)
        elif file_type == "factory":
            df = HarmonyAnalysisService.read_factory_data(file_path)
        else:
            raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory")

        if df is None or df.empty:
            return {
                "status": "success",
                "data": {"columns": [], "rows": [], "total": 0},
            }

        rows = df.head(100).fillna("").to_dict(orient="records")
        columns = [str(c) for c in df.columns]
        return {
            "status": "success",
            "data": {"columns": columns, "rows": rows, "total": len(df)},
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Harmony preview file failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"文件解析失败: {str(e)}")
    finally:
        if os.path.exists(file_path):
            os.remove(file_path)


@router.post("/harmony/upload")
async def harmony_upload(
    store_file: Optional[UploadFile] = File(None),
    factory_file: Optional[UploadFile] = File(None),
    start_date: str = Form(None),
    end_date: str = Form(None),
):
    """上传鸿蒙门店兜底配置、主机厂数据(产值表数据从数据库自动查询)"""
    global _harmony_store_file, _harmony_factory_file
    result = {"status": "success", "messages": []}

    if store_file and store_file.filename:
        fname = _build_dated_filename(store_file.filename, "harmony_store")
        file_path = _date_path(fname, category="drafts")
        with open(file_path, "wb") as f:
            shutil.copyfileobj(store_file.file, f)
        _harmony_store_file = file_path
        result["messages"].append(f"门店兜底配置已上传: {store_file.filename}")

    if factory_file and factory_file.filename:
        fname = _build_dated_filename(factory_file.filename, "harmony_factory", start_date, end_date)
        # 如果没有日期范围,则存入 drafts 目录
        cat = "harmony" if (start_date and end_date) else "drafts"
        file_path = _date_path(fname, category=cat)
        with open(file_path, "wb") as f:
            shutil.copyfileobj(factory_file.file, f)
        _harmony_factory_file = file_path
        result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")

    if not result["messages"]:
        raise HTTPException(status_code=400, detail="请至少上传一个文件")

    return result


@router.post("/harmony/generate")
async def harmony_generate(
    start_date: str = Form(None),
    end_date: str = Form(None),
    store_batch_no: str = Form(None),
    factory_batch_no: str = Form(None),
):
    """根据已上传的数据或历史批次生成鸿蒙生态分析报表(产值数据从数据库自动查询)"""
    global _harmony_store_file, _harmony_factory_file

    # 加载store_df:优先批次DB数据,其次文件,最后默认模板
    if store_batch_no:
        store_df = HarmonyAnalysisService.load_store_df_from_batch(store_batch_no)
    elif _harmony_store_file and os.path.exists(_harmony_store_file):
        store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
    else:
        try:
            _harmony_store_file = _find_latest_template("门店数据-鸿蒙-模板")
            store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
        except FileNotFoundError:
            raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件")

    # 加载factory_df:优先批次DB数据,其次文件
    factory_df = None
    if factory_batch_no:
        sheets, _ = _load_oem_factory_from_batch(factory_batch_no)
        factory_df = HarmonyAnalysisService._coerce_factory_df(sheets)
    elif _harmony_factory_file and os.path.exists(_harmony_factory_file):
        factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file)

    try:
        output_path = HarmonyAnalysisService.build_report(
            store_df,
            factory_df=factory_df,
            start_date=start_date,
            end_date=end_date,
        )

        factory_count = len(factory_df) if factory_df is not None else 0
        return {
            "status": "success",
            "message": "鸿蒙分析报表已生成",
            "file_path": output_path,
            "download_url": f"api/harmony/download?file={os.path.basename(output_path)}",
            "store_count": len(store_df),
            "factory_count": factory_count,
            "db_store_count": len(store_df),
        }
    except Exception as e:
        logger.error(f"Harmony analysis generate failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")


@router.get("/harmony/download")
async def harmony_download(file: str = Query(None)):
    """下载鸿蒙分析报表"""
    if file:
        file_path = _find_file(file)
        if not file_path:
            raise HTTPException(status_code=404, detail="指定的报表文件不存在")
        return FileResponse(
            file_path, filename=file,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )

    # 无指定时返回最新的鸿蒙分析文件
    output_files = sorted(
        [os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
         for f in fs if f.startswith("鸿蒙分析") and f.endswith(".xlsx")],
        key=lambda f: os.path.getmtime(f),
        reverse=True
    )
    if not output_files:
        raise HTTPException(status_code=404, detail="未找到鸿蒙分析报表,请先生成")

    file_path = output_files[0]
    return FileResponse(
        file_path,
        filename=output_files[0],
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    )


# ==================== 鸿蒙子品牌分析接口 ====================

_sub_brand_file = None


@router.get("/harmony/sub-brand/template/{template_type}")
async def download_sub_brand_template(template_type: str):
    """下载鸿蒙子品牌分析模板文件"""
    prefix_map = {
        "input": "主机厂数据-鸿蒙子品牌-模板",
        "factory": "主机厂数据-鸿蒙子品牌-模板",
        "output": "输出模板-鸿蒙子品牌-模板",
    }
    prefix = prefix_map.get(template_type)
    if not prefix:
        raise HTTPException(status_code=400, detail="无效的模板类型,支持: input/factory/output")

    try:
        file_path = _find_latest_template(prefix)
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail=f"未找到类型为 {template_type} 的模板文件")

    filename = os.path.basename(file_path)
    return FileResponse(file_path, filename=filename,
                        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")


@router.post("/harmony/sub-brand/upload")
async def sub_brand_upload(
    data_file: UploadFile = File(...),
    start_date: str = Form(None),
    end_date: str = Form(None),
    store_batch_no: str = Form(None),
):
    """上传鸿蒙子品牌主机厂数据并返回预览"""
    global _sub_brand_file

    if not data_file or not data_file.filename:
        raise HTTPException(status_code=400, detail="请上传子品牌数据文件")

    fname = _build_dated_filename(data_file.filename, "hm_sub_brand", start_date, end_date)
    file_path = _date_path(fname, category="harmony")
    with open(file_path, "wb") as f:
        shutil.copyfileobj(data_file.file, f)
    _sub_brand_file = file_path

    try:
        store_df = None
        if store_batch_no:
            store_df = HarmonyAnalysisService.load_store_df_from_batch(store_batch_no)
        preview = HarmonyAnalysisService.preview_sub_brand_data(
            file_path, store_df=store_df, start_date=start_date, end_date=end_date)
        if preview.get("total", 0) == 0:
            raise ValueError("未解析到有效子品牌数据,请使用「主机厂数据-鸿蒙子品牌-模板001.xlsx」")
    except ValueError as e:
        if os.path.exists(file_path):
            os.remove(file_path)
        _sub_brand_file = None
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Sub-brand upload preview failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"文件解析失败: {str(e)}")

    return {
        "status": "success",
        "message": f"子品牌数据已上传: {data_file.filename}",
        "data": preview,
    }


@router.post("/harmony/sub-brand/save-batch")
async def sub_brand_save_batch(
    data_file: UploadFile = File(...),
    start_date: str = Form(""),
    end_date: str = Form(""),
):
    """保存鸿蒙子品牌主机厂数据为历史批次"""
    from app.services.upload_service import _get_conn, _generate_batch_no

    if not data_file or not data_file.filename:
        raise HTTPException(status_code=400, detail="请上传子品牌数据文件")

    fname = _build_dated_filename(data_file.filename, "hm_sub_brand", start_date, end_date)
    file_path = _date_path(fname, category="batch")
    with open(file_path, "wb") as f:
        shutil.copyfileobj(data_file.file, f)

    try:
        oem_df = HarmonyAnalysisService.read_sub_brand_oem_data(file_path)
        if oem_df.empty:
            raise ValueError("未解析到有效子品牌数据")

        batch_no = _generate_batch_no()
        batch_start = start_date or datetime.now().replace(day=1).strftime("%Y-%m-%d")
        batch_end = end_date or datetime.now().strftime("%Y-%m-%d")
        conn = _get_conn()
        try:
            with conn.cursor() as cur:
                cur.execute(
                    """INSERT INTO upload_batch
                       (batch_no, brand, data_type, period_type, data_period_start, data_period_end,
                        file_name, file_size, row_count, remark)
                       VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
                    (
                        batch_no, "鸿蒙", "harmony_sub_brand_oem", "sub_brand",
                        batch_start, batch_end,
                        os.path.basename(file_path), os.path.getsize(file_path),
                        len(oem_df), file_path,
                    ),
                )
            conn.commit()
        finally:
            conn.close()

        return {
            "status": "success",
            "data": {
                "batch_no": batch_no,
                "row_count": len(oem_df),
                "period": f"{batch_start} ~ {batch_end}",
            },
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Sub-brand save batch failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"保存批次失败: {str(e)}")


@router.get("/harmony/sub-brand/batch-data")
async def sub_brand_batch_data(
    batch_no: str = Query(...),
    store_batch_no: str = Query(None),
    start_date: str = Query(None),
    end_date: str = Query(None),
):
    """加载子品牌 OEM 历史批次预览"""
    from app.services.upload_service import _get_conn

    conn = _get_conn()
    try:
        with conn.cursor() as cur:
            cur.execute(
                """SELECT remark, data_period_start, data_period_end, file_name
                   FROM upload_batch
                   WHERE batch_no=%s AND data_type='harmony_sub_brand_oem' AND status != 3""",
                (batch_no,),
            )
            row = cur.fetchone()
    finally:
        conn.close()

    if not row or not row.get("remark") or not os.path.exists(row["remark"]):
        raise HTTPException(status_code=404, detail="子品牌批次不存在或文件已丢失")

    global _sub_brand_file
    _sub_brand_file = row["remark"]

    store_df = None
    if store_batch_no:
        store_df = HarmonyAnalysisService.load_store_df_from_batch(store_batch_no)

    sd = start_date or str(row.get("data_period_start") or "")[:10]
    ed = end_date or str(row.get("data_period_end") or "")[:10]
    preview = HarmonyAnalysisService.preview_sub_brand_data(
        row["remark"], store_df=store_df, start_date=sd or None, end_date=ed or None)
    preview["batch_no"] = batch_no
    preview["file_name"] = row.get("file_name") or ""
    return {"status": "success", "data": preview}


@router.post("/harmony/sub-brand/generate")
async def sub_brand_generate(
    start_date: str = Form(None),
    end_date: str = Form(None),
    store_batch_no: str = Form(None),
    oem_batch_no: str = Form(None),
):
    """根据上传的子品牌数据生成鸿蒙子品牌分析报表"""
    global _sub_brand_file

    file_path = _sub_brand_file
    if oem_batch_no:
        from app.services.upload_service import _get_conn
        conn = _get_conn()
        try:
            with conn.cursor() as cur:
                cur.execute(
                    """SELECT remark FROM upload_batch
                       WHERE batch_no=%s AND data_type='harmony_sub_brand_oem' AND status != 3""",
                    (oem_batch_no,),
                )
                row = cur.fetchone()
                if row and row.get("remark") and os.path.exists(row["remark"]):
                    file_path = row["remark"]
        finally:
            conn.close()

    if not file_path or not os.path.exists(file_path):
        raise HTTPException(status_code=400, detail="请先上传或选择子品牌主机厂数据")

    try:
        output_path = HarmonyAnalysisService.build_sub_brand_report(
            file_path,
            start_date=start_date,
            end_date=end_date,
            store_batch_no=store_batch_no,
        )
        detail_rows = max(0, len(HarmonyAnalysisService.read_sub_brand_data(
            file_path,
            store_df=HarmonyAnalysisService.load_store_df_from_batch(store_batch_no)
            if store_batch_no else None,
        )))
        return {
            "status": "success",
            "message": "鸿蒙子品牌分析报表已生成",
            "file_path": output_path,
            "download_url": f"/api/harmony/sub-brand/download?file={os.path.basename(output_path)}",
            "detail_rows": detail_rows,
            "summary_rows": 5,
        }
    except Exception as e:
        logger.error(f"Sub-brand analysis generate failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")


@router.get("/harmony/sub-brand/download")
async def sub_brand_download(file: str = Query(None)):
    """下载鸿蒙子品牌分析报表"""
    if file:
        file_path = _find_file(file)
        if not file_path:
            raise HTTPException(status_code=404, detail="指定的报表文件不存在")
        return FileResponse(
            file_path, filename=file,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )

    output_files = sorted(
        [os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
         for f in fs if f.startswith("鸿蒙子品牌分析") and f.endswith(".xlsx")],
        key=lambda f: os.path.getmtime(f),
        reverse=True
    )
    if not output_files:
        raise HTTPException(status_code=404, detail="未找到鸿蒙子品牌分析报表,请先生成")

    file_path = output_files[0]
    return FileResponse(
        file_path,
        filename=os.path.basename(file_path),
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    )


# ==================== 策略效果盯防接口 ====================

@router.get("/strategy/options")
async def strategy_options():
    """获取策略盯防筛选选项"""
    try:
        return {"status": "success", "data": StrategyService.get_filter_options()}
    except Exception as e:
        logger.error(f"Strategy options failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/strategy/list")
async def strategy_list(
    keyword: Optional[str] = Query(None),
    province: Optional[str] = Query(None),
    baodi_type: Optional[str] = Query(None),
    monitor_type: Optional[str] = Query(None),
    status: Optional[str] = Query(None),
    operation_mode: Optional[str] = Query(None),
    effect: Optional[str] = Query(None),
    start_date: Optional[str] = Query(None),
    end_date: Optional[str] = Query(None),
    strategy_type: Optional[str] = Query(None),
    page: int = Query(1, ge=1),
    page_size: int = Query(8, ge=1, le=100),
):
    """策略盯防列表:查询策略并计算执行前后效果"""
    try:
        data = StrategyService.get_strategy_list(
            keyword=keyword,
            province=province,
            baodi_type=baodi_type,
            monitor_type=monitor_type,
            status=status,
            operation_mode=operation_mode,
            effect=effect,
            start_date=start_date,
            end_date=end_date,
            strategy_type=strategy_type,
            page=page,
            page_size=page_size,
        )
        return {"status": "success", "data": data}
    except Exception as e:
        logger.error(f"Strategy list failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"查询策略列表失败: {str(e)}")


@router.get("/strategy/{strategy_id}")
async def strategy_detail(strategy_id: int):
    """获取单条策略详情及效果分析"""
    try:
        data = StrategyService.get_strategy_detail(strategy_id)
        if not data:
            raise HTTPException(status_code=404, detail="策略不存在")
        return {"status": "success", "data": data}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Strategy detail failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"查询策略详情失败: {str(e)}")


@router.get("/strategy/{strategy_id}/penetration")
async def strategy_penetration_analysis(strategy_id: int):
    """获取策略渗透率分析数据(按天/阶段、员工、品牌、产品维度拆解 + LLM总结)"""
    try:
        data = StrategyService.get_penetration_analysis(strategy_id)
        if not data:
            raise HTTPException(status_code=404, detail="策略不存在")
        return {"status": "success", "data": data}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Penetration analysis failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"渗透率分析失败: {str(e)}")


# ==================== 策略分析任务控制接口 ====================

@router.post("/strategy/analyze")
async def strategy_trigger_analyze():
    """触发策略效果批量分析任务(异步后台执行)"""
    try:
        state = get_task_state()
        if state.get("running"):
            return {
                "status": "warning",
                "message": "分析任务已在运行中",
                "data": state,
            }
        result = StrategyService.trigger_analysis_async()
        return {"status": "success", "message": "分析任务已触发", "data": result}
    except Exception as e:
        logger.error(f"Strategy analyze trigger failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"触发分析任务失败: {str(e)}")


@router.post("/strategy/analyze/{strategy_id}")
async def strategy_analyze_single(strategy_id: int):
    """对单条策略执行分析并保存结果(同步实时执行,分析+写入完成后返回)"""
    try:
        logger.info(f"[API] ==== POST /strategy/analyze/{strategy_id} START ====")
        result = StrategyService.analyze_and_save_single(strategy_id)
        if result is None:
            logger.warning(f"[API] POST /strategy/analyze/{strategy_id} returned None")
            raise HTTPException(status_code=404, detail=f"策略 #{strategy_id} 未找到或分析失败")
        logger.info(f"[API] ==== POST /strategy/analyze/{strategy_id} DONE, effect={result.get('effect_label')} ====")
        return {"status": "success", "message": f"策略 #{strategy_id} 分析完成", "data": result}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Single strategy analyze failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"单条策略分析失败: {str(e)}")


@router.get("/strategy/analyze/status")
async def strategy_analyze_status():
    """获取策略分析任务进度状态"""
    try:
        state = get_task_state()
        return {"status": "success", "data": state}
    except Exception as e:
        logger.error(f"Strategy analyze status failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"获取任务状态失败: {str(e)}")


@router.post("/strategy/refresh-stale")
async def strategy_refresh_stale(stale_hours: int = Query(4, ge=1, le=48)):
    """手动触发超时盯防数据刷新,扫描超过指定小时未更新的盯防策略并自动刷新"""
    try:
        result = StrategyService.auto_refresh_stale_monitoring(stale_hours)
        return {"status": "success", "message": f"刷新完成", "data": result}
    except Exception as e:
        logger.error(f"Strategy refresh stale failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"刷新盯防数据失败: {str(e)}")


@router.get("/strategy/refresh-status")
async def strategy_refresh_status():
    """查询盯防数据刷新状态(活跃/超时/从未刷新)"""
    try:
        status = StrategyService.get_monitoring_refresh_status()
        return {"status": "success", "data": status}
    except Exception as e:
        logger.error(f"Strategy refresh status failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"查询刷新状态失败: {str(e)}")


@router.get("/strategy/stale-list")
async def strategy_stale_list(stale_hours: int = Query(4, ge=1, le=48)):
    """查询超时未刷新的盯防策略列表"""
    try:
        strategies = StrategyService.get_stale_monitoring_strategies(stale_hours)
        items = []
        for s in strategies:
            items.append({
                "id": s["id"],
                "title": s.get("title") or "",
                "merchant_name": s.get("merchant_name") or "",
                "start_date": StrategyService._date_str(s.get("start_date")),
                "end_date": StrategyService._date_str(s.get("end_date")),
            })
        return {"status": "success", "data": {"count": len(items), "items": items}}
    except Exception as e:
        logger.error(f"Strategy stale list failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"查询超时策略失败: {str(e)}")


# ==================== 门店数据 & 主机厂数据 上传接口 ====================

# 数据导入临时上传(使用 _date_path + data 类别实现日期分级)
DATA_UPLOAD_CATEGORY = "data"


def _save_upload(file: UploadFile, brand: str, data_type: str, start_date: str = None, end_date: str = None, period_type: str = "") -> tuple:
    """保存上传文件。
    - 如果提供日期范围,则按正式命名规范整理并存入 data 目录
    - 否则存入 drafts 目录
    """
    if start_date and end_date:
        if data_type == "store":
            formal_name = build_store_filename(brand, start_date, end_date)
        else:
            formal_name = build_factory_filename(brand, period_type, start_date, end_date)
        cat = DATA_UPLOAD_CATEGORY
        file_name = formal_name
    else:
        ts = datetime.now().strftime("%H%M%S")
        base, ext = os.path.splitext(file.filename)
        file_name = f"{data_type}_{brand}_{ts}{ext}"
        cat = "drafts"

    file_path = _date_path(file_name, category=cat)
    # 确保文件名唯一
    file_path = ensure_unique_filename(os.path.dirname(file_path), os.path.basename(file_path))
    file_path = os.path.join(os.path.dirname(file_path), os.path.basename(file_path))

    with open(file_path, "wb") as f:
        shutil.copyfileobj(file.file, f)
    return file_path, file.filename


@router.post("/data-import/upload-store")
async def upload_store_guarantee(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(...),
    brand: str = Form(...),
    period_start: str = Form(...),
    period_end: str = Form(...),
):
    """上传门店兜底配置 Excel,导入 store_guarantee_config 表"""
    logger.info(f"upload-store: filename={file.filename}, brand={brand}, period={period_start}~{period_end}")
    if not file.filename:
        raise HTTPException(status_code=400, detail="请选择文件")
    if brand not in ("问界", "鸿蒙"):
        raise HTTPException(status_code=400, detail="品牌仅支持 问界 或 鸿蒙")

    file_path, original_name = _save_upload(file, brand, "store", start_date=period_start, end_date=period_end)

    try:
        file_size = os.path.getsize(file_path)
        result = import_store_guarantee(
            file_path=file_path,
            original_filename=os.path.basename(file_path),
            brand=brand,
            data_period_start=period_start,
            data_period_end=period_end,
            file_size=file_size,
            remark=file_path
        )
        return {"status": "success", "data": result}
    except ValueError as e:
        logger.warning(f"Store guarantee upload validation: {e}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Store guarantee upload failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"导入失败: {str(e)}")


@router.post("/data-import/upload-oem")
async def upload_oem_delivery(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(...),
    brand: str = Form(...),
    period_start: str = Form(...),
    period_end: str = Form(...),
    period_type: str = Form(""),
):
    """上传主机厂交付数据 Excel,导入 oem_delivery_data 表"""
    logger.info(f"upload-oem: filename={file.filename}, brand={brand}, period={period_start}~{period_end}, period_type={period_type}")
    if not file.filename:
        raise HTTPException(status_code=400, detail="请选择文件")
    if brand not in ("问界", "鸿蒙"):
        raise HTTPException(status_code=400, detail="品牌仅支持 问界 或 鸿蒙")
    if period_type not in ("", "ecology", "nature"):
        raise HTTPException(status_code=400, detail="周期类型仅支持 ecology 或 nature")

    file_path, original_name = _save_upload(file, brand, "oem", start_date=period_start, end_date=period_end, period_type=period_type)

    try:
        file_size = os.path.getsize(file_path)
        result = import_oem_delivery(
            file_path=file_path,
            original_filename=os.path.basename(file_path),
            brand=brand,
            data_period_start=period_start,
            data_period_end=period_end,
            period_type=period_type,
            file_size=file_size,
            remark=file_path
        )
        return {"status": "success", "data": result}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"OEM delivery upload failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"导入失败: {str(e)}")


@router.get("/data-import/history")
async def get_import_history(
    brand: Optional[str] = Query(None),
    data_type: Optional[str] = Query(None),
    period_type: Optional[str] = Query(None),
):
    """获取上传批次历史列表"""
    try:
        rows = get_upload_history(brand=brand, data_type=data_type, period_type=period_type)
        return {"status": "success", "data": rows}
    except Exception as e:
        logger.error(f"Get upload history failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"查询失败: {str(e)}")