merchant_goods_code_processor.py 60.5 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
merchant_goods_code 补齐处理器
根据文档第11章节实现两轮补数逻辑
"""

import logging
from datetime import datetime
from scene_type_mapping import DATA_MIGRATION_USER, DATA_MIGRATION_USER2


class MerchantGoodsCodeProcessor:
    """merchant_goods_code 补齐处理器"""

    def __init__(self, db_helper, test_mode=False):
        """
        初始化处理器

        Args:
            db_helper: 数据库辅助实例
            test_mode: 是否为测试模式
        """
        self.db = db_helper
        self.test_mode = test_mode
        self.logger = logging.getLogger(__name__)

        # 临时表名
        self.context_table = 'tmp_goods_relation_context'
        self.detail_table = 'tmp_merchant_goods_code_detail'
        self.exception_table = 'tmp_merchant_goods_code_exception'
        # self.query_keys_table = 'tmp_query_keys'  # 用于批量查询的临时表

        # 内存缓存:商品数据
        self.goods_code_cache = None  # {(merchant_id, base_scene_code, upgrade_goods_id): [merchant_goods_code, ...]}

        # 内存缓存:订单数据
        self.order_finance_cache = None  # {(settle_rule_id, base_scene_code, upgrade_goods_id): [merchant_goods_code, ...]}
        self.order_reconciliation_cache = None  # {(reconciliation_rule_id, base_scene_code, upgrade_goods_id): [merchant_goods_code, ...]}

    def create_temp_tables(self):
        """创建临时表"""
        self.logger.info("创建临时表...")

        # 1. 规则上下文表
        create_context_sql = f"""
        CREATE TABLE IF NOT EXISTS {self.context_table} (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            relation_id BIGINT NOT NULL COMMENT '规则关系表ID',
            rule_type TINYINT NOT NULL COMMENT '规则类型:1=财务,3=对账',
            goods_type_group_rule_id BIGINT NOT NULL COMMENT '商品分组规则ID',
            upgrade_goods_id BIGINT COMMENT '升级商品ID',
            merchant_id BIGINT COMMENT '商户ID',
            scene_type TINYINT COMMENT '场景类型',
            base_scene_code VARCHAR(20) COMMENT '细分场景编码',
            settle_rule_id BIGINT COMMENT '财务规则ID',
            reconciliation_rule_id BIGINT COMMENT '对账规则ID',
            created_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            KEY idx_relation (relation_id),
            KEY idx_rule_type (rule_type, goods_type_group_rule_id),
            KEY idx_merchant_scene (merchant_id, scene_type, base_scene_code)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规则商品关系上下文临时表';
        """

        # 2. 补数明细表
        create_detail_sql = f"""
        CREATE TABLE IF NOT EXISTS {self.detail_table} (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            relation_id BIGINT NOT NULL COMMENT '原规则关系表ID',
            rule_type TINYINT NOT NULL COMMENT '规则类型',
            goods_type_group_rule_id BIGINT NOT NULL COMMENT '商品分组规则ID',
            upgrade_goods_id BIGINT COMMENT '升级商品ID',
            merchant_id BIGINT COMMENT '商户ID',
            scene_type TINYINT COMMENT '场景类型',
            base_scene_code VARCHAR(20) COMMENT '细分场景编码',
            merchant_goods_code VARCHAR(100) COMMENT '推导出的商品编码',
            source_type VARCHAR(50) COMMENT '来源类型:MERCHANT_GOODS_REF/ORDER_HISTORY',
            action_type VARCHAR(50) COMMENT '处理动作:UPDATE_ORIGIN/INSERT_COPY/SKIP',
            skip_reason VARCHAR(500) COMMENT '跳过原因或异常原因',
            created_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            KEY idx_relation (relation_id),
            KEY idx_merchant_goods (merchant_id, merchant_goods_code)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='merchant_goods_code补数明细表';
        """

        # 3. 异常清单表
        create_exception_sql = f"""
        CREATE TABLE IF NOT EXISTS {self.exception_table} (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            relation_id BIGINT NOT NULL COMMENT '规则关系表ID',
            exception_type VARCHAR(100) COMMENT '异常类型',
            exception_desc TEXT COMMENT '异常描述',
            created_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            KEY idx_relation (relation_id),
            KEY idx_type (exception_type)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='merchant_goods_code补数异常清单表';
        """

        # 4. 批量查询键临时表(内存表,用于JOIN优化)
        # create_query_keys_sql = f"""
        # CREATE TABLE IF NOT EXISTS {self.query_keys_table} (
        #     merchant_id BIGINT,
        #     base_scene_code VARCHAR(20) COLLATE utf8mb4_unicode_ci,
        #     upgrade_goods_id BIGINT,
        #     settle_rule_id BIGINT,
        #     reconciliation_rule_id BIGINT,
        #     KEY idx_merchant_goods (merchant_id, base_scene_code, upgrade_goods_id),
        #     KEY idx_finance (settle_rule_id, base_scene_code, upgrade_goods_id),
        #     KEY idx_reconciliation (reconciliation_rule_id, base_scene_code, upgrade_goods_id)
        # ) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='批量查询键临时表';
        # """

        self.db.execute_update(create_context_sql)
        self.db.execute_update(create_detail_sql)
        self.db.execute_update(create_exception_sql)
        # self.db.execute_update(create_query_keys_sql)
        self.logger.info("临时表创建完成")

    def drop_temp_tables(self):
        """删除临时表"""
        self.logger.info("删除临时表...")
        self.db.execute_update(f"DROP TABLE IF EXISTS {self.context_table};")
        self.db.execute_update(f"DROP TABLE IF EXISTS {self.detail_table};")
        self.db.execute_update(f"DROP TABLE IF EXISTS {self.exception_table};")
        self.logger.info("临时表删除完成")

    def load_merchant_goods_cache(self):
        """
        程序启动时加载所有商品数据到内存
        构建 {(merchant_id, base_scene_code, upgrade_goods_id): [merchant_goods_code, ...]} 映射
        """
        import sys

        self.logger.info("=" * 80)
        self.logger.info("开始加载商品数据到内存...")

        query_sql = """
        SELECT
            mgr.merchant_id,
            mgi.base_scene_code,
            mgi.upgrade_goods_id,
            mgi.merchant_goods_code,
            mgi.id
        FROM dj_car_life_merchant_goods_info mgi
        JOIN dj_car_life_merchant_goods_ref mgr
          ON mgr.merchant_goods_id = mgi.id
        WHERE (mgi.merchant_goods_code IS NOT NULL
          or mgi.merchant_goods_code != '')
        ORDER BY mgr.merchant_id, mgi.base_scene_code, mgi.upgrade_goods_id, mgi.id, mgi.merchant_goods_code;
        """

        results = self.db.execute_query(query_sql)

        if not results:
            self.logger.warning("未查询到任何商品数据!")
            self.goods_code_cache = {}
            return

        # 构建缓存
        self.goods_code_cache = {}
        total_records = len(results)

        for row in results:
            merchant_id, base_scene_code, upgrade_goods_id, merchant_goods_code, mgi_id = row
            key = (merchant_id, base_scene_code, upgrade_goods_id)

            if key not in self.goods_code_cache:
                self.goods_code_cache[key] = []

            # 去重(保持顺序)
            if merchant_goods_code not in self.goods_code_cache[key]:
                self.goods_code_cache[key].append(merchant_goods_code)

        # 计算内存占用(粗略估算)
        cache_size_mb = sys.getsizeof(self.goods_code_cache) / 1024 / 1024
        estimated_mb = total_records * 264 / 1024 / 1024

        self.logger.info(f"商品数据加载完成:")
        self.logger.info(f"  - 原始记录数:{total_records:,} 条")
        self.logger.info(f"  - 唯一键数量:{len(self.goods_code_cache):,} 个")
        self.logger.info(f"  - 缓存对象大小:{cache_size_mb:.2f} MB")
        self.logger.info(f"  - 预估总内存:{estimated_mb:.2f} MB")
        self.logger.info("=" * 80)

    def load_order_cache(self):
        """
        程序启动时加载所有订单数据到内存
        构建财务规则和对账规则的订单商品编码映射
        """
        import sys

        self.logger.info("=" * 80)
        self.logger.info("开始加载订单数据到内存...")

        # 1. 加载财务规则订单数据
        finance_sql = """
        SELECT
            ord.specify_account_rule_id,
            ord.base_scene_code,
            sub.upgrade_goods_id,
            sub.merchant_goods_code
        FROM dj_car_life_goods_order ord
        JOIN dj_car_life_goods_sub_order sub
          ON sub.order_code = ord.order_code
         AND sub.upgrade_goods_id IS NOT NULL
         AND sub.merchant_goods_code IS NOT NULL
         AND sub.merchant_goods_code != ''
        WHERE ord.specify_account_rule_id IS NOT NULL
        ORDER BY ord.specify_account_rule_id,
                 ord.base_scene_code, sub.upgrade_goods_id, sub.merchant_goods_code;
        """

        finance_results = self.db.execute_query(finance_sql)

        # 构建财务规则缓存
        self.order_finance_cache = {}
        for row in finance_results:
            settle_rule_id, base_scene_code, upgrade_goods_id, merchant_goods_code = row
            key = (settle_rule_id, base_scene_code, upgrade_goods_id)

            if key not in self.order_finance_cache:
                self.order_finance_cache[key] = []

            if merchant_goods_code not in self.order_finance_cache[key]:
                self.order_finance_cache[key].append(merchant_goods_code)

        # 2. 加载对账规则订单数据
        reconciliation_sql = """
        SELECT
            ord.specify_reconciliation_rule_id,
            ord.base_scene_code,
            sub.upgrade_goods_id,
            sub.merchant_goods_code
        FROM dj_car_life_goods_order ord
        JOIN dj_car_life_goods_sub_order sub
          ON sub.order_code = ord.order_code
         AND sub.upgrade_goods_id IS NOT NULL
         AND sub.merchant_goods_code IS NOT NULL
         AND sub.merchant_goods_code != ''
        WHERE ord.specify_reconciliation_rule_id IS NOT NULL
        ORDER BY ord.specify_reconciliation_rule_id, ord.base_scene_code,
                 sub.upgrade_goods_id, sub.merchant_goods_code;
        """

        reconciliation_results = self.db.execute_query(reconciliation_sql)

        # 构建对账规则缓存
        self.order_reconciliation_cache = {}
        for row in reconciliation_results:
            reconciliation_rule_id, base_scene_code, upgrade_goods_id, merchant_goods_code = row
            key = (reconciliation_rule_id, base_scene_code, upgrade_goods_id)

            if key not in self.order_reconciliation_cache:
                self.order_reconciliation_cache[key] = []

            if merchant_goods_code not in self.order_reconciliation_cache[key]:
                self.order_reconciliation_cache[key].append(merchant_goods_code)

        # 计算内存占用
        total_records = len(finance_results) + len(reconciliation_results)
        finance_cache_size = sys.getsizeof(self.order_finance_cache) / 1024 / 1024
        reconciliation_cache_size = sys.getsizeof(self.order_reconciliation_cache) / 1024 / 1024
        estimated_mb = total_records * 264 / 1024 / 1024

        self.logger.info(f"订单数据加载完成:")
        self.logger.info(f"  - 财务规则记录数:{len(finance_results):,} 条")
        self.logger.info(f"  - 财务规则唯一键:{len(self.order_finance_cache):,} 个")
        self.logger.info(f"  - 对账规则记录数:{len(reconciliation_results):,} 条")
        self.logger.info(f"  - 对账规则唯一键:{len(self.order_reconciliation_cache):,} 个")
        self.logger.info(f"  - 财务缓存大小:{finance_cache_size:.2f} MB")
        self.logger.info(f"  - 对账缓存大小:{reconciliation_cache_size:.2f} MB")
        self.logger.info(f"  - 预估总内存:{estimated_mb:.2f} MB")
        self.logger.info("=" * 80)

    def build_rule_context(self):
        """
        构造规则上下文
        将 dj_car_life_goods_type_group_relation 中需要补齐的记录
        反推出规则上下文(merchant_id, scene_type, base_scene_code)
        """
        self.logger.info("=" * 80)
        self.logger.info("开始构造规则上下文...")

        # 清空上下文表
        self.db.execute_update(f"TRUNCATE TABLE {self.context_table};")

        # 1. 处理财务规则(rule_type=1)
        self.logger.info("处理财务规则上下文(rule_type=1)...")
        self._build_finance_context()

        # 2. 处理对账规则(rule_type=3)
        self.logger.info("处理对账规则上下文(rule_type=3)...")
        self._build_reconciliation_context()

        # 统计
        count_sql = f"SELECT COUNT(*) FROM {self.context_table};"
        result = self.db.execute_query_one(count_sql)
        total_count = result[0] if result else 0
        self.logger.info(f"规则上下文构造完成,共 {total_count} 条记录")

    def _build_finance_context(self):
        """构造财务规则上下文"""
        # 财务规则链路:
        # dj_car_life_goods_type_group_relation.goods_type_group_rule_id
        #   -> dj_car_life_goods_type_group.id
        #   -> dj_car_life_merchant_goods_type_group_settle_rule.goods_type_group_id
        #   -> dj_car_life_merchant_settle_account_rule.id
        # 同时关联分账规则:不要了,根据财务补就行
        #   -> dj_car_life_merchant_goods_type_group_division_rule.goods_type_group_id
        #   -> dj_car_life_merchant_division_rule.id

        insert_sql = f"""
        INSERT INTO {self.context_table}
        (relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
         merchant_id, scene_type, base_scene_code, settle_rule_id)
        SELECT DISTINCT
            gtgr.id AS relation_id,
            1 AS rule_type,
            gtgr.goods_type_group_rule_id,
            gtgr.upgrade_goods_id,
            sar.merchant_id,
            sar.scene_type,
            sar.base_scene_code,
            sar.id AS settle_rule_id
        FROM dj_car_life_goods_type_group_relation gtgr
        JOIN dj_car_life_goods_type_group gtg
          ON gtg.id = gtgr.goods_type_group_rule_id
        JOIN dj_car_life_merchant_goods_type_group_settle_rule gtgsr
          ON gtgsr.goods_type_group_id = gtg.id
        JOIN dj_car_life_merchant_settle_account_rule sar
          ON sar.id = gtgsr.settle_rule_id
        WHERE gtgr.rule_type = 1
          AND gtgr.category_type = 2 and sar.scene_type in (0,1,2,3,7)
          AND gtgr.upgrade_goods_id IS NOT NULL
          AND (gtgr.merchant_goods_code IS NULL OR gtgr.merchant_goods_code = '');;
        """

        if self.db.execute_update(insert_sql):
            count_sql = f"SELECT COUNT(*) FROM {self.context_table} WHERE rule_type = 1;"
            result = self.db.execute_query_one(count_sql)
            count = result[0] if result else 0
            self.logger.info(f"  财务规则上下文:{count} 条")

    def _build_reconciliation_context(self):
        """构造对账规则上下文"""
        # 对账规则链路:
        # dj_car_life_goods_type_group_relation.goods_type_group_rule_id
        #   -> dj_car_life_merchant_goods_type_group_reconciliation_rule.id
        #   -> dj_car_life_merchant_reconciliation_rule.id

        insert_sql = f"""
        INSERT INTO {self.context_table}
        (relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
         merchant_id, scene_type, base_scene_code, reconciliation_rule_id)
        SELECT DISTINCT
            gtgr.id AS relation_id,
            3 AS rule_type,
            gtgr.goods_type_group_rule_id,
            gtgr.upgrade_goods_id,
            rr.merchant_id,
            rr.scene_type,
            rr.base_scene_code,
            rr.id AS reconciliation_rule_id
        FROM dj_car_life_goods_type_group_relation gtgr
        JOIN dj_car_life_merchant_goods_type_group_reconciliation_rule gtgrr
          ON gtgrr.id = gtgr.goods_type_group_rule_id
        JOIN dj_car_life_merchant_reconciliation_rule rr
          ON rr.id = gtgrr.reconciliation_rule_id
        WHERE gtgr.rule_type = 3
          AND gtgr.category_type = 2  and rr.scene_type in (0,1,2,3,7)
          AND gtgr.upgrade_goods_id IS NOT NULL
          AND (gtgr.merchant_goods_code IS NULL OR gtgr.merchant_goods_code = '');
        """

        if self.db.execute_update(insert_sql):
            count_sql = f"SELECT COUNT(*) FROM {self.context_table} WHERE rule_type = 3;"
            result = self.db.execute_query_one(count_sql)
            count = result[0] if result else 0
            self.logger.info(f"  对账规则上下文:{count} 条")

    def round1_fill_from_merchant_goods(self):
        """
        第一轮补数:从商品上架数据和商户商品关联表补齐
        先按商户+规则类型维度分组,再对每组进行批量处理(每批5000条,使用游标分页)
        """
        import gc

        self.logger.info("=" * 80)
        self.logger.info("第一轮补数:从商品上架数据补齐...")

        # 查询总记录数(用于进度显示)
        count_sql = f"SELECT COUNT(*) FROM {self.context_table};"
        result = self.db.execute_query_one(count_sql)
        total_count = result[0] if result else 0
        self.logger.info(f"共 {total_count} 条记录需要处理")

        # 第一步:查询所有需要处理的商户+规则类型组合
        merchant_rule_sql = f"""
        SELECT DISTINCT merchant_id, rule_type
        FROM {self.context_table}
        ORDER BY merchant_id, rule_type;
        """
        merchant_rule_groups = self.db.execute_query(merchant_rule_sql)

        if not merchant_rule_groups:
            self.logger.warning("未找到需要处理的商户+规则类型组合")
            return

        self.logger.info(f"共 {len(merchant_rule_groups)} 个商户+规则类型组合需要处理")

        # 全局统计
        global_total_processed = 0
        global_total_updated = 0
        global_total_inserted = 0
        global_total_skipped = 0
        group_num = 0

        # 第二步:遍历每个商户+规则类型组合
        for merchant_id, rule_type in merchant_rule_groups:
            group_num += 1
            self.logger.info(f"=" * 60)
            self.logger.info(f"处理第 {group_num}/{len(merchant_rule_groups)} 组:merchant_id={merchant_id}, rule_type={rule_type}")

            # 查询当前组的记录数
            group_count_sql = f"""
            SELECT COUNT(*) FROM {self.context_table}
            WHERE merchant_id = {merchant_id} AND rule_type = {rule_type};
            """
            result = self.db.execute_query_one(group_count_sql)
            group_total_count = result[0] if result else 0
            self.logger.info(f"  当前组共 {group_total_count} 条记录")

            # 第三步:对当前组进行游标分页处理
            batch_size = 5000
            last_id = 0
            batch_num = 0
            group_processed = 0
            group_updated = 0
            group_inserted = 0
            group_skipped = 0

            while True:
                batch_num += 1
                self.logger.info(f"  处理批次 {batch_num},已处理 {group_processed}/{group_total_count} 条")

                # 使用游标分页,增加 merchant_id 和 rule_type 过滤条件
                query_sql = f"""
                SELECT id, relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
                       merchant_id, scene_type, base_scene_code
                FROM {self.context_table}
                WHERE merchant_id = {merchant_id}
                  AND rule_type = {rule_type}
                  AND id > {last_id}
                ORDER BY id
                LIMIT {batch_size};
                """

                contexts = self.db.execute_query(query_sql)
                if not contexts:
                    break

                # 记录本批次最大ID,用于下次游标查询
                last_id = contexts[-1][0]

                # 批量查询所有需要的 merchant_goods_code
                # 构建查询条件:按 (merchant_id, base_scene_code, upgrade_goods_id) 分组
                query_keys = set()
                ctx_map = {}  # relation_id -> context
                for ctx in contexts:
                    ctx_id, relation_id, rule_type_val, goods_type_group_rule_id, upgrade_goods_id, \
                    merchant_id_val, scene_type, base_scene_code = ctx

                    query_keys.add((merchant_id_val, base_scene_code, upgrade_goods_id))
                    ctx_map[relation_id] = {
                        'ctx_id': ctx_id,
                        'relation_id': relation_id,
                        'rule_type': rule_type_val,
                        'goods_type_group_rule_id': goods_type_group_rule_id,
                        'upgrade_goods_id': upgrade_goods_id,
                        'merchant_id': merchant_id_val,
                        'scene_type': scene_type,
                        'base_scene_code': base_scene_code
                    }

                # 批量查询 merchant_goods_code
                self.logger.info(f"    批量查询 {len(query_keys)} 组商品编码...")
                goods_code_map = self._batch_query_merchant_goods_codes(list(query_keys))

                # 准备批量更新和插入的数据
                updates = []  # [(relation_id, merchant_goods_code)]
                inserts = []  # [(relation_id, rule_type, goods_type_group_rule_id, merchant_goods_code, ...)]
                details = []  # 明细记录

                processed = 0
                updated = 0
                inserted = 0
                skipped = 0

                for relation_id, ctx in ctx_map.items():
                    key = (ctx['merchant_id'], ctx['base_scene_code'], ctx['upgrade_goods_id'])
                    merchant_goods_codes = goods_code_map.get(key, [])
                    # 打印要拆分的商品和上架ID
                    self.logger.info(f"      relation_id={relation_id}, key={key}, merchant_goods_codes={merchant_goods_codes}")

                    if not merchant_goods_codes:
                        skipped += 1
                        continue

                    # 处理匹配结果
                    if len(merchant_goods_codes) == 1:
                        # 只有一条,更新原记录
                        code = merchant_goods_codes[0]
                        updates.append((relation_id, code))
                        details.append((relation_id, code, 'MERCHANT_GOODS_REF', 'UPDATE_ORIGIN', None,
                                      ctx['rule_type'], ctx['goods_type_group_rule_id'], ctx['upgrade_goods_id'],
                                      ctx['merchant_id'], ctx['scene_type'], ctx['base_scene_code']))
                        updated += 1
                    else:
                        # 多条,原记录更新第一条,其余复制插入
                        first_code = merchant_goods_codes[0]
                        updates.append((relation_id, first_code))
                        details.append((relation_id, first_code, 'MERCHANT_GOODS_REF', 'UPDATE_ORIGIN', None,
                                      ctx['rule_type'], ctx['goods_type_group_rule_id'], ctx['upgrade_goods_id'],
                                      ctx['merchant_id'], ctx['scene_type'], ctx['base_scene_code']))
                        updated += 1

                        for code in merchant_goods_codes[1:]:
                            inserts.append((relation_id, ctx['rule_type'], ctx['goods_type_group_rule_id'], code))
                            details.append((relation_id, code, 'MERCHANT_GOODS_REF', 'INSERT_COPY', None,
                                          ctx['rule_type'], ctx['goods_type_group_rule_id'], ctx['upgrade_goods_id'],
                                          ctx['merchant_id'], ctx['scene_type'], ctx['base_scene_code']))
                            inserted += 1

                    processed += 1

                # 批量执行更新
                if updates:
                    self.logger.info(f"    批量更新 {len(updates)} 条记录...")
                    self._batch_update_original_records(updates)

                # 批量执行插入
                if inserts:
                    self.logger.info(f"    批量插入 {len(inserts)} 条记录...")
                    self._batch_insert_copy_records(inserts)

                # 批量记录明细
                if details:
                    self.logger.info(f"    批量记录 {len(details)} 条明细...")
                    self._batch_log_details(details)

                self.logger.info(f"    批次完成:处理 {processed} 条,更新 {updated} 条,插入 {inserted} 条,跳过 {skipped} 条")

                group_processed += processed
                group_updated += updated
                group_inserted += inserted
                group_skipped += skipped

                # 内存管理:清理大对象
                del updates, inserts, details, ctx_map, goods_code_map, query_keys, contexts

                # 每10批强制垃圾回收
                if batch_num % 10 == 0:
                    gc.collect()
                    self.logger.info(f"    已完成 {batch_num} 批次,执行垃圾回收")

            # 当前组处理完成
            self.logger.info(f"  当前组完成:处理 {group_processed} 条,更新 {group_updated} 条,插入 {group_inserted} 条,跳过 {group_skipped} 条")

            global_total_processed += group_processed
            global_total_updated += group_updated
            global_total_inserted += group_inserted
            global_total_skipped += group_skipped

        self.logger.info("=" * 80)
        self.logger.info(f"第一轮补数完成:总计处理 {global_total_processed} 条,更新 {global_total_updated} 条,插入 {global_total_inserted} 条,跳过 {global_total_skipped} 条")

    def _query_merchant_goods_codes(self, merchant_id, base_scene_code, upgrade_goods_id):
        """
        查询商户商品编码

        Args:
            merchant_id: 商户ID
            base_scene_code: 细分场景编码
            upgrade_goods_id: 升级商品ID

        Returns:
            list: merchant_goods_code 列表,按 id 排序
        """
        query_sql = f"""
        SELECT DISTINCT mgi.merchant_goods_code
        FROM dj_car_life_merchant_goods_info mgi
        JOIN dj_car_life_merchant_goods_ref mgr
          ON mgr.merchant_goods_id = mgi.id
         AND mgr.merchant_id = {merchant_id}
        WHERE mgi.upgrade_goods_id = {upgrade_goods_id}
          AND mgi.base_scene_code = '{base_scene_code}'
          AND mgi.merchant_goods_code IS NOT NULL
          AND mgi.merchant_goods_code != ''
        ORDER BY mgi.id, mgi.merchant_goods_code;
        """

        results = self.db.execute_query(query_sql)
        return [row[0] for row in results]

    def _batch_query_merchant_goods_codes(self, query_keys):
        """
        从内存缓存中批量查询商户商品编码(优化版:直接从内存读取)

        Args:
            query_keys: list of (merchant_id, base_scene_code, upgrade_goods_id)

        Returns:
            dict: {(merchant_id, base_scene_code, upgrade_goods_id): [merchant_goods_code, ...]}
        """
        if not query_keys:
            return {}

        # 检查缓存是否已初始化
        if self.goods_code_cache is None:
            raise RuntimeError("商品数据缓存未初始化,请先调用 load_merchant_goods_cache()")

        # 直接从内存查询(O(1) 时间复杂度)
        goods_code_map = {}
        for key in query_keys:
            if key in self.goods_code_cache:
                goods_code_map[key] = self.goods_code_cache[key]

        return goods_code_map

    def _update_original_record(self, relation_id, merchant_goods_code, source_type):
        """更新原记录的 merchant_goods_code"""
        update_sql = f"""
        UPDATE dj_car_life_goods_type_group_relation
        SET merchant_goods_code = '{merchant_goods_code}',
            updated_by = '{DATA_MIGRATION_USER2}',
            updated_date = NOW()
        WHERE id = {relation_id};
        """

        if self.db.execute_update(update_sql):
            # 记录到明细表
            self._log_detail(relation_id, merchant_goods_code, source_type, 'UPDATE_ORIGIN', None)

    def _insert_copy_record(self, relation_id, rule_type, goods_type_group_rule_id,
                           merchant_goods_code, source_type):
        """复制插入新记录"""
        # 先检查是否已存在
        check_sql = f"""
        SELECT COUNT(*) FROM dj_car_life_goods_type_group_relation
        WHERE rule_type = {rule_type}
          AND goods_type_group_rule_id = {goods_type_group_rule_id}
          AND category_type = 2
          AND merchant_goods_code = '{merchant_goods_code}';
        """
        result = self.db.execute_query_one(check_sql)
        if result and result[0] > 0:
            # 已存在,跳过
            self._log_detail(relation_id, merchant_goods_code, source_type, 'SKIP', '已存在相同记录')
            return

        # 复制插入
        insert_sql = f"""
        INSERT INTO dj_car_life_goods_type_group_relation
        (rule_type, goods_type_group_rule_id, category_type, upgrade_goods_id,
         merchant_goods_code, goods_type, goods_type_name, package_code, package_name,
         deleted_flag, created_by, created_date, updated_by, updated_date)
        SELECT
            rule_type, goods_type_group_rule_id, category_type, upgrade_goods_id,
            '{merchant_goods_code}' AS merchant_goods_code,
            goods_type, goods_type_name, package_code, package_name,
            deleted_flag, '{DATA_MIGRATION_USER2}', NOW(), '{DATA_MIGRATION_USER2}', NOW()
        FROM dj_car_life_goods_type_group_relation
        WHERE id = {relation_id};
        """

        if self.db.execute_update(insert_sql):
            self._log_detail(relation_id, merchant_goods_code, source_type, 'INSERT_COPY', None)

    def _log_detail(self, relation_id, merchant_goods_code, source_type, action_type, skip_reason):
        """记录补数明细"""
        # 查询上下文信息
        query_sql = f"""
        SELECT rule_type, goods_type_group_rule_id, upgrade_goods_id,
               merchant_id, scene_type, base_scene_code
        FROM {self.context_table}
        WHERE relation_id = {relation_id}
        LIMIT 1;
        """
        result = self.db.execute_query_one(query_sql)
        if not result:
            return

        rule_type, goods_type_group_rule_id, upgrade_goods_id, \
        merchant_id, scene_type, base_scene_code = result

        skip_reason_str = f"'{skip_reason}'" if skip_reason else 'NULL'

        insert_sql = f"""
        INSERT INTO {self.detail_table}
        (relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
         merchant_id, scene_type, base_scene_code, merchant_goods_code,
         source_type, action_type, skip_reason)
        VALUES ({relation_id}, {rule_type}, {goods_type_group_rule_id}, {upgrade_goods_id},
                {merchant_id}, {scene_type}, '{base_scene_code}', '{merchant_goods_code}',
                '{source_type}', '{action_type}', {skip_reason_str});
        """
        self.db.execute_update(insert_sql)

    def _batch_update_original_records(self, updates):
        """
        批量更新原记录的 merchant_goods_code(优化版:切片CASE WHEN,避免SQL过长)

        Args:
            updates: list of (relation_id, merchant_goods_code)
        """
        if not updates:
            return

        # 分批更新,每次最多1000条(从5000降到1000,避免CASE WHEN过重)
        batch_size = 1000
        for i in range(0, len(updates), batch_size):
            batch = updates[i:i+batch_size]

            # 使用 CASE WHEN 批量更新
            case_when_parts = []
            relation_ids = []
            for relation_id, merchant_goods_code in batch:
                case_when_parts.append(f"WHEN {relation_id} THEN '{merchant_goods_code}'")
                relation_ids.append(str(relation_id))

            case_when_clause = " ".join(case_when_parts)
            ids_clause = ",".join(relation_ids)

            update_sql = f"""
            UPDATE dj_car_life_goods_type_group_relation
            SET merchant_goods_code = CASE id {case_when_clause} END,
                updated_by = '{DATA_MIGRATION_USER2}',
                updated_date = NOW()
            WHERE id IN ({ids_clause});
            """

            self.db.execute_update(update_sql)

    def _batch_insert_copy_records(self, inserts):
        """
        批量复制插入新记录(优化版:先查询后插入,避免500个UNION ALL)

        Args:
            inserts: list of (relation_id, rule_type, goods_type_group_rule_id, merchant_goods_code)
        """
        if not inserts:
            return

        # 先批量检查已存在的记录(使用元组IN)
        check_tuples = [f"({rule_type}, {goods_type_group_rule_id}, '{merchant_goods_code}')"
                        for relation_id, rule_type, goods_type_group_rule_id, merchant_goods_code in inserts]

        existing_set = set()
        batch_size = 1000
        for i in range(0, len(check_tuples), batch_size):
            batch_tuples = check_tuples[i:i+batch_size]
            in_clause = ",".join(batch_tuples)

            check_sql = f"""
            SELECT rule_type, goods_type_group_rule_id, merchant_goods_code
            FROM dj_car_life_goods_type_group_relation
            WHERE category_type = 2
              AND (rule_type, goods_type_group_rule_id, merchant_goods_code) IN ({in_clause});
            """

            existing_results = self.db.execute_query(check_sql)
            for row in existing_results:
                existing_set.add((row[0], row[1], row[2]))

        # 过滤掉已存在的记录
        filtered_inserts = []
        for relation_id, rule_type, goods_type_group_rule_id, merchant_goods_code in inserts:
            if (rule_type, goods_type_group_rule_id, merchant_goods_code) not in existing_set:
                filtered_inserts.append((relation_id, rule_type, goods_type_group_rule_id, merchant_goods_code))

        if not filtered_inserts:
            return

        # 批量查询原记录数据(使用 id IN)
        # 构建 relation_id 到 merchant_goods_code 列表的映射(一个 relation_id 可能对应多个 merchant_goods_code)
        id_to_codes = {}
        for relation_id, rule_type, goods_type_group_rule_id, merchant_goods_code in filtered_inserts:
            if relation_id not in id_to_codes:
                id_to_codes[relation_id] = []
            id_to_codes[relation_id].append(merchant_goods_code)

        relation_ids = list(id_to_codes.keys())

        # 分批查询,每次500条
        batch_size = 500
        for i in range(0, len(relation_ids), batch_size):
            batch_ids = [str(rid) for rid in relation_ids[i:i+batch_size]]
            ids_clause = ",".join(batch_ids)

            # 查询原记录
            query_sql = f"""
            SELECT id, rule_type, goods_type_group_rule_id, category_type, upgrade_goods_id,
                   goods_type, goods_type_name, package_code, package_name, deleted_flag
            FROM dj_car_life_goods_type_group_relation
            WHERE id IN ({ids_clause});
            """

            original_records = self.db.execute_query(query_sql)

            # 构建 VALUES 子句
            values_parts = []
            for record in original_records:
                original_id, rule_type, goods_type_group_rule_id, category_type, upgrade_goods_id, \
                goods_type, goods_type_name, package_code, package_name, deleted_flag = record

                # 获取对应的所有 merchant_goods_code(一个 relation_id 可能对应多个)
                new_codes = id_to_codes.get(original_id, [])

                # 为每个 merchant_goods_code 生成一条插入记录
                for new_code in new_codes:
                    values_parts.append(f"""(
                        {rule_type}, {goods_type_group_rule_id}, {category_type}, {upgrade_goods_id},
                        '{new_code}', {goods_type if goods_type else 'NULL'},
                        {f"'{goods_type_name}'" if goods_type_name else 'NULL'},
                        {f"'{package_code}'" if package_code else 'NULL'},
                        {f"'{package_name}'" if package_name else 'NULL'},
                        '{deleted_flag}', '{DATA_MIGRATION_USER2}', NOW(), '{DATA_MIGRATION_USER2}', NOW()
                    )""")

            if values_parts:
                # 使用普通的 INSERT INTO ... VALUES
                insert_sql = f"""
                INSERT INTO dj_car_life_goods_type_group_relation
                (rule_type, goods_type_group_rule_id, category_type, upgrade_goods_id,
                 merchant_goods_code, goods_type, goods_type_name, package_code, package_name,
                 deleted_flag, created_by, created_date, updated_by, updated_date)
                VALUES {','.join(values_parts)};
                """
                self.db.execute_update(insert_sql)

    def _batch_log_details(self, details):
        """
        批量记录补数明细

        Args:
            details: list of (relation_id, merchant_goods_code, source_type, action_type, skip_reason,
                             rule_type, goods_type_group_rule_id, upgrade_goods_id,
                             merchant_id, scene_type, base_scene_code)
        """
        if not details:
            return

        values_parts = []
        for detail in details:
            relation_id, merchant_goods_code, source_type, action_type, skip_reason, \
            rule_type, goods_type_group_rule_id, upgrade_goods_id, \
            merchant_id, scene_type, base_scene_code = detail

            skip_reason_str = f"'{skip_reason}'" if skip_reason else 'NULL'

            values_parts.append(f"({relation_id}, {rule_type}, {goods_type_group_rule_id}, {upgrade_goods_id}, "
                              f"{merchant_id}, {scene_type}, '{base_scene_code}', '{merchant_goods_code}', "
                              f"'{source_type}', '{action_type}', {skip_reason_str})")

        # 分批插入,每次最多1000条
        batch_size = 1000
        for i in range(0, len(values_parts), batch_size):
            batch_values = values_parts[i:i+batch_size]
            values_clause = ",\n".join(batch_values)

            insert_sql = f"""
            INSERT INTO {self.detail_table}
            (relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
             merchant_id, scene_type, base_scene_code, merchant_goods_code,
             source_type, action_type, skip_reason)
            VALUES {values_clause};
            """
            self.db.execute_update(insert_sql)

    def round2_fill_from_order_history(self):
        """
        第二轮补数:从历史订单补下架商品
        注意:第一轮已补的记录,如果订单中还有其他merchant_goods_code,第二轮仍需补充
        批量处理,每批5000条,使用游标分页
        """
        import gc

        self.logger.info("=" * 80)
        self.logger.info("第二轮补数:从历史订单补齐...")

        # 查询总记录数
        count_sql = f"SELECT COUNT(*) FROM {self.context_table};"
        result = self.db.execute_query_one(count_sql)
        total_count = result[0] if result else 0
        self.logger.info(f"共 {total_count} 条记录需要检查订单补齐")

        batch_size = 5000  # 优化:从100000降到5000
        last_id = 0
        batch_num = 0
        total_processed = 0
        total_updated = 0
        total_inserted = 0
        total_skipped = 0

        while True:
            batch_num += 1
            self.logger.info(f"处理批次 {batch_num},已处理 {total_processed}/{total_count} 条")

            # 使用游标分页代替OFFSET
            query_sql = f"""
            SELECT ctx.id, ctx.relation_id, ctx.rule_type, ctx.goods_type_group_rule_id,
                   ctx.upgrade_goods_id, ctx.merchant_id, ctx.scene_type, ctx.base_scene_code,
                   ctx.settle_rule_id, ctx.reconciliation_rule_id
            FROM {self.context_table} ctx
            WHERE ctx.id > {last_id}
            ORDER BY ctx.id
            LIMIT {batch_size};
            """

            contexts = self.db.execute_query(query_sql)
            if not contexts:
                break

            # 记录本批次最大ID
            last_id = contexts[-1][0]

            # 分组:财务规则和对账规则
            finance_keys = set()  # (settle_rule_id, base_scene_code, upgrade_goods_id)
            reconciliation_keys = set()  # (reconciliation_rule_id, base_scene_code, upgrade_goods_id)
            ctx_map = {}  # relation_id -> context

            for ctx in contexts:
                ctx_id, relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id, \
                merchant_id, scene_type, base_scene_code, settle_rule_id, \
                reconciliation_rule_id = ctx

                ctx_map[relation_id] = {
                    'ctx_id': ctx_id,
                    'relation_id': relation_id,
                    'rule_type': rule_type,
                    'goods_type_group_rule_id': goods_type_group_rule_id,
                    'upgrade_goods_id': upgrade_goods_id,
                    'merchant_id': merchant_id,
                    'scene_type': scene_type,
                    'base_scene_code': base_scene_code,
                    'settle_rule_id': settle_rule_id,
                    'reconciliation_rule_id': reconciliation_rule_id
                }

                if rule_type == 1:
                    finance_keys.add((settle_rule_id, base_scene_code, upgrade_goods_id))
                else:
                    reconciliation_keys.add((reconciliation_rule_id, base_scene_code, upgrade_goods_id))

            # 批量查询订单中的 merchant_goods_code
            self.logger.info(f"  批量查询订单商品编码:财务规则 {len(finance_keys)} 组,对账规则 {len(reconciliation_keys)} 组...")
            finance_goods_map = self._batch_query_order_goods_codes_finance(list(finance_keys))
            reconciliation_goods_map = self._batch_query_order_goods_codes_reconciliation(list(reconciliation_keys))

            # 批量查询已存在的 merchant_goods_code(用于去重)
            all_check_keys = set()
            for ctx in ctx_map.values():
                all_check_keys.add((ctx['rule_type'], ctx['goods_type_group_rule_id']))

            self.logger.info(f"  批量查询已存在的商品编码 {len(all_check_keys)} 组...")
            existing_codes_map = self._batch_query_existing_codes(list(all_check_keys))

            # 批量查询原记录是否已有 merchant_goods_code
            relation_ids = list(ctx_map.keys())
            self.logger.info(f"  批量查询原记录状态 {len(relation_ids)} 条...")
            original_codes_map = self._batch_query_original_codes(relation_ids)

            # 准备批量更新和插入的数据
            updates = []
            inserts = []
            details = []
            exceptions = []

            processed = 0
            updated = 0
            inserted = 0
            skipped = 0

            for relation_id, ctx in ctx_map.items():
                # 获取订单中的 merchant_goods_code
                if ctx['rule_type'] == 1:
                    key = (ctx['settle_rule_id'], ctx['base_scene_code'], ctx['upgrade_goods_id'])
                    merchant_goods_codes = finance_goods_map.get(key, [])
                else:
                    key = (ctx['reconciliation_rule_id'], ctx['base_scene_code'], ctx['upgrade_goods_id'])
                    merchant_goods_codes = reconciliation_goods_map.get(key, [])

                if not merchant_goods_codes:
                    # 订单中没有找到,检查第一轮是否已处理
                    first_round_processed = self._check_first_round_processed(relation_id)
                    if not first_round_processed:
                        # 第一轮也没处理,记录异常
                        exceptions.append((relation_id, 'NO_MERCHANT_GOODS_CODE', '两轮补数均未找到匹配的merchant_goods_code'))
                    skipped += 1
                    continue

                # 获取已存在的 merchant_goods_code
                existing_key = (ctx['rule_type'], ctx['goods_type_group_rule_id'])
                existing_codes = existing_codes_map.get(existing_key, set())

                # 获取原记录的 merchant_goods_code
                original_code = original_codes_map.get(relation_id, '')

                # 处理订单中找到的 merchant_goods_code
                for code in merchant_goods_codes:
                    # 检查是否已存在
                    if code in existing_codes:
                        details.append((relation_id, code, 'ORDER_HISTORY', 'SKIP', '已存在相同记录',
                                      ctx['rule_type'], ctx['goods_type_group_rule_id'], ctx['upgrade_goods_id'],
                                      ctx['merchant_id'], ctx['scene_type'], ctx['base_scene_code']))
                        continue

                    # 检查原记录是否已有 merchant_goods_code
                    if not original_code:
                        # 原记录还没有 merchant_goods_code,更新原记录
                        updates.append((relation_id, code))
                        details.append((relation_id, code, 'ORDER_HISTORY', 'UPDATE_ORIGIN', None,
                                      ctx['rule_type'], ctx['goods_type_group_rule_id'], ctx['upgrade_goods_id'],
                                      ctx['merchant_id'], ctx['scene_type'], ctx['base_scene_code']))
                        updated += 1
                        original_code = code  # 更新本地状态
                        existing_codes.add(code)  # 添加到已存在集合
                    else:
                        # 原记录已有 merchant_goods_code,复制插入新记录
                        inserts.append((relation_id, ctx['rule_type'], ctx['goods_type_group_rule_id'], code))
                        details.append((relation_id, code, 'ORDER_HISTORY', 'INSERT_COPY', None,
                                      ctx['rule_type'], ctx['goods_type_group_rule_id'], ctx['upgrade_goods_id'],
                                      ctx['merchant_id'], ctx['scene_type'], ctx['base_scene_code']))
                        inserted += 1
                        existing_codes.add(code)  # 添加到已存在集合

                processed += 1

            # 批量执行更新
            if updates:
                self.logger.info(f"  批量更新 {len(updates)} 条记录...")
                self._batch_update_original_records(updates)

            # 批量执行插入
            if inserts:
                self.logger.info(f"  批量插入 {len(inserts)} 条记录...")
                self._batch_insert_copy_records(inserts)

            # 批量记录明细
            if details:
                self.logger.info(f"  批量记录 {len(details)} 条明细...")
                self._batch_log_details(details)

            # 批量记录异常
            if exceptions:
                self.logger.info(f"  批量记录 {len(exceptions)} 条异常...")
                self._batch_log_exceptions(exceptions)

            self.logger.info(f"  批次完成:处理 {processed} 条,更新 {updated} 条,插入 {inserted} 条,跳过 {skipped} 条")

            total_processed += processed
            total_updated += updated
            total_inserted += inserted
            total_skipped += skipped

            # 内存管理:清理大对象
            del updates, inserts, details, exceptions, ctx_map
            del finance_goods_map, reconciliation_goods_map, existing_codes_map, original_codes_map
            del finance_keys, reconciliation_keys, all_check_keys, relation_ids, contexts

            # 每10批强制垃圾回收
            if batch_num % 10 == 0:
                gc.collect()
                self.logger.info(f"  已完成 {batch_num} 批次,执行垃圾回收")

        self.logger.info(f"第二轮补数完成:总计处理 {total_processed} 条,更新 {total_updated} 条,插入 {total_inserted} 条,跳过 {total_skipped} 条")

    def _check_first_round_processed(self, relation_id):
        """检查第一轮是否已处理"""
        query_sql = f"""
        SELECT COUNT(*) FROM {self.detail_table}
        WHERE relation_id = {relation_id}
          AND action_type IN ('UPDATE_ORIGIN', 'INSERT_COPY');
        """
        result = self.db.execute_query_one(query_sql)
        return result and result[0] > 0

    def _check_merchant_goods_code_exists(self, rule_type, goods_type_group_rule_id, merchant_goods_code):
        """检查指定的 merchant_goods_code 是否已存在"""
        check_sql = f"""
        SELECT COUNT(*) FROM dj_car_life_goods_type_group_relation
        WHERE rule_type = {rule_type}
          AND goods_type_group_rule_id = {goods_type_group_rule_id}
          AND category_type = 2
          AND merchant_goods_code = '{merchant_goods_code}';
        """
        result = self.db.execute_query_one(check_sql)
        return result and result[0] > 0

    def _check_original_has_code(self, relation_id):
        """检查原记录是否已有 merchant_goods_code"""
        query_sql = f"""
        SELECT merchant_goods_code FROM dj_car_life_goods_type_group_relation
        WHERE id = {relation_id};
        """
        result = self.db.execute_query_one(query_sql)
        if result and result[0]:
            code = result[0].strip()
            return code != ''
        return False

    # def _query_order_goods_codes_finance(self, settle_rule_id, division_rule_id,
    #                                     base_scene_code, upgrade_goods_id):
    #     """从订单查询财务规则的商品编码"""
    #     query_sql = f"""
    #     SELECT DISTINCT sub.merchant_goods_code
    #     FROM dj_car_life_goods_order ord
    #     JOIN dj_car_life_goods_sub_order sub
    #       ON sub.order_code = ord.order_code
    #      AND sub.deleted_flag = 'N'
    #      AND sub.upgrade_goods_id = {upgrade_goods_id}
    #      AND sub.merchant_goods_code IS NOT NULL
    #      AND sub.merchant_goods_code != ''
    #     WHERE ord.deleted_flag = 'N'
    #       AND ord.specify_account_rule_id = {settle_rule_id}
    #       AND ord.specify_division_rule_id = {division_rule_id}
    #       AND ord.base_scene_code = '{base_scene_code}'
    #     ORDER BY sub.merchant_goods_code;
    #     """
    #
    #     results = self.db.execute_query(query_sql)
    #     return [row[0] for row in results]

    # def _query_order_goods_codes_reconciliation(self, reconciliation_rule_id,
    #                                            base_scene_code, upgrade_goods_id):
    #     """从订单查询对账规则的商品编码"""
    #     query_sql = f"""
    #     SELECT DISTINCT sub.merchant_goods_code
    #     FROM dj_car_life_goods_order ord
    #     JOIN dj_car_life_goods_sub_order sub
    #       ON sub.order_code = ord.order_code
    #      AND sub.deleted_flag = 'N'
    #      AND sub.upgrade_goods_id = {upgrade_goods_id}
    #      AND sub.merchant_goods_code IS NOT NULL
    #      AND sub.merchant_goods_code != ''
    #     WHERE ord.deleted_flag = 'N'
    #       AND ord.specify_reconciliation_rule_id = {reconciliation_rule_id}
    #       AND ord.base_scene_code = '{base_scene_code}'
    #     ORDER BY sub.merchant_goods_code;
    #     """
    #
    #     results = self.db.execute_query(query_sql)
    #     return [row[0] for row in results]

    def _log_exception(self, relation_id, exception_type, exception_desc):
        """记录异常"""
        insert_sql = f"""
        INSERT INTO {self.exception_table}
        (relation_id, exception_type, exception_desc)
        VALUES ({relation_id}, '{exception_type}', '{exception_desc}');
        """
        self.db.execute_update(insert_sql)

    def _batch_log_exceptions(self, exceptions):
        """
        批量记录异常

        Args:
            exceptions: list of (relation_id, exception_type, exception_desc)
        """
        if not exceptions:
            return

        values_parts = []
        for relation_id, exception_type, exception_desc in exceptions:
            exception_desc_escaped = exception_desc.replace("'", "''")
            values_parts.append(f"({relation_id}, '{exception_type}', '{exception_desc_escaped}')")

        # 分批插入,每次最多1000条
        batch_size = 1000
        for i in range(0, len(values_parts), batch_size):
            batch_values = values_parts[i:i+batch_size]
            values_clause = ",\n".join(batch_values)

            insert_sql = f"""
            INSERT INTO {self.exception_table}
            (relation_id, exception_type, exception_desc)
            VALUES {values_clause};
            """
            self.db.execute_update(insert_sql)

    def _batch_query_order_goods_codes_finance(self, query_keys):
        """
        从内存缓存中批量查询财务规则的订单商品编码(优化版:直接从内存读取)

        Args:
            query_keys: list of (settle_rule_id, base_scene_code, upgrade_goods_id)

        Returns:
            dict: {(settle_rule_id, base_scene_code, upgrade_goods_id): [merchant_goods_code, ...]}
        """
        if not query_keys:
            return {}

        # 检查缓存是否已初始化
        if self.order_finance_cache is None:
            raise RuntimeError("订单财务规则缓存未初始化,请先调用 load_order_cache()")

        # 直接从内存查询(O(1) 时间复杂度)
        goods_code_map = {}
        for key in query_keys:
            if key in self.order_finance_cache:
                goods_code_map[key] = self.order_finance_cache[key]

        return goods_code_map

    def _batch_query_order_goods_codes_reconciliation(self, query_keys):
        """
        从内存缓存中批量查询对账规则的订单商品编码(优化版:直接从内存读取)

        Args:
            query_keys: list of (reconciliation_rule_id, base_scene_code, upgrade_goods_id)

        Returns:
            dict: {(reconciliation_rule_id, base_scene_code, upgrade_goods_id): [merchant_goods_code, ...]}
        """
        if not query_keys:
            return {}

        # 检查缓存是否已初始化
        if self.order_reconciliation_cache is None:
            raise RuntimeError("订单对账规则缓存未初始化,请先调用 load_order_cache()")

        # 直接从内存查询(O(1) 时间复杂度)
        goods_code_map = {}
        for key in query_keys:
            if key in self.order_reconciliation_cache:
                goods_code_map[key] = self.order_reconciliation_cache[key]

        return goods_code_map

    def _batch_query_existing_codes(self, check_keys):
        """
        批量查询已存在的 merchant_goods_code(优化版:使用元组IN代替OR拼接)

        Args:
            check_keys: list of (rule_type, goods_type_group_rule_id)

        Returns:
            dict: {(rule_type, goods_type_group_rule_id): set(merchant_goods_code, ...)}
        """
        if not check_keys:
            return {}

        # 构建元组IN: ((1, 100), (3, 200), ...)
        values = [f"({rule_type}, {goods_type_group_rule_id})"
                  for rule_type, goods_type_group_rule_id in check_keys]

        # 分批查询,每次1000条,避免IN列表过长
        existing_map = {}
        batch_size = 1000
        for i in range(0, len(values), batch_size):
            batch_values = values[i:i+batch_size]
            in_clause = ",".join(batch_values)

            query_sql = f"""
            SELECT rule_type, goods_type_group_rule_id, merchant_goods_code
            FROM dj_car_life_goods_type_group_relation
            WHERE category_type = 2
              AND merchant_goods_code IS NOT NULL
              AND merchant_goods_code != ''
              AND (rule_type, goods_type_group_rule_id) IN ({in_clause});
            """

            results = self.db.execute_query(query_sql)

            # 组织结果
            for row in results:
                rule_type, goods_type_group_rule_id, merchant_goods_code = row
                key = (rule_type, goods_type_group_rule_id)
                if key not in existing_map:
                    existing_map[key] = set()
                existing_map[key].add(merchant_goods_code)

        return existing_map

    def _batch_query_original_codes(self, relation_ids):
        """
        批量查询原记录的 merchant_goods_code

        Args:
            relation_ids: list of relation_id

        Returns:
            dict: {relation_id: merchant_goods_code}
        """
        if not relation_ids:
            return {}

        ids_clause = ",".join([str(rid) for rid in relation_ids])

        query_sql = f"""
        SELECT id, merchant_goods_code
        FROM dj_car_life_goods_type_group_relation
        WHERE id IN ({ids_clause});
        """

        results = self.db.execute_query(query_sql)

        # 组织结果
        original_map = {}
        for row in results:
            relation_id, merchant_goods_code = row
            code = merchant_goods_code.strip() if merchant_goods_code else ''
            original_map[relation_id] = code

        return original_map

    def validate_results(self):
        """验证补数结果"""
        self.logger.info("=" * 80)
        self.logger.info("验证补数结果...")

        # 1. 仍未补齐的记录
        query_sql = """
        SELECT rule_type, COUNT(*) as cnt
        FROM dj_car_life_goods_type_group_relation
        WHERE category_type = 2
          AND upgrade_goods_id IS NOT NULL
          AND (merchant_goods_code IS NULL OR merchant_goods_code = '')
        GROUP BY rule_type;
        """
        results = self.db.execute_query(query_sql)
        if results:
            self.logger.warning("仍未补齐的记录:")
            for row in results:
                self.logger.warning(f"  rule_type={row[0]}: {row[1]} 条")
        else:
            self.logger.info("所有记录已补齐")

        # 2. 同一规则分组下重复商品编码
        query_sql = """
        SELECT rule_type, goods_type_group_rule_id, merchant_goods_code, COUNT(*) as cnt
        FROM dj_car_life_goods_type_group_relation
        WHERE category_type = 2
          AND merchant_goods_code IS NOT NULL
          AND merchant_goods_code != ''
        GROUP BY rule_type, goods_type_group_rule_id, merchant_goods_code
        HAVING COUNT(*) > 1;
        """
        results = self.db.execute_query(query_sql)
        if results:
            self.logger.warning(f"发现 {len(results)} 组重复商品编码")
        else:
            self.logger.info("未发现重复商品编码")

        # 3. 统计补数明细
        query_sql = f"""
        SELECT source_type, action_type, COUNT(*) as cnt
        FROM {self.detail_table}
        GROUP BY source_type, action_type
        ORDER BY source_type, action_type;
        """
        results = self.db.execute_query(query_sql)
        if results:
            self.logger.info("补数明细统计:")
            for row in results:
                self.logger.info(f"  {row[0]} - {row[1]}: {row[2]} 条")

        # 4. 统计异常
        query_sql = f"""
        SELECT exception_type, COUNT(*) as cnt
        FROM {self.exception_table}
        GROUP BY exception_type;
        """
        results = self.db.execute_query(query_sql)
        if results:
            self.logger.warning("异常统计:")
            for row in results:
                self.logger.warning(f"  {row[0]}: {row[1]} 条")

    def export_exception_report(self, output_file='merchant_goods_code_exceptions.csv'):
        """导出异常报告"""
        self.logger.info(f"导出异常报告到 {output_file}...")

        query_sql = f"""
        SELECT
            exc.relation_id,
            gtgr.rule_type,
            gtgr.goods_type_group_rule_id,
            gtgr.upgrade_goods_id,
            exc.exception_type,
            exc.exception_desc,
            exc.created_date
        FROM {self.exception_table} exc
        JOIN dj_car_life_goods_type_group_relation gtgr
          ON gtgr.id = exc.relation_id
        ORDER BY exc.id;
        """

        results = self.db.execute_query(query_sql)

        if not results:
            self.logger.info("没有异常记录")
            return

        import csv
        with open(output_file, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)
            writer.writerow(['relation_id', 'rule_type', 'goods_type_group_rule_id',
                           'upgrade_goods_id', 'exception_type', 'exception_desc', 'created_date'])
            writer.writerows(results)

        self.logger.info(f"异常报告已导出,共 {len(results)} 条")