strategy_analysis_demo.py 62.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
# -*- coding: utf-8 -*-
"""
策略效果分析 Demo
=================
功能:选定一条策略,提取该策略涉及门店在【前置基线期/策略执行期/效果跟踪期】的运营数据,
      进行多维度对比分析,并可选接入 LLM 生成分析报告。

用法:
    python tests/strategy_analysis_demo.py                          # 列出所有策略
    python tests/strategy_analysis_demo.py --id 10                  # 分析指定策略
    python tests/strategy_analysis_demo.py --id 10 --llm            # 分析并调用LLM生成报告
    python tests/strategy_analysis_demo.py --id 10 --export-report  # 导出分析报告到文件
"""

import os
import sys
import json
import argparse
from datetime import datetime, timedelta
from collections import defaultdict
from pathlib import Path
from typing import Optional

import pymysql
from openai import OpenAI

# 添加项目根目录到 path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# ==================== 数据库配置 ====================
DB_CONFIG = {
    "host": "192.168.2.155",
    "port": 3308,
    "user": "user_jiangmy",
    "password": "PYuxMTB1",
    "database": "data_analyze",
    "charset": "utf8mb4",
    "cursorclass": pymysql.cursors.DictCursor,
}

# ==================== 策略类型映射 ====================
STRATEGY_TYPE_MAP = {
    0: "学习类",
    1: "优秀录音分享类",
    2: "带教",
    3: "任务型",
    4: "销售精英到店提拉",
    5: "强力促销",
    6: "最终盘点与低客单产品购入",
    7: "留言",
    8: "带教申请",
    9: "人员更换评估",
    10: "商务政策更新评估",
    11: "多品类拓张",
    12: "流量问题改善",
}

# ==================== 产品定义 ====================
PRODUCTS = {
    "extended_warranty": {"name": "整车延保", "order_col": "sum_extended_warranty"},
    "ax_package": {"name": "安心包", "order_col": "sum_ax_package"},
    "battery_extended": {"name": "电池延保", "order_col": "sum_battery_extended"},
}

# ==================== 数据库操作 ====================

def get_conn():
    return pymysql.connect(**DB_CONFIG)


def fetch_one(sql: str, params: tuple = None):
    conn = get_conn()
    try:
        with conn.cursor() as cur:
            cur.execute(sql, params)
            return cur.fetchone()
    finally:
        conn.close()


def fetch_all(sql: str, params: tuple = None):
    conn = get_conn()
    try:
        with conn.cursor() as cur:
            cur.execute(sql, params)
            return cur.fetchall()
    finally:
        conn.close()


# ==================== 策略查询 ====================

def list_strategies(limit: int = 20):
    """列出最近创建的策略"""
    sql = """
        SELECT id, title, sub_title, strategy_type, merchant_id, merchant_name,
               start_date, end_date, push_flag, description, biz
        FROM ods_strategy_info
        WHERE deleted_flag = 'N'
        ORDER BY created_date DESC
        LIMIT %s
    """
    rows = fetch_all(sql, (limit,))
    return rows


def get_strategy(strategy_id: int):
    """获取单条策略详情"""
    sql = "SELECT * FROM ods_strategy_info WHERE id = %s"
    return fetch_one(sql, (strategy_id,))


# ==================== 门店数据查询 ====================

def get_store_config(merchant_id: int):
    """获取门店配置信息"""
    sql = """
        SELECT merchant_id, merchant_name, merchant_code, province, city,
               channel, operation_mode, traffic_grade, primary_brand,
               area_manager, online_ops, flight_supervisor, deploy_time
        FROM ods_store_config
        WHERE merchant_id = %s AND deleted_flag = 'N'
    """
    return fetch_one(sql, (merchant_id,))


def get_store_daily_metrics(merchant_id: int, start_date: str, end_date: str):
    """
    获取门店在指定日期范围内的日报指标汇总。

    返回按天聚合的数据列表,每条包含:
    report_date, delivery_count,
    pre_sale_touch (售前触客), after_sale_touch (售后触客),
    extended_warranty_orders, ax_package_orders, battery_extended_orders,
    total_orders, sum_battery_money
    """
    sql = """
        SELECT
            report_date,
            SUM(IFNULL(delivery_count, 0))              AS delivery_count,
            SUM(IFNULL(sum_equity_to_shop, 0))          AS pre_sale_touch,
            SUM(IFNULL(sum_after_sale_to_shop, 0))      AS after_sale_touch,
            SUM(IFNULL(sum_extended_warranty, 0))        AS extended_warranty_orders,
            SUM(IFNULL(sum_ax_package, 0))               AS ax_package_orders,
            SUM(IFNULL(sum_battery_extended, 0))         AS battery_extended_orders,
            SUM(IFNULL(sum_tire_warranty, 0))            AS tire_warranty_orders,
            SUM(IFNULL(sum_order_count, 0))              AS total_orders,
            SUM(IFNULL(sum_battery_money, 0))            AS battery_money,
            SUM(IFNULL(total_staff, 0))                  AS total_staff,
            SUM(IFNULL(active_staff, 0))                 AS active_staff
        FROM dws_merchant_daily_wide
        WHERE merchant_id = %s
          AND report_date BETWEEN %s AND %s
          AND first_brand_id = 2365
          AND brand_id = 2695
          AND scene_type = '0'
        GROUP BY report_date
        ORDER BY report_date
    """
    return fetch_all(sql, (merchant_id, start_date, end_date))


def get_store_delivery_from_ods(merchant_id: int, start_date: str, end_date: str):
    """
    从 ODS 门店日报表直接获取交付数(用于 DWS 宽表无数据时的回退)。
    返回总交付数和数据天数。
    """
    sql = """
        SELECT
            SUM(IFNULL(delivery_count, 0))              AS total_delivery,
            COUNT(DISTINCT report_date)                  AS data_days
        FROM ods_merchant_daily_report_huawei
        WHERE merchant_id = %s
          AND report_date BETWEEN %s AND %s
          AND deleted_flag = 'N'
    """
    return fetch_one(sql, (merchant_id, start_date, end_date))


def get_guarantee_daily(merchant_id: int, start_date: str, end_date: str):
    """获取门店兜底保障日指标"""
    sql = """
        SELECT report_date, product_type, brand,
               target_conversion_rate, unit_compensation,
               guarantee_type,
               actual_touch_count, actual_order_count, actual_delivery_count,
               actual_conversion_rate, is_triggered,
               gap_count, estimated_compensation
        FROM dwm_guarantee_daily
        WHERE merchant_id = %s
          AND report_date BETWEEN %s AND %s
        ORDER BY report_date, product_type
    """
    return fetch_all(sql, (merchant_id, start_date, end_date))


def get_staff_daily_metrics(merchant_id: int, start_date: str, end_date: str):
    """
    获取门店下各员工日报指标汇总。
    注意: dws_staff_daily_wide 的 ETL 未填充指标字段(订单数等均为0),
          因此直接从 ODS 源表 ods_staff_daily_report_huawei 查询。
    """
    sql = """
        SELECT
            sdrh.staff_uuid,
            IFNULL(si.staff_name, sdrh.staff_uuid) AS staff_name,
            SUM(IFNULL(sdrh.equity_to_shop_count, 0))           AS pre_sale_touch,
            SUM(IFNULL(sdrh.after_sale_equity_to_shop_count, 0)
              + IFNULL(sdrh.after_sale_extended_warranty_to_shop_count, 0)
              + IFNULL(sdrh.after_sale_real_equity_to_shop_count, 0)) AS after_sale_touch,
            SUM(IFNULL(sdrh.total_order_count, 0))              AS total_orders,
            SUM(IFNULL(sdrh.extended_warranty_count, 0))        AS extended_warranty_orders,
            SUM(IFNULL(sdrh.tire_warranty_count, 0))            AS tire_warranty_orders,
            SUM(IFNULL(sdrh.ax_package_count, 0))               AS ax_package_orders,
            SUM(IFNULL(sdrh.battery_extended_warranty_count, 0)) AS battery_extended_orders,
            SUM(IFNULL(sdrh.battery_extended_warranty_money, 0)) AS battery_money,
            COUNT(DISTINCT sdrh.report_date)                    AS work_days,
            0                                                    AS delivery_count
        FROM ods_staff_daily_report_huawei sdrh
        LEFT JOIN ods_staff_info si ON sdrh.staff_uuid = si.staff_uuid
        WHERE sdrh.merchant_id = %s
          AND sdrh.report_date BETWEEN %s AND %s
          AND sdrh.deleted_flag = 'N'
          AND sdrh.scene_type = '0'
        GROUP BY sdrh.staff_uuid, si.staff_name
        ORDER BY total_orders DESC
    """
    return fetch_all(sql, (merchant_id, start_date, end_date))


# ==================== 行业对比查询 ====================

def get_peer_benchmarks(merchant_id: int, province: str, channel: str,
                        start_date: str, end_date: str):
    """
    获取同省同渠道门店的均值基准,以及 Top5 标杆门店数据。

    返回 dict: {
        'peer_avg': { ... },       # 同省同渠道均值
        'top5_stores': [ ... ],    # Top5 门店详情
        'total_peers': int         # 同群门店总数
    }
    """
    # 同省同渠道门店日均值
    sql_peer = """
        SELECT
            COUNT(DISTINCT merchant_id) AS peer_count,
            SUM(IFNULL(delivery_count, 0))   / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_delivery,
            SUM(IFNULL(sum_equity_to_shop, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_touch,
            SUM(IFNULL(sum_extended_warranty, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_ew,
            SUM(IFNULL(sum_ax_package, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_ax,
            SUM(IFNULL(sum_battery_extended, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_battery,
            SUM(IFNULL(sum_order_count, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_orders
        FROM dws_merchant_daily_wide
        WHERE province_name = (SELECT province_name FROM dws_merchant_daily_wide WHERE merchant_id = %s LIMIT 1)
          AND channel_type = (SELECT channel_type FROM dws_merchant_daily_wide WHERE merchant_id = %s LIMIT 1)
          AND merchant_id != %s
          AND report_date BETWEEN %s AND %s
          AND first_brand_id = 2365 AND brand_id = 2695 AND scene_type = '0'
    """
    peer_avg = fetch_one(sql_peer, (merchant_id, merchant_id, merchant_id, start_date, end_date))

    # Top5 标杆门店(按总订单数排名)
    sql_top5 = """
        SELECT
            merchant_id,
            MAX(merchant_name) AS merchant_name,
            SUM(IFNULL(sum_order_count, 0))   AS total_orders,
            SUM(IFNULL(sum_extended_warranty, 0)) AS total_ew,
            SUM(IFNULL(sum_ax_package, 0))    AS total_ax,
            SUM(IFNULL(sum_battery_extended, 0)) AS total_battery,
            SUM(IFNULL(delivery_count, 0))    AS total_delivery,
            COUNT(DISTINCT report_date)       AS active_days
        FROM dws_merchant_daily_wide
        WHERE province_name = (SELECT province_name FROM dws_merchant_daily_wide WHERE merchant_id = %s LIMIT 1)
          AND report_date BETWEEN %s AND %s
          AND first_brand_id = 2365 AND brand_id = 2695 AND scene_type = '0'
        GROUP BY merchant_id
        ORDER BY total_orders DESC
        LIMIT 5
    """
    top5 = fetch_all(sql_top5, (merchant_id, start_date, end_date))

    return {"peer_avg": peer_avg, "top5_stores": top5}


def get_same_city_avg(merchant_id: int, start_date: str, end_date: str):
    """获取同城门店日均指标均值"""
    sql = """
        SELECT
            COUNT(DISTINCT merchant_id) AS city_peer_count,
            SUM(IFNULL(sum_order_count, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_orders,
            SUM(IFNULL(sum_extended_warranty, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_ew,
            SUM(IFNULL(sum_ax_package, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_ax,
            SUM(IFNULL(sum_battery_extended, 0)) / NULLIF(COUNT(DISTINCT report_date), 0) AS avg_daily_battery
        FROM dws_merchant_daily_wide
        WHERE city_name = (SELECT city_name FROM dws_merchant_daily_wide WHERE merchant_id = %s LIMIT 1)
          AND merchant_id != %s
          AND report_date BETWEEN %s AND %s
          AND first_brand_id = 2365 AND brand_id = 2695 AND scene_type = '0'
    """
    return fetch_one(sql, (merchant_id, merchant_id, start_date, end_date))


# ==================== 分析计算 ====================

def safe_rate(numerator, denominator):
    """安全计算渗透率,返回百分比字符串"""
    if not denominator or denominator == 0:
        return "0.00%"
    return f"{float(numerator) / float(denominator) * 100:.2f}%"


def safe_num(val):
    """安全返回数值"""
    return val if val is not None else 0


def aggregate_period_metrics(daily_rows):
    """
    对日报数据进行按周期汇总,计算各指标总量和日均值。
    返回 dict。
    """
    if not daily_rows:
        return None

    total_delivery = sum(safe_num(r.get("delivery_count", 0)) for r in daily_rows)
    total_pre_touch = sum(safe_num(r.get("pre_sale_touch", 0)) for r in daily_rows)
    total_after_touch = sum(safe_num(r.get("after_sale_touch", 0)) for r in daily_rows)
    total_ew = sum(safe_num(r.get("extended_warranty_orders", 0)) for r in daily_rows)
    total_ax = sum(safe_num(r.get("ax_package_orders", 0)) for r in daily_rows)
    total_battery = sum(safe_num(r.get("battery_extended_orders", 0)) for r in daily_rows)
    total_orders = sum(safe_num(r.get("total_orders", 0)) for r in daily_rows)
    total_battery_money = sum(safe_num(r.get("battery_money", 0)) for r in daily_rows)

    days = len(daily_rows)

    return {
        "days": days,
        "total_delivery": total_delivery,
        "total_pre_touch": total_pre_touch,
        "total_after_touch": total_after_touch,
        "total_touch": total_pre_touch + total_after_touch,
        "total_ew": total_ew,
        "total_ax": total_ax,
        "total_battery": total_battery,
        "total_orders": total_orders,
        "total_battery_money": round(total_battery_money, 2),
        # 日均
        "avg_daily_delivery": round(total_delivery / days, 1) if days else 0,
        "avg_daily_touch": round((total_pre_touch + total_after_touch) / days, 1) if days else 0,
        "avg_daily_orders": round(total_orders / days, 1) if days else 0,
        # 转化率 (以交付为分母)
        "ew_conversion": safe_rate(total_ew, total_delivery),
        "ax_conversion": safe_rate(total_ax, total_delivery),
        "battery_conversion": safe_rate(total_battery, total_delivery),
        # 触客转化率
        "ew_touch_conversion": safe_rate(total_ew, total_pre_touch),
        "ax_touch_conversion": safe_rate(total_ax, total_pre_touch),
        "battery_touch_conversion": safe_rate(total_battery, total_pre_touch),
    }


def aggregate_guarantee_metrics(guarantee_rows):
    """汇总兜底保障指标"""
    if not guarantee_rows:
        return None

    by_product = defaultdict(lambda: {
        "days_triggered": 0,
        "total_days": 0,
        "target_rate": 0,
        "actual_rates": [],
        "total_compensation": 0,
        "total_gap": 0,
        "total_actual_touch": 0,
        "total_actual_order": 0,
        "total_actual_delivery": 0,
    })

    for r in guarantee_rows:
        pt = r.get("product_type", "")
        if not pt:
            continue
        d = by_product[pt]
        d["total_days"] += 1
        d["target_rate"] = max(d["target_rate"], safe_num(r.get("target_conversion_rate")))
        d["total_compensation"] += safe_num(r.get("estimated_compensation"))
        d["total_gap"] += safe_num(r.get("gap_count"))
        d["total_actual_touch"] += safe_num(r.get("actual_touch_count"))
        d["total_actual_order"] += safe_num(r.get("actual_order_count"))
        d["total_actual_delivery"] += safe_num(r.get("actual_delivery_count"))
        if r.get("actual_conversion_rate") is not None:
            d["actual_rates"].append(float(r["actual_conversion_rate"]))
        if r.get("is_triggered") == "Y":
            d["days_triggered"] += 1

    result = {}
    for pt, d in by_product.items():
        avg_actual_rate = sum(d["actual_rates"]) / len(d["actual_rates"]) if d["actual_rates"] else 0
        result[pt] = {
            "target_rate": f"{d['target_rate'] * 100:.2f}%" if d["target_rate"] else "N/A",
            "avg_actual_rate": f"{avg_actual_rate * 100:.2f}%",
            "days_triggered": d["days_triggered"],
            "total_days": d["total_days"],
            "trigger_rate": f"{d['days_triggered'] / d['total_days'] * 100:.1f}%" if d["total_days"] else "N/A",
            "total_compensation": round(d["total_compensation"], 2),
            "total_gap": round(d["total_gap"], 2),
            "actual_touch": d["total_actual_touch"],
            "actual_order": d["total_actual_order"],
            "actual_delivery": d["total_actual_delivery"],
        }
    return result


def safe_rate_num(numerator, denominator):
    """安全计算渗透率,返回 float"""
    if not denominator or denominator == 0:
        return 0.0
    return float(numerator) / float(denominator) * 100.0


def aggregate_staff_metrics(staff_rows, total_delivery):
    """汇总员工指标,按延保渗透率降序排列"""
    if not staff_rows:
        return []

    result = []
    for r in staff_rows:
        ew = safe_num(r.get("extended_warranty_orders"))
        ax = safe_num(r.get("ax_package_orders"))
        battery = safe_num(r.get("battery_extended_orders"))
        touch = safe_num(r.get("pre_sale_touch"))
        orders = safe_num(r.get("total_orders"))

        # 渗透率 = 产品订单数 / 门店交付数(店级分母)
        ew_pen_num = float(safe_rate_num(ew, total_delivery))
        ax_pen_num = float(safe_rate_num(ax, total_delivery))
        battery_pen_num = float(safe_rate_num(battery, total_delivery))
        # 综合渗透率权重: 延保*0.5 + 安心包*0.3 + 电池*0.2
        composite_pen = ew_pen_num * 0.5 + ax_pen_num * 0.3 + battery_pen_num * 0.2

        result.append({
            "staff_name": r.get("staff_name") or r.get("staff_uuid", ""),
            "staff_uuid": r.get("staff_uuid", ""),
            "work_days": safe_num(r.get("work_days")),
            "pre_sale_touch": touch,
            "after_sale_touch": safe_num(r.get("after_sale_touch")),
            "total_orders": orders,
            "extended_warranty_orders": ew,
            "ax_package_orders": ax,
            "battery_extended_orders": battery,
            "battery_money": round(safe_num(r.get("battery_money")), 2),
            # 渗透率(数值,用于排序)
            "ew_penetration_num": ew_pen_num,
            "ax_penetration_num": ax_pen_num,
            "battery_penetration_num": battery_pen_num,
            "composite_penetration_num": composite_pen,
            # 渗透率(展示用字符串)
            "ew_penetration": safe_rate(ew, total_delivery),
            "ax_penetration": safe_rate(ax, total_delivery),
            "battery_penetration": safe_rate(battery, total_delivery),
        })

    # 按综合渗透率降序排列
    result.sort(key=lambda x: x["composite_penetration_num"], reverse=True)
    return result


def compute_comparison(my_metrics, peer_data, city_data, label: str):
    """
    以渗透率为核心维度进行同业对比。
    渗透率 = 产品订单数 / 交付数
    """
    comparisons = []

    ew_orders = my_metrics.get("total_ew", 0)
    ax_orders = my_metrics.get("total_ax", 0)
    battery_orders = my_metrics.get("total_battery", 0)
    total_delivery = my_metrics.get("total_delivery", 0)
    days = my_metrics.get("days", 1)

    # 本店渗透率 (数值)
    my_ew_pen = ew_orders / total_delivery * 100 if total_delivery else 0
    my_ax_pen = ax_orders / total_delivery * 100 if total_delivery else 0
    my_battery_pen = battery_orders / total_delivery * 100 if total_delivery else 0

    product_pen_map = {
        "extended_warranty": {"name": "整车延保", "my_pen": my_ew_pen, "peer_col": "avg_daily_ew"},
        "ax_package":        {"name": "安心包",   "my_pen": my_ax_pen, "peer_col": "avg_daily_ax"},
        "battery_extended":  {"name": "电池延保", "my_pen": my_battery_pen, "peer_col": "avg_daily_battery"},
    }

    # 同业渗透率对比
    if peer_data and peer_data.get("peer_avg"):
        pa = peer_data["peer_avg"]
        peer_count = safe_num(pa.get("peer_count"))
        peer_delivery_avg = safe_num(pa.get("avg_daily_delivery"))

        for key, info in product_pen_map.items():
            peer_orders_avg = safe_num(pa.get(info["peer_col"]))
            peer_pen = peer_orders_avg / peer_delivery_avg * 100 if peer_delivery_avg else 0
            diff_pp = f"{info['my_pen'] - peer_pen:+.2f}pp" if peer_pen else "N/A"
            comparisons.append({
                "维度": f"同业-{info['name']}渗透率",
                "本店": f"{info['my_pen']:.2f}%",
                f"同业均值(N={peer_count})": f"{peer_pen:.2f}%",
                "差异": diff_pp,
            })

    # 同城渗透率对比
    if city_data and city_data.get("city_peer_count"):
        city_count = safe_num(city_data.get("city_peer_count"))
        # 同城交付近似用同业日均 (同城表无 delivery 列)
        city_delivery = peer_delivery_avg if peer_data and peer_data.get("peer_avg") else 1
        city_col_map = {"extended_warranty": "avg_daily_ew", "ax_package": "avg_daily_ax", "battery_extended": "avg_daily_battery"}
        for key, info in product_pen_map.items():
            city_col = city_col_map.get(key)
            city_orders = safe_num(city_data.get(city_col)) if city_data.get(city_col) is not None else 0
            city_pen = city_orders / city_delivery * 100 if city_delivery else 0
            diff_pp = f"{info['my_pen'] - city_pen:+.2f}pp" if city_pen else "N/A"
            comparisons.append({
                "维度": f"同城-{info['name']}渗透率",
                "本店": f"{info['my_pen']:.2f}%",
                f"同城均值(N={city_count})": f"{city_pen:.2f}%",
                "差异": diff_pp,
            })

    # Top5 标杆渗透率对比
    if peer_data and peer_data.get("top5_stores"):
        top5 = peer_data["top5_stores"]
        for key, info in product_pen_map.items():
            top5_key = {"extended_warranty": "total_ew", "ax_package": "total_ax", "battery_extended": "total_battery"}[key]
            top5_pens = []
            for ts in top5:
                ts_orders = safe_num(ts.get(top5_key, 0))
                ts_delivery = safe_num(ts.get("total_delivery", 0))
                ts_days = max(safe_num(ts.get("active_days", 1)), 1)
                ts_pen = ts_orders / ts_delivery * 100 if ts_delivery else 0
                top5_pens.append(ts_pen)
            if top5_pens:
                top5_avg_pen = sum(top5_pens) / len(top5_pens)
                top1_pen = top5_pens[0]
                comparisons.append({
                    "维度": f"标杆-{info['name']}渗透率",
                    "本店": f"{info['my_pen']:.2f}%",
                    "Top1": f"{top1_pen:.2f}%",
                    "Top5均值": f"{top5_avg_pen:.2f}%",
                    "vs.Top1": f"{'↑' if info['my_pen'] > top1_pen else ('→' if info['my_pen'] == top1_pen else '↓')} {info['my_pen'] / top1_pen * 100:.1f}%" if top1_pen else "N/A",
                })

    return comparisons


# ==================== LLM 分析报告 ====================

def build_analysis_context(
    strategy: dict,
    store: dict,
    period_labels: list,
    period_metrics: list,
    guarantee_data: list,
    staff_data: list,
    comparisons: list,
) -> str:
    """构建传给 LLM 的分析上下文"""
    strategy_type_name = STRATEGY_TYPE_MAP.get(safe_num(strategy.get("strategy_type")), "未知")

    ctx = f"""
## 策略基本信息
- 策略ID: {strategy.get('id')}
- 策略类型: {strategy_type_name}
- 标题: {strategy.get('title', 'N/A')}
- 副标题: {strategy.get('sub_title', 'N/A')}
- 策略说明: {strategy.get('description', 'N/A')}
- 执行开始: {strategy.get('start_date')}
- 执行结束: {strategy.get('end_date')}
- 推送状态: {strategy.get('push_flag')}
- 业务类型: {strategy.get('biz')}

## 门店信息
- 门店名称: {store.get('merchant_name', 'N/A') if store else 'N/A'}
- 门店编码: {store.get('merchant_code', 'N/A') if store else 'N/A'}
- 省份/城市: {store.get('province', 'N/A')}/{store.get('city', 'N/A') if store else 'N/A'}
- 运营模式: {store.get('operation_mode', 'N/A') if store else 'N/A'}
- 流量分级: {store.get('traffic_grade', 'N/A') if store else 'N/A'}
- 渠道: {store.get('channel', 'N/A') if store else 'N/A'}
- 区域运营: {store.get('area_manager', 'N/A') if store else 'N/A'}
- 线上运营: {store.get('online_ops', 'N/A') if store else 'N/A'}
- 飞行督导: {store.get('flight_supervisor', 'N/A') if store else 'N/A'}

## 各周期门店指标汇总
"""
    for i, (label, metrics) in enumerate(zip(period_labels, period_metrics)):
        if not metrics:
            ctx += f"\n### {label}\n(无数据)\n"
            continue
        ctx += f"""
### {label} ({metrics.get('days', 0)}天)
| 指标 | 数值 |
|------|------|
| 交付数 | {metrics.get('total_delivery', 0)} |
| 售前触客 | {metrics.get('total_pre_touch', 0)} |
| 售后触客 | {metrics.get('total_after_touch', 0)} |
| 日均触客 | {metrics.get('avg_daily_touch', 0)} |
| 总订单 | {metrics.get('total_orders', 0)} |
| 日均订单 | {metrics.get('avg_daily_orders', 0)} |
| 整车延保订单 | {metrics.get('total_ew', 0)} (转化率: {metrics.get('ew_conversion', 'N/A')}) |
| 安心包订单 | {metrics.get('total_ax', 0)} (转化率: {metrics.get('ax_conversion', 'N/A')}) |
| 电池延保订单 | {metrics.get('total_battery', 0)} (转化率: {metrics.get('battery_conversion', 'N/A')}) |
| 电池延保金额 | {metrics.get('total_battery_money', 0)} 元 |
"""

    # 兜底数据
    ctx += "\n## 兜底保障指标\n"
    for i, (label, gd) in enumerate(zip(period_labels, guarantee_data)):
        ctx += f"\n### {label}\n"
        if not gd:
            ctx += "(无兜底数据)\n"
            continue
        for pt, info in gd.items():
            ctx += f"""
**{pt}**:
- 目标转化率: {info['target_rate']}
- 实际平均转化率: {info['avg_actual_rate']}
- 触发兜底天数: {info['days_triggered']}/{info['total_days']} ({info['trigger_rate']})
- 预估赔付金额: {info['total_compensation']} 元
- 差额: {info['total_gap']}
"""

    # 员工数据 (策略执行期)
    staff = staff_data[1] if len(staff_data) > 1 and staff_data[1] else []
    if staff_data[0] and not staff:
        staff = staff_data[0]  # fallback to baseline
    if staff:
        ctx += "\n## 策略执行期员工指标\n"
        ctx += "| 员工 | 触客 | 延保 | 延保渗透率 | 安心包 | 安心包渗透率 | 电池 | 电池渗透率 | 金额 |\n"
        ctx += "|------|------|------|------------|--------|------------|------|------------|------|\n"
        for s in staff:
            ctx += (f"| {s['staff_name']} | {s['pre_sale_touch']} | "
                    f"{s['extended_warranty_orders']} | {s['ew_penetration']} | "
                    f"{s['ax_package_orders']} | {s['ax_penetration']} | "
                    f"{s['battery_extended_orders']} | {s['battery_penetration']} | "
                    f"{s['battery_money']} |\n")
        # Top3/Bottom3 按渗透率
        ctx += f"\n**渗透率 Top3**: {', '.join(s['staff_name'] for s in staff[:3])}\n"
        if len(staff) > 3:
            ctx += f"**渗透率 Bottom3**: {', '.join(s['staff_name'] for s in staff[-3:])}\n"

    # 同业对比
    if comparisons:
        ctx += "\n## 同业对比分析\n"
        for c in comparisons:
            ctx += f"- {c.get('维度', '')}: {json.dumps(c, ensure_ascii=False)}\n"

    return ctx


def call_llm_for_report(context: str, model: str = "qwen3.7-plus") -> str:
    """调用 Qwen LLM 生成分析报告"""
    api_key = "sk-ws-H.EMRRHMX.S4k3.MEUCIQDnkdAOI5V_gOXO0s4h0uj66P9Yp5DFxghgCCoLB0cxkAIgWbLaokBGxsQjlN90pivlsjwVBIRNIfCDVuyCW__6ldU"
    base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"

    client = OpenAI(api_key=api_key, base_url=base_url)

    system_prompt = """你是一位汽车行业门店运营数据分析专家。请根据提供的数据,生成一份专业的策略效果分析报告。

报告结构:
1. **策略背景**:为什么会有这个策略(结合门店数据和策略类型分析触发原因)
2. **策略前后对比分析**:分周期对比各项指标变化,**以渗透率(产品订单/交付数)为核心指标**,因为订单绝对值受交付量影响不完全可控,渗透率更能反映驻店人员的推广能力。标注显著变化。
3. **策略有效性评估**:基于渗透率变化判断策略是否有效,给出置信度评估
4. **建议**:针对该门店和策略类型,提出具体可行的后续优化建议

注意:
- 核心指标是渗透率而非绝对值
- 对比需要标注百分比变化
- 如果某些周期数据为空,需要说明原因
- 语气专业、客观、有洞察力
- 用 Markdown 格式输出"""

    try:
        resp = client.chat.completions.create(
            model=model,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": f"请分析以下数据并生成报告:\n\n{context}"},
            ],
            temperature=0.3,
            max_tokens=4096,
        )
        return resp.choices[0].message.content
    except Exception as e:
        return f"\n\n[LLM调用失败: {e}]\n\n--- 以下为基础数据摘要 ---\n{context[:3000]}..."


# ==================== 主流程 ====================

def analyze_strategy(strategy_id: int, use_llm: bool = False, export: bool = False):
    """
    对指定策略进行完整分析。

    时间窗口定义:
    - T-1 (前置基线期): start_date 前等长周期
    - T   (策略执行期): start_date ~ end_date
    - T+1 (效果跟踪期): end_date 后等长周期
    """
    # 1. 获取策略
    strategy = get_strategy(strategy_id)
    if not strategy:
        print(f"[X] 策略 ID={strategy_id} 不存在")
        return None

    strategy_type_name = STRATEGY_TYPE_MAP.get(safe_num(strategy.get("strategy_type")), "未知")

    print("=" * 70)
    print(f"  策略效果分析报告")
    print("=" * 70)
    print(f"  策略ID:     {strategy['id']}")
    print(f"  策略类型:   {strategy_type_name}")
    print(f"  标题:       {strategy.get('title', 'N/A')}")
    print(f"  副标题:     {strategy.get('sub_title', 'N/A')}")
    print(f"  策略说明:   {strategy.get('description', 'N/A')}")
    print(f"  门店ID:     {strategy.get('merchant_id', 'N/A')}")
    print(f"  门店名称:   {strategy.get('merchant_name', 'N/A')}")
    print(f"  执行日期:   {str(strategy.get('start_date'))[:10]} ~ {str(strategy.get('end_date'))[:10]}")
    print(f"  创建人:     {strategy.get('created_by', 'N/A')}")
    print("=" * 70)

    merchant_id = strategy.get("merchant_id")
    if not merchant_id:
        print("[X] 该策略未关联门店,无法分析")
        return None

    # 2. 计算时间窗口
    start_date = strategy.get("start_date")
    end_date = strategy.get("end_date")

    if not start_date or not end_date:
        print("[X] 策略缺少执行起止日期")
        return None

    if isinstance(start_date, datetime):
        start_date = start_date.strftime("%Y-%m-%d")
    else:
        start_date = str(start_date)[:10]

    if isinstance(end_date, datetime):
        end_date = end_date.strftime("%Y-%m-%d")
    else:
        end_date = str(end_date)[:10]

    start_dt = datetime.strptime(start_date, "%Y-%m-%d")
    end_dt = datetime.strptime(end_date, "%Y-%m-%d")
    duration_days = (end_dt - start_dt).days + 1

    # T-1: 前置基线期(等长周期前移)
    t_minus_1_start = (start_dt - timedelta(days=duration_days)).strftime("%Y-%m-%d")
    t_minus_1_end = (start_dt - timedelta(days=1)).strftime("%Y-%m-%d")

    # T: 策略执行期
    t_start = start_date
    t_end = end_date

    # T+1: 效果跟踪期
    t_plus_1_start = (end_dt + timedelta(days=1)).strftime("%Y-%m-%d")
    t_plus_1_end = (end_dt + timedelta(days=duration_days)).strftime("%Y-%m-%d")
    # 不能超过今天
    today = datetime.now().strftime("%Y-%m-%d")
    if t_plus_1_end > today:
        t_plus_1_end = today
        if t_plus_1_start > t_plus_1_end:
            t_plus_1_start = None  # 表示无跟踪期数据

    periods = [
        ("T-1 前置基线期", t_minus_1_start, t_minus_1_end),
        ("T   策略执行期", t_start, t_end),
        ("T+1 效果跟踪期", t_plus_1_start, t_plus_1_end),
    ]

    print(f"\n  分析时间窗口:")
    for label, ps, pe in periods:
        if ps and pe:
            print(f"    {label}: {ps} ~ {pe} ({(datetime.strptime(pe, '%Y-%m-%d') - datetime.strptime(ps, '%Y-%m-%d')).days + 1}天)")
        else:
            print(f"    {label}: (无数据)")

    # 3. 获取门店配置
    store = get_store_config(merchant_id)
    if not store:
        print(f"\n[!] 门店 {merchant_id} 未在 ods_store_config 中找到配置信息")

    print(f"\n  [*] 门店信息:")
    if store:
        print(f"    名称: {store.get('merchant_name', 'N/A')}")
        print(f"    省份/城市: {store.get('province', 'N/A')}/{store.get('city', 'N/A')}")
        print(f"    运营模式: {store.get('operation_mode', 'N/A')}")
        print(f"    流量分级: {store.get('traffic_grade', 'N/A')}")
        print(f"    区域运营: {store.get('area_manager', 'N/A')}")
        print(f"    线上运营: {store.get('online_ops', 'N/A')}")
        print(f"    飞行督导: {store.get('flight_supervisor', 'N/A')}")

    # 4. 按周期查询数据
    period_metrics = []
    guarantee_data = []
    staff_data = []

    for label, ps, pe in periods:
        print(f"\n  {'='*50}")
        print(f"   {label} ({ps} ~ {pe})" if ps and pe else f"   {label} (无数据)")

        if not ps or not pe or ps > pe:
            print(f"    (该周期无有效数据)")
            period_metrics.append(None)
            guarantee_data.append(None)
            staff_data.append([])
            continue

        # 4a. 门店日报指标(优先从 DWS 宽表,无数据时从员工 ODS 聚合)
        daily = get_store_daily_metrics(merchant_id, ps, pe)
        metrics = aggregate_period_metrics(daily)

        # 4b. 兜底保障数据
        guarantee = get_guarantee_daily(merchant_id, ps, pe)
        g_metrics = aggregate_guarantee_metrics(guarantee)
        guarantee_data.append(g_metrics)

        # 4c. 员工数据(先查员工,用于回退填充店级指标)
        staff = get_staff_daily_metrics(merchant_id, ps, pe)

        # 售前触客数始终从员工 ODS 聚合,并用交付数封顶
        # 原因:源数据中权益/延保品类重复计数(同一批客户计了两次),真实触客 ≤ 交付
        if staff and metrics:
            staff_pre_touch = sum(safe_num(r.get("pre_sale_touch", 0)) for r in staff)
            staff_after_touch = sum(safe_num(r.get("after_sale_touch", 0)) for r in staff)
            # 触客数不超过交付数
            capped_pre = min(staff_pre_touch, metrics["total_delivery"])
            capped_aft = min(staff_after_touch, metrics["total_delivery"] - capped_pre)
            metrics["total_pre_touch"] = capped_pre
            metrics["total_after_touch"] = capped_aft
            metrics["total_touch"] = capped_pre + capped_aft
            metrics["avg_daily_touch"] = round(metrics["total_touch"] / metrics["days"], 1) if metrics["days"] else 0
            # 同步更新触客转化率
            metrics["ew_touch_conversion"] = safe_rate(metrics["total_ew"], capped_pre)
            metrics["ax_touch_conversion"] = safe_rate(metrics["total_ax"], capped_pre)
            metrics["battery_touch_conversion"] = safe_rate(metrics["total_battery"], capped_pre)

        # 回退:当 DWS 宽表无数据但员工 ODS 有数据时,从员工数据聚合店级指标
        if not metrics and staff:
            # 从员工日数据聚合店级交付和触客
            staff_total_touch = sum(safe_num(r.get("pre_sale_touch", 0)) for r in staff)
            staff_total_after_touch = sum(safe_num(r.get("after_sale_touch", 0)) for r in staff)
            staff_total_ew = sum(safe_num(r.get("extended_warranty_orders", 0)) for r in staff)
            staff_total_ax = sum(safe_num(r.get("ax_package_orders", 0)) for r in staff)
            staff_total_battery = sum(safe_num(r.get("battery_extended_orders", 0)) for r in staff)
            staff_total_orders = sum(safe_num(r.get("total_orders", 0)) for r in staff)
            staff_total_battery_money = sum(safe_num(r.get("battery_money", 0)) for r in staff)
            # 天数:取员工中最大的 work_days(即该周期内有记录的员工的最大出勤天数)
            staff_days = max((safe_num(r.get("work_days", 0)) for r in staff), default=0)
            if staff_days == 0:
                staff_days = (datetime.strptime(pe, "%Y-%m-%d") - datetime.strptime(ps, "%Y-%m-%d")).days + 1

            # 交付数从门店日报 ODS 表取(店级指标,不能从员工求和)


            delivery_row = get_store_delivery_from_ods(merchant_id, ps, pe)
            store_delivery = int(safe_num(delivery_row.get("total_delivery", 0))) if delivery_row else 0
            store_data_days = int(safe_num(delivery_row.get("data_days", 0))) if delivery_row else 0

            # 天数为 max(ODS 数据天数, 员工出勤天数)
            actual_days = store_data_days or staff_days

            # 触客数用交付数封顶(避免品类重复计数导致超出)
            capped_touch = min(staff_total_touch, store_delivery)
            capped_after_touch = min(staff_total_after_touch, store_delivery - capped_touch)

            metrics = {
                "days": actual_days,
                "total_delivery": store_delivery,
                "total_pre_touch": capped_touch,
                "total_after_touch": capped_after_touch,
                "total_touch": capped_touch + capped_after_touch,
                "total_ew": staff_total_ew,
                "total_ax": staff_total_ax,
                "total_battery": staff_total_battery,
                "total_orders": staff_total_orders,
                "total_battery_money": round(staff_total_battery_money, 2),
                "avg_daily_delivery": round(store_delivery / actual_days, 1) if actual_days else 0,
                "avg_daily_touch": round((capped_touch + capped_after_touch) / actual_days, 1) if actual_days else 0,
                "avg_daily_orders": round(staff_total_orders / actual_days, 1) if actual_days else 0,
                "ew_conversion": safe_rate(staff_total_ew, store_delivery),
                "ax_conversion": safe_rate(staff_total_ax, store_delivery),
                "battery_conversion": safe_rate(staff_total_battery, store_delivery),
                "ew_touch_conversion": safe_rate(staff_total_ew, capped_touch),
                "ax_touch_conversion": safe_rate(staff_total_ax, capped_touch),
                "battery_touch_conversion": safe_rate(staff_total_battery, capped_touch),
                "_fallback": True,
            }
        period_metrics.append(metrics)

        if metrics:
            fallback_note = " [*]" if metrics.get("_fallback") else ""
            print(f"    数据天数: {metrics['days']}天{fallback_note}")
            print(f"    交付数:   {metrics['total_delivery']}{' (ODS回退)' if metrics.get('_fallback') else ''}")
            print(f"    触客数:   {metrics['total_touch']} (售前{metrics['total_pre_touch']}/售后{metrics['total_after_touch']})")
            print(f"    总订单:   {metrics['total_orders']} (日均{metrics['avg_daily_orders']})")
            print(f"    整车延保: {metrics['total_ew']}  ({metrics['ew_conversion']})")
            print(f"    安心包:   {metrics['total_ax']}  ({metrics['ax_conversion']})")
            print(f"    电池延保: {metrics['total_battery']}  ({metrics['battery_conversion']})")
            print(f"    电池金额: {metrics['total_battery_money']} 元")

            # 周期对比 — 聚焦渗透率变化
            if len(period_metrics) >= 2 and period_metrics[-2]:
                prev = period_metrics[-2]
                print(f"\n     vs 上一周期变化:")
                # 交付/触客基础指标
                print(f"      交付: {prev['total_delivery']} → {metrics['total_delivery']}"
                      f"  {_delta_arrow(prev['total_delivery'], metrics['total_delivery'])}")
                # 各品类渗透率(核心关注)
                _print_pen_delta("整车延保渗透率", prev["ew_conversion"], metrics["ew_conversion"])
                _print_pen_delta("安心包渗透率",   prev["ax_conversion"], metrics["ax_conversion"])
                _print_pen_delta("电池延保渗透率", prev["battery_conversion"], metrics["battery_conversion"])
        else:
            print(f"    (该周期无日报数据)")

        # 兜底保障显示 (已在上面查询)
        if g_metrics:
            print(f"\n     兜底保障:")
            for pt, info in g_metrics.items():
                print(f"      {pt}: 目标{info['target_rate']} / 实际{info['avg_actual_rate']} / "
                      f"触发{info['days_triggered']}/{info['total_days']}天 / 赔付{info['total_compensation']}元")
        else:
            print(f"     兜底保障: 无数据")

        # 员工数据显示 (staff 已在上面查询)
        staff_agg = aggregate_staff_metrics(staff, metrics.get("total_delivery", 0) if metrics else 0)
        staff_data.append(staff_agg)

        if staff_agg:
            print(f"\n     员工数据:")
            # 表头
            print(f"      {'姓名':<8s} {'触客':>4s} {'延保':>4s} {'延保渗透率':>8s} {'安心包':>4s} {'安心包渗透率':>8s} {'电池':>4s} {'电池渗透率':>8s} {'金额':>10s}")
            print(f"      {'-'*8} {'-'*4} {'-'*4} {'-'*8} {'-'*4} {'-'*8} {'-'*4} {'-'*8} {'-'*10}")
            for s in staff_agg:
                print(f"      {s['staff_name']:<8s} {int(s['pre_sale_touch']):>4d} "
                      f"{int(s['extended_warranty_orders']):>4d} {s['ew_penetration']:>8s} "
                      f"{int(s['ax_package_orders']):>4d} {s['ax_penetration']:>8s} "
                      f"{int(s['battery_extended_orders']):>4d} {s['battery_penetration']:>8s} "
                      f"{float(s['battery_money']):>10.2f}")
            # 汇总行
            total_ew = sum(s['extended_warranty_orders'] for s in staff_agg)
            total_ax = sum(s['ax_package_orders'] for s in staff_agg)
            total_bt = sum(s['battery_extended_orders'] for s in staff_agg)
            total_touch = min(sum(s['pre_sale_touch'] for s in staff_agg), metrics.get("total_delivery", 0) if metrics else 0)
            total_money = sum(s['battery_money'] for s in staff_agg)
            print(f"      {'-'*8} {'-'*4} {'-'*4} {'-'*8} {'-'*4} {'-'*8} {'-'*4} {'-'*8} {'-'*10}")
            print(f"      {'合计':<8s} {int(total_touch):>4d} "
                  f"{int(total_ew):>4d} {safe_rate(total_ew, metrics.get('total_delivery', 0) if metrics else 0):>8s} "
                  f"{int(total_ax):>4d} {safe_rate(total_ax, metrics.get('total_delivery', 0) if metrics else 0):>8s} "
                  f"{int(total_bt):>4d} {safe_rate(total_bt, metrics.get('total_delivery', 0) if metrics else 0):>8s} "
                  f"{float(total_money):>10.2f}")
        else:
            print(f"     员工数据: 无数据")

    # 5. 同业对比 (针对策略执行期)
    print(f"\n  {'='*50}")
    print(f"   同业渗透率对比 (T 策略执行期)")
    province = store.get("province", "") if store else ""
    channel = store.get("channel", "") if store else ""

    if province:
        peer_data = get_peer_benchmarks(merchant_id, province, channel, t_start, t_end)
        city_data = get_same_city_avg(merchant_id, t_start, t_end)
        exec_metrics = period_metrics[1] if len(period_metrics) > 1 else None

        if exec_metrics:
            comparisons = compute_comparison(exec_metrics, peer_data, city_data, "策略执行期")

            if peer_data and peer_data.get("peer_avg"):
                pa = peer_data["peer_avg"]
                print(f"    同群门店数: {safe_num(pa.get('peer_count'))}")

            if city_data:
                print(f"    同城门店数: {safe_num(city_data.get('city_peer_count'))}")

            if peer_data and peer_data.get("top5_stores"):
                print(f"\n    本省 Top5 标杆门店:")
                for idx, ts in enumerate(peer_data["top5_stores"], 1):
                    ts_delivery = safe_num(ts.get("total_delivery", 0))
                    print(f"      #{idx} {ts.get('merchant_name', ts['merchant_id'])}: "
                          f"交付{ts_delivery} / "
                          f"延保{ts.get('total_ew', 0)}({safe_rate(ts.get('total_ew', 0), ts_delivery)}) / "
                          f"安心包{ts.get('total_ax', 0)}({safe_rate(ts.get('total_ax', 0), ts_delivery)}) / "
                          f"电池{ts.get('total_battery', 0)}({safe_rate(ts.get('total_battery', 0), ts_delivery)})")

            print(f"\n    渗透率对比详情:")
            for c in comparisons:
                dim = c.get("维度", "")
                other = {k: v for k, v in c.items() if k != "维度"}
                detail = "  ".join(f"{k}: {v}" for k, v in other.items())
                print(f"      [{dim}] {detail}")
        else:
            comparisons = []
    else:
        comparisons = []
        peer_data = {}
        city_data = {}

    # 6. 生成数据概览(始终生成,供导出报告使用)
    period_labels = [p[0] for p in periods]
    data_context = build_analysis_context(
        strategy, store,
        period_labels, period_metrics,
        guarantee_data, staff_data,
        comparisons,
    )

    # 数据驱动结论(始终输出)
    conclusion = generate_conclusion(
        strategy, store, period_labels, period_metrics,
        staff_data, comparisons,
    )
    print(f"\n{conclusion}")

    # 组装最终报告(数据 + 结论)
    if use_llm:
        print(f"  {'='*50}")
        print(f"   LLM 增强分析报告生成中...")
        llm_context = data_context + f"\n\n## 自动分析结论(供参考)\n{conclusion}"
        llm_report = call_llm_for_report(llm_context)
        print(f"\n{llm_report}")
        final_report = (
            f"## 一、完整数据概览\n\n{data_context}\n\n"
            f"---\n\n"
            f"## 二、自动分析结论\n\n{conclusion}\n\n"
            f"---\n\n"
            f"## 三、LLM 增强分析\n\n{llm_report}"
        )
    else:
        final_report = (
            f"## 一、完整数据概览\n\n{data_context}\n\n"
            f"---\n\n"
            f"## 二、自动分析结论\n\n{conclusion}"
        )

    if export:
        out_dir = Path(__file__).parent / "output"
        out_dir.mkdir(parents=True, exist_ok=True)
        filename = out_dir / f"strategy_{strategy_id}_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
        with open(filename, "w", encoding="utf-8") as f:
            f.write(f"# 策略效果分析报告\n\n")
            f.write(f"**策略ID**: {strategy_id}\n\n")
            f.write(f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            f.write("---\n\n")
            f.write(final_report)
        print(f"\n   报告已导出: {filename}")

    print(f"\n{'=' * 70}")
    print(f"  分析完成")
    print(f"{'=' * 70}")

    return {
        "strategy": strategy,
        "store": store,
        "period_metrics": period_metrics,
        "guarantee_data": guarantee_data,
        "staff_data": staff_data,
        "comparisons": comparisons,
    }


def _print_delta(label: str, old_val, new_val):
    """打印环比变化"""
    if old_val is None or new_val is None:
        return
    if old_val == 0 and new_val == 0:
        direction = "→ 持平"
    elif old_val == 0:
        direction = f"↑ +{new_val} (新增)"
    else:
        change = (new_val - old_val) / old_val * 100
        arrow = "↑" if change > 0 else ("↓" if change < 0 else "→")
        direction = f"{arrow} {change:+.1f}%"
    print(f"      {label}: {old_val} → {new_val}  {direction}")


def _delta_arrow(old_val, new_val):
    """返回环比方向箭头"""
    if old_val is None or new_val is None:
        return ""
    if old_val == new_val:
        return "持平"
    return "↑" if new_val > old_val else "↓"


def _print_pen_delta(label: str, old_str: str, new_str: str):
    """打印渗透率环比变化(百分点)"""
    ov = float(old_str.replace("%", "")) if old_str else 0.0
    nv = float(new_str.replace("%", "")) if new_str else 0.0
    diff = nv - ov
    if diff > 0:
        arrow = "↑"
    elif diff < 0:
        arrow = "↓"
    else:
        arrow = "→ 持平"
    print(f"      {label}: {old_str} → {new_str}  {arrow} {diff:+.1f}pp")


def _pen_change(old_m, new_m, key):
    """计算渗透率pp变化"""
    ov = old_m.get(key, 0) if old_m else 0
    nv = new_m.get(key, 0) if new_m else 0
    if isinstance(ov, str):
        ov = float(ov.replace("%", ""))
    if isinstance(nv, str):
        nv = float(nv.replace("%", ""))
    return nv - ov


# ==================== 数据驱动结论 ====================

def generate_conclusion(strategy, store, period_labels, period_metrics,
                        staff_data, comparisons):
    """基于数据自动生成分析结论(无需 LLM)"""
    lines = []
    strategy_type_name = STRATEGY_TYPE_MAP.get(safe_num(strategy.get("strategy_type")), "未知")

    base = period_metrics[0] if len(period_metrics) > 0 else None
    exec_m = period_metrics[1] if len(period_metrics) > 1 else None
    track = period_metrics[2] if len(period_metrics) > 2 else None

    lines.append("=" * 70)
    lines.append("  策略效果分析结论")
    lines.append("=" * 70)

    # ---- 一、策略背景与触发原因 ----
    lines.append("\n## 一、策略背景与触发原因\n")
    store_name = store.get("merchant_name", "N/A") if store else str(strategy.get("merchant_id"))
    lines.append(f"- 门店: {store_name} ({store.get('province', '')}/{store.get('city', '') if store else ''})")
    lines.append(f"- 策略类型: {strategy_type_name}")
    lines.append(f"- 策略说明: {strategy.get('description', 'N/A') or 'N/A'}")

    # 从 T-1 基线期分析触发原因
    if base:
        ew_pen = base.get("ew_conversion", "0%")
        ax_pen = base.get("ax_conversion", "0%")
        bt_pen = base.get("battery_conversion", "0%")
        touch_per_day = base.get("avg_daily_touch", 0)

        reasons = []
        if isinstance(ew_pen, str):
            ew_val = float(ew_pen.replace("%", ""))
        else:
            ew_val = ew_pen
        if isinstance(ax_pen, str):
            ax_val = float(ax_pen.replace("%", ""))
        else:
            ax_val = ax_pen

        if ew_val < 15:
            reasons.append(f"整车延保渗透率仅 {ew_pen},严重偏低")
        elif ew_val < 30:
            reasons.append(f"整车延保渗透率 {ew_pen},有提升空间")
        if ax_val < 10:
            reasons.append(f"安心包渗透率仅 {ax_pen},产品推广不足")
        if touch_per_day < 2:
            reasons.append(f"日均触客仅 {touch_per_day},客源触达不足")

        if not reasons:
            reasons.append(f"基线期延保渗透率 {ew_pen},安心包 {ax_pen},存在改善空间")

        for r in reasons:
            lines.append(f"  [!] {r}")

        lines.append(f"\n  T-1 基线期: {base.get('total_delivery', 0)}次交付 / {base.get('total_touch', 0)}次触客, "
                      f"整车延保{base.get('total_ew', 0)}单({ew_pen}), "
                      f"安心包{base.get('total_ax', 0)}单({ax_pen}), "
                      f"电池延保{base.get('total_battery', 0)}单({bt_pen})")
    else:
        lines.append("  (T-1 基线期无数据,无法分析触发原因)")

    # ---- 二、策略执行效果 ----
    lines.append("\n## 二、策略执行效果\n")

    if exec_m:
        def rate_pp(delta):
            if delta > 10: return "大幅提升(显著改善)"
            if delta > 3: return "明显提升"
            if delta > 0: return "小幅提升"
            if delta == 0: return "持平"
            if delta > -3: return "小幅下降"
            if delta > -10: return "明显下降"
            return "大幅下降(需关注)"

        # T vs T-1
        if base:
            lines.append("### 策略执行期 vs 基线期 (T vs T-1)")
            ew_delta = _pen_change(base, exec_m, "ew_conversion")
            ax_delta = _pen_change(base, exec_m, "ax_conversion")
            bt_delta = _pen_change(base, exec_m, "battery_conversion")
            touch_delta_pp = (exec_m.get("avg_daily_touch", 0) / max(base.get("avg_daily_touch", 0.1), 0.1) - 1) * 100

            lines.append(f"  - 整车延保渗透率变化: {ew_delta:+.1f}pp → {rate_pp(ew_delta)}")
            lines.append(f"  - 安心包渗透率变化: {ax_delta:+.1f}pp → {rate_pp(ax_delta)}")
            lines.append(f"  - 电池延保渗透率变化: {bt_delta:+.1f}pp → {rate_pp(bt_delta)}")
            if touch_delta_pp > 10:
                lines.append(f"  - 日均触客变化: {touch_delta_pp:+.0f}% → 客源拓展有改善")

            # 综合判断
            improvements = sum(1 for d in [ew_delta, ax_delta, bt_delta] if d > 0)
            if improvements >= 2:
                lines.append(f"\n  [OK] T期综合判断: 改善产品数 {improvements}/3,策略执行期间渗透率有所提升")
            elif improvements == 1:
                lines.append(f"\n  [~] T期综合判断: 仅 {improvements}/3 产品改善,效果有限")
            else:
                lines.append(f"\n  [X] T期综合判断: 所有产品渗透率均未改善,策略执行期效果不佳")

        # T+1 vs T
        if track:
            lines.append("\n### 效果跟踪期 vs 执行期 (T+1 vs T)")
            ew_delta2 = _pen_change(exec_m, track, "ew_conversion")
            ax_delta2 = _pen_change(exec_m, track, "ax_conversion")
            bt_delta2 = _pen_change(exec_m, track, "battery_conversion")

            lines.append(f"  - 整车延保渗透率变化: {ew_delta2:+.1f}pp → {rate_pp(ew_delta2)}")
            lines.append(f"  - 安心包渗透率变化: {ax_delta2:+.1f}pp → {rate_pp(ax_delta2)}")
            lines.append(f"  - 电池延保渗透率变化: {bt_delta2:+.1f}pp → {rate_pp(bt_delta2)}")

            if ew_delta2 > 0 or ax_delta2 > 0 or bt_delta2 > 0:
                lines.append(f"\n  [OK] 跟踪期仍有改善,策略具备持续性")
            elif ew_delta2 == 0 and ax_delta2 == 0 and bt_delta2 == 0:
                lines.append(f"\n  [~] 跟踪期持平,策略效果已趋于稳定")
            else:
                lines.append(f"\n  [X] 跟踪期回落,策略效果不具备持续性,需持续关注")
    else:
        lines.append("  (无执行期数据)")

    # ---- 三、同业对比 ----
    lines.append("\n## 三、同业对比诊断\n")
    if comparisons:
        for c in comparisons:
            dim = c.get("维度", "")
            if "同业-" in dim:
                diff = c.get("差异", "")
                if diff and diff.startswith("-"):
                    lines.append(f"  [X] {dim}: {diff},低于同业水平")
                elif diff and diff.startswith("+"):
                    lines.append(f"  [OK] {dim}: {diff},优于同业水平")
                else:
                    lines.append(f"  [~] {dim}: {diff}")
            elif "标杆-" in dim:
                vs = c.get("vs.Top1", "")
                product_name = dim.replace("标杆-", "").replace("渗透率", "")
                lines.append(f"  - {product_name}: {vs}(本店 vs 省Top1)")
    else:
        lines.append("  (无同业数据可供对比)")

    # ---- 四、员工表现 ----
    exec_staff = staff_data[1] if len(staff_data) > 1 and staff_data[1] else (staff_data[0] if staff_data[0] else [])
    if exec_staff:
        lines.append("\n## 四、员工表现\n")
        top3 = exec_staff[:3]
        bottom3 = exec_staff[-3:] if len(exec_staff) > 3 else []
        lines.append(f"  渗透率 Top3: {', '.join(s['staff_name'] for s in top3)}")
        if bottom3:
            lines.append(f"  渗透率 Bottom3: {', '.join(s['staff_name'] for s in bottom3)}")

        # 找出明星员工和待提升员工
        top_pen = top3[0]["composite_penetration_num"] if top3 else 0
        if top_pen > 10:
            lines.append(f"  [OK] 有明星员工(综合渗透率>{top_pen:.0f}%),可总结优秀话术推广")
        gap = top_pen - (bottom3[-1]["composite_penetration_num"] if bottom3 else 0)
        if gap > 15:
            lines.append(f"  [!] 员工渗透率差距大({gap:.0f}pp),需针对性辅导低绩效人员")

    # ---- 五、综合评估与建议 ----
    lines.append("\n## 五、综合评估与建议\n")

    # 打分
    score = 50  # 基础分
    if base and exec_m:
        ew_d = _pen_change(base, exec_m, "ew_conversion")
        ax_d = _pen_change(base, exec_m, "ax_conversion")
        bt_d = _pen_change(base, exec_m, "battery_conversion")
        avg_improve = (ew_d + ax_d + bt_d) / 3
        if avg_improve > 5:
            score += 20
        elif avg_improve > 0:
            score += 10

    if track and exec_m:
        ew_d2 = _pen_change(exec_m, track, "ew_conversion")
        ax_d2 = _pen_change(exec_m, track, "ax_conversion")
        bt_d2 = _pen_change(exec_m, track, "battery_conversion")
        avg_improve2 = (ew_d2 + ax_d2 + bt_d2) / 3
        if avg_improve2 > 3:
            score += 15
        elif avg_improve2 > 0:
            score += 5
        elif avg_improve2 < -5:
            score -= 10

    # 同业对比加分
    if comparisons:
        beat_count = sum(1 for c in comparisons if c.get("差异", "").startswith("+"))
        if beat_count >= 5:
            score += 10
        elif beat_count >= 2:
            score += 5

    if score >= 80:
        grade = "A (优秀)"
    elif score >= 65:
        grade = "B (良好)"
    elif score >= 50:
        grade = "C (一般)"
    else:
        grade = "D (需改进)"

    lines.append(f"  综合评分: {score}/100 → {grade}")
    lines.append(f"\n  评估逻辑:")
    lines.append(f"  - 策略类型「{strategy_type_name}」对门店{store_name}")

    if base and exec_m:
        ew_p0 = base.get("ew_conversion", "0%")
        ew_p1 = exec_m.get("ew_conversion", "0%")
        lines.append(f"  - T-1→T 期延保渗透率: {ew_p0} → {ew_p1}")
    if exec_m and track:
        ew_p2 = track.get("ew_conversion", "0%")
        lines.append(f"  - T→T+1 期延保渗透率: {exec_m.get('ew_conversion', '0%')} → {ew_p2}")

    lines.append("\n## 建议\n")
    suggestions = []

    # 基于数据给出建议
    if base and exec_m:
        if _pen_change(base, exec_m, "ew_conversion") < 3:
            suggestions.append("整车延保渗透率提升有限,建议检查话术培训是否到位,或调整激励政策")

    if comparisons:
        ew_peer_behind = any("同业-整车延保" in c.get("维度", "") and c.get("差异", "").startswith("-") for c in comparisons)
        if ew_peer_behind:
            suggestions.append("整车延保渗透率持续低于同业,建议对标省内 Top 门店学习其销售方法")

    if exec_staff and len(exec_staff) >= 2:
        if exec_staff[0]["composite_penetration_num"] - exec_staff[-1]["composite_penetration_num"] > 15:
            suggestions.append(f"员工间渗透率差异大,建议由 {exec_staff[0]['staff_name']} 做经验分享,手把手带教低绩效员工")

    if not suggestions:
        suggestions.append("持续跟踪该门店表现,关注下一周期数据变化")
        suggestions.append("将此策略经验沉淀为标准化流程,复用到其他类似门店")

    for s in suggestions:
        lines.append(f"  - {s}")

    lines.append("")
    return "\n".join(lines)


# ==================== CLI ====================

def main():
    parser = argparse.ArgumentParser(description="策略效果分析 Demo")
    parser.add_argument("--id", type=int, help="策略ID,不传则列出所有策略")
    parser.add_argument("--llm", action="store_true", help="调用LLM生成分析报告")
    parser.add_argument("--export-report", action="store_true", help="导出分析报告到Markdown文件")
    parser.add_argument("--list", action="store_true", help="列出策略列表")
    args = parser.parse_args()

    if args.list or (not args.id):
        print("=" * 70)
        print("  策略列表 (最近20条)")
        print("=" * 70)
        strategies = list_strategies(20)
        for s in strategies:
            flag_map = {0: "未推送", 1: "已推送", 2: "未完成", 3: "审批中", 4: "执行中", 5: "已驳回", 6: "已完成"}
            flag_name = flag_map.get(s.get("push_flag"), str(s.get("push_flag")))
            stype = STRATEGY_TYPE_MAP.get(safe_num(s.get("strategy_type")), "未知")
            print(f"  ID:{s['id']:>4} | {stype: <12s} | {str(s.get('start_date'))[:10]} ~ {str(s.get('end_date'))[:10]} | "
                  f"门店:{s.get('merchant_name', 'N/A') or 'N/A': <15s} | {flag_name} | {s.get('title', '') or ''}")
        if not args.id:
            print(f"\n用法: python tests/strategy_analysis_demo.py --id <策略ID> [--llm] [--export-report]")
            return

    if args.id:
        analyze_strategy(args.id, use_llm=args.llm, export=args.export_report)


if __name__ == "__main__":
    main()