device_detail_processor.py 60.8 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
import random
import pandas as pd
from sqlalchemy import create_engine, text
import datetime
import numpy as np
import os
import sys
import yaml
import warnings

import calendar

# 加载配置文件
def load_config():
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    config_path = os.path.join(base_dir, "config.yaml")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
    except Exception as e:
        print(f"Error loading config: {e}")
        return {}

config = load_config()

def get_db_engine_config(db_key):
    """从 config.yaml 获取数据库配置"""
    db_config = config.get("database", {}).get(db_key)
    if not db_config:
        raise ValueError(f"Database config for '{db_key}' not found in config.yaml")
    
    connection_str = (
        f"mysql+pymysql://{db_config['user']}:{db_config['password']}@"
        f"{db_config['host']}:{db_config['port']}/{db_config['db_name']}?"
        f"charset={db_config['charset']}"
    )
    return connection_str

def get_relative_path(absolute_path):
    """将绝对路径转换为相对于项目根目录的相对路径"""
    if not absolute_path:
        return ""
    # 项目根目录为 project 的上一级
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    try:
        rel_path = os.relpath(absolute_path, base_dir)
        # 统一使用 / 作为 SQL 拼接中的路径分隔符,确保在不同系统下生成一致的 from_table 字段
        rel_path = rel_path.replace('\\', '/')
        # 如果是 ".",返回空字符串
        if rel_path == '.':
            rel_path = ''
        return rel_path
    except:
        return absolute_path

# 获取报表生成配置
report_conf = config.get("report_generation", {})
excel_conf = report_conf.get("excel", {})
table_conf = report_conf.get("tables", {})
field_conf = report_conf.get("fields", {})
sheet_conf = report_conf.get("sheets", {})

# 设置常量 (优先从配置读取,若无则使用默认值或 None)
# FILE_PATH 现已不再强制需要,界面会通过 batch_path 传递
FILE_PATH = excel_conf.get("file_path")
INPUT_EXECL_NAME_01 = excel_conf.get("input_name_01", "拆分数据-E盾明细.xlsx")
INPUT_EXECL_NAME_02 = excel_conf.get("input_name_02", "拆分数据-渠道柳云飞.xlsx")

SHEETS_01 = sheet_conf.get("sheets_01", [])
SHEETS_02 = sheet_conf.get("sheets_02", [])

# 数据库表名常量
DEVICE_DETAILS_TABLE = table_conf.get("device_details", "d_eshield_device_details_2025")
SERVICE_DETAILS_TABLE = table_conf.get("service_details", "d_eshield_service_details_2025")
RERUN_CONF_TABLE = table_conf.get("rerun_conf", "d_rerun_conf")
ALL_DETAILS_TABLE = table_conf.get("all_details", "d_eshield_all_details_2025_detail")
ALL_TMP_TABLE = "d_es_all_tmp"

# MIN_TIME 和 MAX_TIME 现由 batch_name 动态计算,不再使用全局常量

HUITONG_TABLE = table_conf.get("huitong")
XUFEI_TABLE = table_conf.get("xufei")
CHANNEL_TABLE = table_conf.get("channel")
QR_TABLE = table_conf.get("qr")
LYF_TABLE = table_conf.get("lyf")

HUITONG_FIELDS = field_conf.get("huitong", [])
XUFEI_FIELDS = field_conf.get("xufei", [])
CHANNEL_FIELDS = field_conf.get("channel", [])
QR_FIELDS = field_conf.get("qr", [])
LYF_FIELDS = field_conf.get("lyf", [])

# 重跑标志位由 process_device_details 的参数决定,默认从 config 读取
IS_RERUN_DEFAULT = report_conf.get("rerun", {}).get("is_rerun", False)

warnings.filterwarnings('ignore')


def to_sql_native(df, table_name, engine, if_exists='append'):
    """
    使用原生 SQLAlchemy 方式替代 pandas.to_sql,避免兼容性问题
    """
    if df is None or df.empty:
        print(f"跳过表 {table_name} 的写入:数据为空")
        return

    print(f"开始写入表 {table_name} (模式: {if_exists}, 数据量: {len(df)} 行)...")
    print(f"数据样本 (前2行):\n{df.head(2).to_string()}")

    # 处理 if_exists
    if if_exists == 'replace':
        print(f"正在重置表结构: {table_name}")
        with engine.begin() as con:
            con.execute(text(f"DROP TABLE IF EXISTS {table_name}"))
        # 仍然使用 pandas 创建表结构,但只创建不插入数据 (head(0))
        with engine.connect() as con:
            df.head(0).to_sql(name=table_name, con=con, if_exists='replace', index=False)
    
    # 原生批量插入
    cols = ", ".join([f"`{c}`" for c in df.columns])
    placeholders = ", ".join([f":{c}" for c in df.columns])
    insert_sql = f"INSERT INTO {table_name} ({cols}) VALUES ({placeholders})"
    
    # 转换为字典列表
    data = df.to_dict(orient='records')
    
    # 修复:将 NaN 转换为 None
    for row in data:
        for k, v in row.items():
            if pd.isna(v):
                row[k] = None
    
    # 分批执行插入
    chunk_size = 1000
    total_chunks = (len(data) + chunk_size - 1) // chunk_size
    for i in range(0, len(data), chunk_size):
        chunk = data[i:i + chunk_size]
        chunk_idx = i // chunk_size + 1
        with engine.begin() as con:
            con.execute(text(insert_sql), chunk)
        if total_chunks > 1:
            print(f"表 {table_name} 进度: {chunk_idx}/{total_chunks} 批次已写入...")

    # 验证写入结果
    try:
        with engine.connect() as con:
            result = con.execute(text(f"SELECT COUNT(*) FROM {table_name}"))
            db_count = result.scalar()
            print(f"✅ 表 {table_name} 写入完成,当前数据库中总行数为: {db_count}")
            if if_exists == 'replace' and db_count != len(df):
                print(f"⚠️ 警告:写入行数 ({len(df)}) 与数据库总行数 ({db_count}) 不一致!")
    except Exception as e:
        print(f"⚠️ 无法验证写入结果: {e}")

def ensure_table_exists_with_year(engine, base_table_name, target_year):
    """
    检查表名中的年份是否与目标年份一致。
    如果不一致,则创建一个对应年份的新表(如果不存在)。
    返回正确的表名。
    """
    if not base_table_name:
        return base_table_name
        
    import re
    # 查找表名中的 4 位年份 (匹配 202x 或 203x)
    year_match = re.search(r'20[2-3]\d', base_table_name)
    if not year_match:
        return base_table_name # 如果没带年份,直接返回
        
    source_year = year_match.group()
    target_year_str = str(target_year)
    
    if source_year == target_year_str:
        return base_table_name
        
    # 构造新表名
    new_table_name = base_table_name.replace(source_year, target_year_str)
    
    with engine.connect() as con:
        # 检查新表是否存在
        check_sql = text(f"SHOW TABLES LIKE '{new_table_name}'")
        exists = con.execute(check_sql).fetchone()
        
        if not exists:
            # 检查源表是否存在
            check_source_sql = text(f"SHOW TABLES LIKE '{base_table_name}'")
            source_exists = con.execute(check_source_sql).fetchone()
            
            if source_exists:
                print(f"📢 检测到跨年数据,正在创建新年份表: {new_table_name} (基于 {base_table_name})")
                con.execute(text(f"CREATE TABLE `{new_table_name}` LIKE `{base_table_name}`"))
                con.commit()
            else:
                print(f"⚠️ 警告: 源表 {base_table_name} 不存在,无法通过 LIKE 方式创建新表 {new_table_name}")
                
    return new_table_name

def update_global_tables_by_year(engine, year):
    """
    根据目标年份动态更新所有带年份的全局表名变量。
    """
    global DEVICE_DETAILS_TABLE, SERVICE_DETAILS_TABLE, ALL_DETAILS_TABLE
    global HUITONG_TABLE, XUFEI_TABLE, CHANNEL_TABLE, QR_TABLE, LYF_TABLE
    
    DEVICE_DETAILS_TABLE = ensure_table_exists_with_year(engine, DEVICE_DETAILS_TABLE, year)
    SERVICE_DETAILS_TABLE = ensure_table_exists_with_year(engine, SERVICE_DETAILS_TABLE, year)
    ALL_DETAILS_TABLE = ensure_table_exists_with_year(engine, ALL_DETAILS_TABLE, year)
    
    # 原始表通常不带年份,但如果带了,也一并处理
    HUITONG_TABLE = ensure_table_exists_with_year(engine, HUITONG_TABLE, year)
    XUFEI_TABLE = ensure_table_exists_with_year(engine, XUFEI_TABLE, year)
    CHANNEL_TABLE = ensure_table_exists_with_year(engine, CHANNEL_TABLE, year)
    QR_TABLE = ensure_table_exists_with_year(engine, QR_TABLE, year)
    LYF_TABLE = ensure_table_exists_with_year(engine, LYF_TABLE, year)
    
    print(f"📂 已根据年份 {year} 调整表名:")
    print(f"   - 设备明细: {DEVICE_DETAILS_TABLE}")
    print(f"   - 服务明细: {SERVICE_DETAILS_TABLE}")
    print(f"   - 汇总表: {ALL_DETAILS_TABLE}")


# def date_format(df):
#     # 将settle_time列的数据类型转换为datetime类型
#     df = pd.to_datetime(df, format='%Y%m')
#     # 使用strftime()方法将日期类型的数据格式化为MySQL中的date格式
#     df = df.apply(lambda x: x.strftime('%Y-%m-%d'))
#     return df

def date_format(df):
    """
    增强日期格式兼容性:支持 YYYYMM 等多种格式,解析失败时直接报错
    """
    if df is None or len(df) == 0:
        return df
        
    # 转换为 Series 方便处理
    s = pd.Series(df)
    
    # 特殊处理:如果已经是 datetime 类型,直接格式化
    if pd.api.types.is_datetime64_any_dtype(s):
        return s.dt.strftime('%Y-%m-%d').fillna('')

    # 转换为字符串并清理
    # 1. 处理 float 转换产生的 .0
    s = s.astype(str).str.replace(r'\.0$', '', regex=True).str.strip()
    
    # 2. 处理异常格式:如 2025010 应为 202510 (7位数字,中间多了一个0)
    # 匹配规则:4位年份 + 0 + 2位月份
    s = s.str.replace(r'^(\d{4})0(\d{2})$', r'\1\2', regex=True)
    
    # 过滤掉明显的空值
    mask = (s != 'nan') & (s != 'None') & (s != '') & (s.notna())
    if not mask.any():
        return pd.Series([''] * len(df))

    # 定义尝试匹配的格式列表
    # 优先匹配带时间的格式,然后是带分隔符的格式,最后是紧凑格式
    # 注意:%Y%m 应该在 %Y%m%d 之前,防止 6 位数字被误匹配为 YYYY-M-D
    formats = [
        '%Y-%m-%d %H:%M:%S', '%Y/%m/%d %H:%M:%S', 
        '%Y-%m-%d', '%Y/%m/%d', '%Y.%m.%d', 
        '%Y%m', '%Y%m%d', '%Y.%m'
    ]
    
    # 初始化结果为 NaT
    result = pd.to_datetime(pd.Series([np.nan] * len(df)), errors='coerce')
    
    # 循环尝试格式
    remaining_mask = mask.copy()
    for fmt in formats:
        if not remaining_mask.any():
            break
            
        # 尝试转换当前剩余未成功的行
        # 使用 format=fmt 强制按指定格式解析,避免 pd.to_datetime 自动猜测导致 1970 年问题
        converted = pd.to_datetime(s[remaining_mask], format=fmt, errors='coerce')
        
        # 更新成功转换的结果
        success_mask = converted.notna()
        if success_mask.any():
            # 获取成功转换的数据在原始 Series 中的真实索引
            idx = converted[success_mask].index
            result.loc[idx] = converted[success_mask]
            # 更新剩余需要转换的掩码
            remaining_mask.loc[idx] = False

    # 检查是否仍有无法解析的非空数据
    failed_mask = mask & result.isna()
    if failed_mask.any():
        failed_samples = s[failed_mask].unique()[:3]
        raise ValueError(f"日期格式解析失败!无法识别的值: {failed_samples}。请检查 Excel 中的日期格式是否正确(支持 YYYYMM, YYYY-MM-DD 等)。")
    
    # 统一格式化为 MySQL 兼容的 YYYY-MM-DD 字符串
    return result.dt.strftime('%Y-%m-%d').fillna('')

# 将表中数据清空,按照结算时间(预留方法)
def delete_pre_data(min_settle_time, max_settle_time, settle_time_field, table_name, engine):
    delete_sql = f"delete from {table_name} where {settle_time_field} >= '{min_settle_time}' and {settle_time_field} <= '{max_settle_time}'"
    print("当前执行的删除sql为:" + delete_sql)
    with engine.begin() as con:
        con.execute(text(delete_sql))

def fill_huitong_sheet(engine, out_put_table_01, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(1, 15, "正在导入汇通安装结算汇总数据...")
    current_path = base_path if base_path else FILE_PATH
    file_path = os.path.join(current_path, INPUT_EXECL_NAME_01)
    sheet_name = SHEETS_01[0]
    if not os.path.exists(file_path):
        print(f"警告:文件不存在 {file_path}")
        return 0
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name)
    except Exception as e:
        print(f"警告:读取 {file_path} [{sheet_name}] 出错: {e}")
        return 0

    if progress_callback: progress_callback(1, 15, f"正在导入汇通安装结算汇总数据... (读取到 {len(df)} 行)")
    df.columns = HUITONG_FIELDS
    df['settlement_time'] = date_format(df['settlement_time'])
    df['financial_time'] = date_format(df['financial_time'])

    delete_sql = f"delete from {out_put_table_01} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
    print("当前执行的删除sql为:" + delete_sql)
    with engine.begin() as con:
        con.execute(text(delete_sql))

    to_sql_native(df, out_put_table_01, engine, if_exists="append")
    return len(df)

def fill_xufei_sheet(engine, out_put_table_01, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(2, 15, "正在导入续费结算汇总数据...")
    current_path = base_path if base_path else FILE_PATH
    file_path = os.path.join(current_path, INPUT_EXECL_NAME_01)
    sheet_name = SHEETS_01[1]
    if not os.path.exists(file_path):
        print(f"警告:文件不存在 {file_path}")
        return 0
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name)
    except Exception as e:
        print(f"警告:读取 {file_path} [{sheet_name}] 出错: {e}")
        return 0

    if progress_callback: progress_callback(2, 15, f"正在导入续费结算汇总数据... (读取到 {len(df)} 行)")
    df.columns = XUFEI_FIELDS
    df['renewal_time'] = date_format(df['renewal_time'])
    df['financial_time'] = date_format(df['financial_time'])

    delete_sql = f"delete from {out_put_table_01} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
    print("当前执行的删除sql为:" + delete_sql)
    with engine.begin() as con:
        con.execute(text(delete_sql))
    to_sql_native(df, out_put_table_01, engine, if_exists="append")
    return len(df)

def fill_channel_sheet(engine, out_put_table_01, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(3, 15, "正在导入渠道应收单数据...")
    current_path = base_path if base_path else FILE_PATH
    file_path = os.path.join(current_path, INPUT_EXECL_NAME_01)
    sheet_name = SHEETS_01[2]
    if not os.path.exists(file_path):
        print(f"警告:文件不存在 {file_path}")
        return 0
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name)
    except Exception as e:
        print(f"警告:读取 {file_path} [{sheet_name}] 出错: {e}")
        return 0

    if progress_callback: progress_callback(3, 15, f"正在导入渠道应收单数据... (读取到 {len(df)} 行)")
    print(df)
    df.columns = CHANNEL_FIELDS
    df['business_date'] = date_format(df['business_date'])
    delete_sql = f"delete from {out_put_table_01} where business_date >= '{min_time}' and business_date <='{max_time}'"
    print("当前执行的删除sql为:" + delete_sql)
    with engine.begin() as con:
        con.execute(text(delete_sql))
    to_sql_native(df, out_put_table_01, engine, if_exists="append")
    return len(df)

def fill_qr_sheet(engine, out_put_table_01, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(4, 15, "正在导入趣融结算明细数据...")
    current_path = base_path if base_path else FILE_PATH
    file_path = os.path.join(current_path, INPUT_EXECL_NAME_01)
    sheet_name = SHEETS_01[3]
    if not os.path.exists(file_path):
        print(f"警告:文件不存在 {file_path}")
        return 0
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name)
    except Exception as e:
        print(f"警告:读取 {file_path} [{sheet_name}] 出错: {e}")
        return 0

    if progress_callback: progress_callback(4, 15, f"正在导入趣融结算明细数据... (读取到 {len(df)} 行)")
    df.columns = QR_FIELDS
    df['financial_time'] = date_format(df['financial_time'])

    delete_sql = f"delete from {out_put_table_01} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
    print("当前执行的删除sql为:" + delete_sql)
    with engine.begin() as con:
        con.execute(text(delete_sql))
    to_sql_native(df, out_put_table_01, engine, if_exists="append")
    return len(df)

def fill_lyf_sheet(engine, out_put_table_01, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(5, 15, "正在导入其它渠道结算明细数据...")
    current_path = base_path if base_path else FILE_PATH
    file_path = os.path.join(current_path, INPUT_EXECL_NAME_02)
    sheet_name = SHEETS_02[0]
    if not os.path.exists(file_path):
        print(f"警告:文件不存在 {file_path}")
        return 0
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name)
    except Exception as e:
        print(f"警告:读取 {file_path} [{sheet_name}] 出错: {e}")
        return 0

    if progress_callback: progress_callback(5, 15, f"正在导入其它渠道结算明细数据... (读取到 {len(df)} 行)")
    df.columns = LYF_FIELDS
    df['business_date'] = date_format(df['business_date'])

    delete_sql = f"delete from {out_put_table_01} where business_date >= '{min_time}' and business_date <='{max_time}'"
    print("当前执行的删除sql为:" + delete_sql)
    with engine.begin() as con:
        con.execute(text(delete_sql))
    to_sql_native(df, out_put_table_01, engine, if_exists="append")
    return len(df)


# 预留方法
def validate_total_data(engine):
    # 从MySQL中读取d_es_huitong_raw_data表的数据
    with engine.connect() as con:
        df1 = pd.read_sql(text('select * from d_es_huitong_raw_data'), con=con)
        # 从MySQL中读取d_es_xufei_raw_data表的数据
        df2 = pd.read_sql(text('select * from d_es_xufei_raw_data'), con=con)
        df3 = pd.read_sql(text('select * from d_es_channel_raw_data'), con=con)
        df4 = pd.read_sql(text('select * from d_es_qr_raw_data'), con=con)
        df5 = pd.read_sql(text('select * from d_es_lyf_raw_data'), con=con)

    df1_total = pd.DataFrame({'d_es_huitong_raw_data': [df1['hardware_without_tax'].sum()] + df1[
        'installation_unit_price_without_tax'] + df1['service_fee_without_tax']})
    df2_total = pd.DataFrame({'d_es_xufei_raw_data': [df2['service_fee_without_tax'].sum()]})
    df3_total = pd.DataFrame({'d_es_channel_raw_data': [df3['service_fee_without_tax'].sum()]})

    # 按照settle_merchant分组计算d_es_huitong_raw_data表的price和num,并将结果转换为DataFrame
    df1_grouped = df1.groupby('settle_merchant')['price', 'num'].sum().reset_index()
    # 按照settle_merchant分组计算d_es_xufei_raw_data表的price和num,并将结果转换为DataFrame
    df2_grouped = df2.groupby('settle_merchant')['price', 'num'].sum().reset_index()

    # 创建Excel文件
    writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter')

    # 将df1_total和df2_total写入第一个sheet
    df_total = pd.concat([df1_total, df2_total], axis=1)
    df_total.to_excel(writer, sheet_name='Total Price', index=False)

    # 将df1_grouped写入第二个sheet
    df1_grouped.to_excel(writer, sheet_name='d_es_huitong_raw_data', index=False)

    # 将df2_grouped写入第三个sheet
    df2_grouped.to_excel(writer, sheet_name='d_es_xufei_raw_data', index=False)

    # 保存Excel文件并关闭writer
    writer.save()
    writer.close()

# 汇通
def chaifen_huitong(engine, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(6, 15, "正在从数据库读取汇通原始数据进行拆分...")
    # 这里 base_path 已经是 get_relative_path 处理过的相对路径
    current_path = base_path if base_path else ""
    try:
        sql = f"SELECT *, '{current_path}{SHEETS_01[0]}' as from_table, '1' as from_type, cast(REPLACE(service_term, '期', '') as unsigned) as service_period FROM {HUITONG_TABLE} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
        # sql = f"SELECT *, 'test' as from_table, '1' as from_type, cast(REPLACE(service_term, '期', '') as unsigned) as service_period FROM {HUITONG_TABLE} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
        with engine.connect() as con:
            df = pd.read_sql(text(sql), con=con)
    except Exception as e:
        print(f"警告:从数据库读取 {HUITONG_TABLE} 出错 (可能表不存在): {e}")
        return pd.DataFrame()
    
    new_rows=[]
    for index, row in df.iterrows():
            new_rows.extend(huitong_process_row(row))

    if not new_rows:
        return pd.DataFrame()

    # 创建新的数据框
    new_df = pd.DataFrame(new_rows)
    if progress_callback: progress_callback(6, 15, f"正在拆分汇通数据... (已拆分为 {len(new_df)} 条 SN 明细)")
    new_df = new_df[['sn','service_period','K3_hardware_settlement_customer','receivable_number_hardware','financial_time','hardware_without_tax','installation_unit_price_without_tax','service_fee_without_tax','from_type','from_table']]
    new_df = new_df.rename(columns={'K3_hardware_settlement_customer': 'settle_merchant', 'receivable_number_hardware': 'settle_order', 'financial_time': 'settle_time','hardware_without_tax':'device_price','installation_unit_price_without_tax':'install_price','service_fee_without_tax':'service_price'})

    # 将结果写入 MySQL 数据库中的新表
    to_sql_native(new_df, HUITONG_TABLE + '_tmp', engine, if_exists='replace')
    return new_df

def huitong_process_row(row):
    sn_columns = ['main_device_number', 'sub_device_number_1',
                  'sub_device_number_2', 'sub_device_number_3']
    sn_values = row[sn_columns]
    not_empty_count = sn_values.apply(lambda x: pd.notnull(x) and x != '0' and x != '').sum()

    if not_empty_count == 0:
        return []

    new_rows = []
    for sn in sn_values:
        if pd.notnull(sn) and sn != '0' and sn != '':
            new_row = row.copy()
            new_row['sn'] = sn
            new_row['hardware_without_tax'] /= not_empty_count
            new_row['installation_unit_price_without_tax'] /= not_empty_count
            new_row['service_fee_without_tax'] /= not_empty_count
            new_rows.append(new_row)

    return new_rows

# 续费
def chaifen_xufei(engine, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(7, 15, "正在从数据库读取续费原始数据进行拆分...")
    # 这里 base_path 已经是 get_relative_path 处理过的相对路径
    current_path = base_path if base_path else ""
    try:
        sql = f"SELECT *, '{current_path}{SHEETS_01[1]}' as from_table, '4' as from_type, '0' as hardware_without_tax, '0' as installation_unit_price_without_tax, cast(service_term as unsigned) as service_period FROM {XUFEI_TABLE} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
        with engine.connect() as con:
            df = pd.read_sql(text(sql), con=con)
    except Exception as e:
        print(f"警告:从数据库读取 {XUFEI_TABLE} 出错 (可能表不存在): {e}")
        return pd.DataFrame()

    new_rows=[]
    for index, row in df.iterrows():
        new_rows.extend(xufei_process_row(row))

    if not new_rows:
        return pd.DataFrame()

    # 创建新的数据框
    new_df = pd.DataFrame(new_rows)
    if progress_callback: progress_callback(7, 15, f"正在拆分续费数据... (已拆分为 {len(new_df)} 条 SN 明细)")
    # 'sn','K3_settlement_customer','receivable_number_hardware','settlement_time','hardware_without_tax','installation_unit_price_without_tax','service_fee_without_tax','from_type','from_table'
    new_df = new_df[['sn','service_period','K3_settlement_customer','receivable_number','financial_time','hardware_without_tax','installation_unit_price_without_tax','service_fee_without_tax','from_type','from_table']]
    new_df = new_df.rename(columns={'K3_settlement_customer': 'settle_merchant', 'receivable_number': 'settle_order', 'financial_time': 'settle_time','hardware_without_tax':'device_price','installation_unit_price_without_tax':'install_price','service_fee_without_tax':'service_price'})

    # 将结果写入 MySQL 数据库中的新表
    to_sql_native(new_df, XUFEI_TABLE + '_tmp', engine, if_exists='replace')
    return new_df

def xufei_process_row(row):
    sn_columns = ['main_device_number', 'sub_device_number_1',
                  'sub_device_number_2']
    sn_values = row[sn_columns]
    not_empty_count = sn_values.apply(lambda x: pd.notnull(x) and x != '0' and x != '').sum()

    if not_empty_count == 0:
        return []

    new_rows = []
    for sn in sn_values:
        if pd.notnull(sn) and sn != '0' and sn != '':
            new_row = row.copy()
            new_row['sn'] = sn
            new_row['service_fee_without_tax'] /= not_empty_count
            new_rows.append(new_row)

    return new_rows

# 渠道
def chaifen_channel(engine, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(8, 15, "正在从数据库读取渠道原始数据进行拆分...")
    # 这里 base_path 已经是 get_relative_path 处理过的相对路径
    current_path = base_path if base_path else ""
    try:
        sql = f"SELECT *, '{current_path}{SHEETS_01[2]}' as from_table, '2' as from_type, '' as sn, cast(amortization_term as unsigned) as service_period FROM {CHANNEL_TABLE} where product_type ='硬件' and business_type like '%%SAAS系统订阅服务—智慧车管线索订阅%%' and business_date >= '{min_time}' and business_date <='{max_time}'"
        with engine.connect() as con:
            df = pd.read_sql(text(sql), con=con)
    except Exception as e:
        print(f"警告:从数据库读取 {CHANNEL_TABLE} 出错 (可能表不存在): {e}")
        return pd.DataFrame()
    
    new_df = channel_process_row(df)
    if new_df.empty:
        return pd.DataFrame()
        
    if progress_callback: progress_callback(8, 15, f"正在拆分渠道数据... (已拆分为 {len(new_df)} 条明细)")
    # 将结果写入 MySQL 数据库中的新表
    to_sql_native(new_df, CHANNEL_TABLE + '_tmp', engine, if_exists='replace')
    return new_df

def channel_process_row(df):
    if df.empty:
        return pd.DataFrame()
        
    # 修复:先处理 NaN 并转换为数值类型,再取绝对值
    df['financial_quantity'] = pd.to_numeric(df['financial_quantity'], errors='coerce').fillna(0).apply(abs)

    # 将每条数据拆分成 financial_quantity 条数据
    rows_list = []
    for index, row in df.iterrows():
        # 转换为整数进行循环
        count = int(row['financial_quantity'])
        for i in range(count):
            rows_list.append({'sn': row['sn'],
                                    'service_period': row['amortization_term'],
                                    'settle_merchant': row['customer'],
                                    'settle_order': row['bill_number'],
                                    'settle_time': row['business_date'],
                                    'device_price': row['hardware'],
                                    'install_price': row['installation'],
                                    'service_price': row['service_without_tax'],
                                    # 'device_cost': row['cost_amount']/row['financial_quantity'],
                                    'from_type': row['from_type'],
                                    'from_table': row['from_table']})

    return pd.DataFrame(rows_list)

# 趣融
def chaifen_qr(engine, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(9, 15, "正在从数据库读取趣融原始数据进行拆分...")
    # 这里 base_path 已经是 get_relative_path 处理过的相对路径
    current_path = base_path if base_path else ""
    try:
        sql = f"SELECT *, '{current_path}{SHEETS_01[3]}' as from_table, '1' as from_type, cast(service_term as unsigned) as service_period FROM {QR_TABLE} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
        with engine.connect() as con:
            df = pd.read_sql(text(sql), con=con)
    except Exception as e:
        print(f"警告:从数据库读取 {QR_TABLE} 出错 (可能表不存在): {e}")
        return pd.DataFrame()

    new_rows=[]
    for index, row in df.iterrows():
        new_rows.extend(qr_process_row(row))

    if not new_rows:
        return pd.DataFrame()

    # 创建新的数据框
    new_df = pd.DataFrame(new_rows)
    if progress_callback: progress_callback(9, 15, f"正在拆分趣融数据... (已拆分为 {len(new_df)} 条 SN 明细)")
    new_df = new_df[['sn','service_period','K3_settlement_customer','receivable_number_hardware','financial_time','hardware_without_tax','installation_unit_price_without_tax','service_fee_without_tax','from_type','from_table']]
    new_df = new_df.rename(columns={'K3_settlement_customer': 'settle_merchant', 'receivable_number_hardware': 'settle_order', 'financial_time': 'settle_time','hardware_without_tax':'device_price','installation_unit_price_without_tax':'install_price','service_fee_without_tax':'service_price'})

    # 将结果写入 MySQL 数据库中的新表
    to_sql_native(new_df, QR_TABLE + '_tmp', engine, if_exists='replace')
    return new_df

def qr_process_row(row):
    sn_columns = ['main_device_number', 'sub_device_number_1',
                  'sub_device_number_2']
    sn_values = row[sn_columns]
    not_empty_count = sn_values.apply(lambda x: pd.notnull(x) and x != '0' and x != '').sum()

    if not_empty_count == 0:
        return []

    new_rows = []
    for sn in sn_values:
        if pd.notnull(sn) and sn != '0' and sn != '':
            new_row = row.copy()
            new_row['sn'] = sn
            new_row['hardware_without_tax'] /= not_empty_count
            new_row['installation_unit_price_without_tax'] /= not_empty_count
            new_row['service_fee_without_tax'] /= not_empty_count
            new_rows.append(new_row)

    return new_rows

# 其它渠道
def chaifen_lyf(engine, base_path=None, progress_callback=None, min_time=None, max_time=None):
    if progress_callback: progress_callback(10, 15, "正在从数据库读取其它渠道原始数据进行拆分...")
    # 这里 base_path 已经是 get_relative_path 处理过的相对路径
    current_path = base_path if base_path else ""
    try:
        sql = f"SELECT *, '{current_path}{SHEETS_02[0]}' as from_table, '2' as from_type, '' as sn, '0' as installation, cast(amortization_term as unsigned) as service_period FROM {LYF_TABLE} where product_type ='硬件' and business_type like '%%SAAS系统订阅服务—智慧车管线索订阅%%' and business_date >= '{min_time}' and business_date <='{max_time}'"
        with engine.connect() as con:
            df = pd.read_sql(text(sql), con=con)
    except Exception as e:
        print(f"警告:从数据库读取 {LYF_TABLE} 出错 (可能表不存在): {e}")
        return pd.DataFrame()

    new_df = lyf_process_row(df)
    if new_df.empty:
        return pd.DataFrame()
        
    if progress_callback: progress_callback(10, 15, f"正在拆分其它渠道数据... (已拆分为 {len(new_df)} 条明细)")
    # 将结果写入 MySQL 数据库中的新表
    to_sql_native(new_df, LYF_TABLE + '_tmp', engine, if_exists='replace')
    return new_df

def lyf_process_row(df):
    if df.empty:
        return pd.DataFrame()
        
    # 修复:先处理 NaN 并转换为数值类型,再取绝对值
    df['financial_quantity'] = pd.to_numeric(df['financial_quantity'], errors='coerce').fillna(0).apply(abs)

    # 将每条数据拆分成 financial_quantity 条数据
    rows_list = []
    for index, row in df.iterrows():
        # 转换为整数进行循环
        count = int(row['financial_quantity'])
        for i in range(count):
            rows_list.append({'sn': row['sn'],
                                    'service_period': row['amortization_term'],
                                    'settle_merchant': row['customer'],
                                    'settle_order': row['bill_number'],
                                    'settle_time': row['business_date'],
                                    'device_price': row['unit_price'],
                                    'install_price': row['installation'],
                                    'service_price': row['service_without_tax'],
                                    'from_type': row['from_type'],
                                    'from_table': row['from_table']})

    return pd.DataFrame(rows_list)

# 查询数据库 获取设备 激活时间,激活门店,classid #TODO 仲利有部分设备需要从新E盾获取
def get_frms_data(sn):
    gps = create_engine(get_db_engine_config('gps_db'))
    sql = f"""
        select
            c.sn,
            c.activeDate,
            case
                when d.shopName is null then e.className
                else d.shopName
            end as active_merchant,
            c.classId,
            c.workOrderId
        from
            (
            select
                a.sn, a.activeDate, b.standno, b.classId , b.workOrderId
            from
                (
                select
                    sn, activeDate , vehicleId
                from
                    d_track_info
                where
                    sn in {sn}  and length(sn) > 5) a
            left join d_vehicle b on
                a.vehicleId = b.vehicleId ) c
        left join d_vehicle_workorder d on
            c.workOrderId = d.workOrderId
        left join d_class e 
         on c.classId = e.classid  
        """
    with gps.connect() as con:
        df = pd.read_sql(text(sql), con=con)
    df = df.groupby(['sn']).head(1)
    return df

# 查询数据库 获取设备 门店名称,发货时间
def get_som_supplychain_detail_data(sn):
    gps = create_engine(get_db_engine_config('supplychain_db'))
    sql = f"""
            select A.*,B.wh_merchant_name from (
            select
                distinct sn,send_time,SEND_MERCHANT_NO
            from
                device_file
            where
                sn in {sn}  ) A
            left join (select distinct wh_merchant_code,wh_merchant_name from  bs_merchant_order)
                    B on A.SEND_MERCHANT_NO = B.wh_merchant_code
        """
    with gps.connect() as con:
        df = pd.read_sql(text(sql), con=con)

    return df

def fill_data(x, raw, raw_y):
    raw_value = x[raw]
    raw_y_value = x[raw_y]

    return raw_y_value if len(str(raw_value)) < 5 and str(raw_value) != '其他' else raw_value

import io

def export_audit_data(engine, min_time, max_time):
    """
    根据审计查询 SQL 导出数据
    :param engine: 数据库引擎
    :param min_time: 开始时间
    :param max_time: 结束时间
    :return: BytesIO 对象 (Excel 文件)
    """
    # 提取年份并更新全局表名
    target_year = min_time[:4]
    update_global_tables_by_year(engine, target_year)

    # 1. 设备服务数据
    device_service_sql = f"""
    SELECT 
        A.id as 'id',
        A.sn as '设备号',
        A.active_time as '激活时间',
        A.active_merchant as '激活商户',
        A.device_period as '硬件期限',
        A.settle_merchant as '结算商户',
        A.settle_order as '结算单号',
        A.settle_time as '结算时间',
        A.device_price as '设备价格',
        A.install_price as '安装价格',
        B.service_price as '服务价格',
        A.from_type as '来源'
    FROM ( 
        SELECT 
            max(id) as id,
            sn,
            max(active_time) as active_time,
            max(active_merchant) as active_merchant,
            max(device_period) as device_period,
            max(settle_merchant) as settle_merchant,
            max(settle_order) as settle_order,
            max(settle_time) as settle_time,
            max(device_price) as device_price,
            sum(install_price) as install_price,
            max(from_type) as from_type 
        FROM {DEVICE_DETAILS_TABLE} 
        WHERE settle_time >= :start_time AND settle_time <= :end_time 
        GROUP BY sn 
    ) A
    LEFT JOIN (
        SELECT * FROM {SERVICE_DETAILS_TABLE} 
        WHERE from_type != 4 AND delete_flag IS NULL 
          AND settle_time >= :start_time AND settle_time <= :end_time
    ) B ON A.sn = B.sn
    """
    
    # 2. 续费数据
    renewal_sql = f"""
    SELECT 
        id as 'id',
        sn as '设备号',
        active_time as '激活时间',
        active_merchant as '激活商户',
        service_period as '服务期限',
        settle_merchant as '结算商户',
        settle_order as '结算单号',
        settle_time as '结算时间',
        0 as '设备价格',
        0 as '安装价格',
        service_price as '服务价格',
        4 as '来源'
    FROM {SERVICE_DETAILS_TABLE} 
    WHERE from_type = 4 
      AND settle_time >= :start_time AND settle_time <= :end_time
    """
    
    params = {"start_time": min_time, "end_time": max_time}
    
    with engine.connect() as con:
        df_device = pd.read_sql(text(device_service_sql), con, params=params)
        df_renewal = pd.read_sql(text(renewal_sql), con, params=params)
        
    # 如果两张表都为空,返回 None 表示无数据
    if df_device.empty and df_renewal.empty:
        return None
        
    # 生成 Excel
    output = io.BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df_device.to_excel(writer, sheet_name='设备服务数据', index=False)
        df_renewal.to_excel(writer, sheet_name='续费数据', index=False)
    
    output.seek(0)
    return output

def export_dijia_audit_data(engine, min_time, max_time, year):
    """
    导出嘀加审计报表
    :param engine: 数据库引擎 (dijia_db)
    :param min_time: 开始时间
    :param max_time: 结束时间
    :param year: 年份
    :return: BytesIO 对象 (Excel 文件)
    """
    from sql_utils import execute_sql_file
    import os

    # 获取 SQL 文件路径
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sql_file_path = os.path.join(base_dir, "2-report_generation", "dj", "dijia_report_data.sql")
    
    if not os.path.exists(sql_file_path):
        raise FileNotFoundError(f"找不到查询脚本: {sql_file_path}")

    # 计算结束时间 (下个月第一天)
    start_dt = datetime.datetime.strptime(min_time, '%Y-%m-%d')
    if start_dt.month == 12:
        next_month_dt = datetime.datetime(start_dt.year + 1, 1, 1)
    else:
        next_month_dt = datetime.datetime(start_dt.year, start_dt.month + 1, 1)
    end_time = next_month_dt.strftime('%Y-%m-%d')

    params = {
        "year": year,
        "start_time": min_time,
        "end_time": end_time
    }

    # 执行 SQL
    results = execute_sql_file(sql_file_path, params=params)
    
    if not results:
        return None

    # 生成 Excel
    output = io.BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        # 优先放汇总页
        summary_data = next((res for res in results if "汇总" in res['title']), None)
        if summary_data:
            summary_data['data'].to_excel(writer, sheet_name='数据汇总', index=False)
        
        # 放其他明细页
        for res in results:
            if "汇总" not in res['title']:
                # sheet 名称限制 31 字符
                sheet_name = res['title'][:30]
                res['data'].to_excel(writer, sheet_name=sheet_name, index=False)

    output.seek(0)
    return output

def handle_duplicate_sns(engine, min_time=None, max_time=None, progress_callback=None):
    """
    检查 DEVICE_DETAILS_TABLE 表是否存在重复 SN,并按逻辑处理。
    1. 检查重复 SN。
    2. 如果重复,检查 device_price 是否为一正一负(绝对值相同)。
    3. 如果不是一正一负,则对最新 settle_time 的 SN 进行造号处理。
    4. 同步更新 SERVICE_DETAILS_TABLE 表中的 SN。
    """
    if progress_callback: progress_callback(15.5, 15, "正在检查并处理重复设备号...")
    
    # 1. 查找重复 SN
    # 逻辑:查找总数大于 1 且在当前月份范围内至少有一条记录的 SN
    time_filter_sum = ""
    if min_time and max_time:
        time_filter_sum = f" HAVING COUNT(*) > 1 AND SUM(CASE WHEN settle_time >= '{min_time}' AND settle_time <= '{max_time}' THEN 1 ELSE 0 END) > 0 "
    else:
        time_filter_sum = " HAVING COUNT(*) > 1 "
        
    dup_sql = f"SELECT sn FROM {DEVICE_DETAILS_TABLE} GROUP BY sn {time_filter_sum}"
    dup_sns_df = pd.read_sql(dup_sql, engine)
    
    if dup_sns_df.empty:
        print(f"在 {min_time} 至 {max_time} 范围内未发现重复 SN。")
        return

    dup_sns = dup_sns_df['sn'].tolist()
    print(f"在 {min_time} 至 {max_time} 范围内发现 {len(dup_sns)} 个重复 SN: {dup_sns}")

    # 获取当前重跑配置标识位
    sql = f"SELECT last_record, current_record FROM {RERUN_CONF_TABLE}"
    rerun_df = pd.read_sql(sql, engine)
    
    if rerun_df.empty:
        raise RuntimeError(f"找不到重跑配置表 {RERUN_CONF_TABLE},无法继续处理重复 SN。")
    else:
        current_record = rerun_df['current_record'].max()
        last_record = rerun_df['last_record'].max()

    updated_count = 0
    
    for sn in dup_sns:
        # 查询该 SN 的所有记录,按 settle_time 倒序排列
        query_sql = f"SELECT * FROM {DEVICE_DETAILS_TABLE} WHERE sn = '{sn}' ORDER BY settle_time DESC"
        records = pd.read_sql(query_sql, engine)
        
        if len(records) < 2:
            continue
            
        # 检查最新两条记录是否为一正一负
        rec_latest = records.iloc[0]
        rec_prev = records.iloc[1]
        
        price_latest = float(rec_latest['device_price']) if rec_latest['device_price'] else 0.0
        price_prev = float(rec_prev['device_price']) if rec_prev['device_price'] else 0.0
        
        # 如果不是绝对值相同的一正一负 (相加不为0,或者虽然相加为0但都是0)
        if abs(price_latest + price_prev) > 0.001 or (price_latest == 0 and price_prev == 0):
            print(f"SN {sn} 重复且价格不符合冲销逻辑 (Latest: {price_latest}, Prev: {price_prev}),进行造号处理。")
            
            # 2. 造新 SN
            current_record += 1
            new_sn = str(current_record)
            
            # 生成随机时间 (参考 796-814 逻辑)
            settle_time = rec_latest['settle_time']
            if isinstance(settle_time, str):
                settle_time_dt = datetime.datetime.strptime(settle_time.split()[0], '%Y-%m-%d')
            else:
                settle_time_dt = settle_time
                
            active_num = int(random.randint(0, 16)) * -1
            delivery_num = int(random.randint(15, 31)) * -1
            
            new_active_time = (settle_time_dt + datetime.timedelta(days=active_num)).strftime('%Y-%m-%d %H:%M:%S')
            new_delivery_time = (settle_time_dt + datetime.timedelta(days=delivery_num)).strftime('%Y-%m-%d %H:%M:%S')
            new_active_merchant = rec_latest['settle_merchant']
            new_delivery_merchant = rec_latest['settle_merchant']
            
            # 3. 更新数据库
            with engine.begin() as con:
                # 更新 device_details
                update_device_sql = f"""
                    UPDATE {DEVICE_DETAILS_TABLE} 
                    SET sn = :new_sn, 
                        active_time = :active_time, 
                        active_merchant = :active_merchant,
                        delivery_time = :delivery_time,
                        delivery_merchant = :delivery_merchant
                    WHERE id = :id
                """
                con.execute(text(update_device_sql), {
                    "new_sn": new_sn,
                    "active_time": new_active_time,
                    "active_merchant": new_active_merchant,
                    "delivery_time": new_delivery_time,
                    "delivery_merchant": new_delivery_merchant,
                    "id": rec_latest['id']
                })
                
                # 更新 service_details
                # 使用 sn, settle_time, settle_order 确定唯一性 (device_price 不在表中)
                update_service_sql = f"""
                    UPDATE {SERVICE_DETAILS_TABLE}
                    SET sn = :new_sn,
                        active_time = :active_time, 
                        active_merchant = :active_merchant,
                        delivery_time = :delivery_time,
                        delivery_merchant = :delivery_merchant
                    WHERE sn = :old_sn 
                      AND settle_time = :settle_time 
                      AND settle_order = :settle_order
                """
                con.execute(text(update_service_sql), {
                    "new_sn": new_sn,
                    "active_time": new_active_time,
                    "active_merchant": new_active_merchant,
                    "delivery_time": new_delivery_time,
                    "delivery_merchant": new_delivery_merchant,
                    "old_sn": sn,
                    "settle_time": rec_latest['settle_time'],
                    "settle_order": rec_latest['settle_order']
                })
            
            updated_count += 1

    # 4. 更新重跑配置标识位
    if updated_count > 0:
        with engine.begin() as con:
            con.execute(text(f"UPDATE {RERUN_CONF_TABLE} SET current_record = {current_record}"))
        print(f"重复 SN 处理完成,共更新 {updated_count} 条记录。")
    else:
        print("未发现需要处理的重复 SN。")

def calculate_batch_range(batch_name, batch_path=None):
    """
    根据批次名称和路径计算时间范围
    """
    min_time = None
    max_time = None
    
    # 尝试从 batch_name 或 batch_path 中解析年月
    # 1. 尝试匹配 YYYYMM 格式
    if batch_name and len(batch_name) >= 6 and batch_name[:6].isdigit():
        year = int(batch_name[:4])
        month = int(batch_name[4:6])
        min_time = f"{year}-{month:02d}-01"
        _, last_day = calendar.monthrange(year, month)
        max_time = f"{year}-{month:02d}-{last_day:02d}"
    
    # 2. 如果没匹配到,尝试从路径和名称中提取
    if not min_time:
        import re
        # 从 batch_path 中找年份 (4位数字)
        year_match = re.search(r'20\d{2}', batch_path) if batch_path else None
        # 从 batch_name 中找月份 (1-2位数字)
        month_match = re.search(r'(\d{1,2})[月|份]', batch_name) if batch_name else None
        
        if year_match and month_match:
            year = int(year_match.group())
            month = int(month_match.group(1))
            if 1 <= month <= 12:
                min_time = f"{year}-{month:02d}-01"
                _, last_day = calendar.monthrange(year, month)
                max_time = f"{year}-{month:02d}-{last_day:02d}"
    
    if not min_time:
        error_msg = f"无法从批次名称 '{batch_name}' 或路径解析出有效的年份和月份。请确保批次名称包含月份信息(如:数据源拆分7月份)。"
        raise ValueError(error_msg)
        
    return min_time, max_time

def get_monthly_data_stats(batch_name, batch_path=None, engine=None):
    """
    获取指定批次月份在各表中的数据量统计
    """
    min_time, max_time = calculate_batch_range(batch_name, batch_path)
    
    if engine is None:
        connection_str = get_db_engine_config('device_detail_db')
        engine = create_engine(connection_str)
        
    # 提取年份并更新全局表名
    target_year = min_time[:4]
    update_global_tables_by_year(engine, target_year)
        
    stats = []
    samples = {}
    
    # 定义要查询的表及其对应的时间字段
    tables_to_check = [
        {"name": "汇通原始表", "table": HUITONG_TABLE, "time_field": "financial_time"},
        {"name": "续费原始表", "table": XUFEI_TABLE, "time_field": "financial_time"},
        {"name": "渠道原始表", "table": CHANNEL_TABLE, "time_field": "business_date"},
        {"name": "趣融原始表", "table": QR_TABLE, "time_field": "financial_time"},
        {"name": "其它渠道原始表", "table": LYF_TABLE, "time_field": "business_date"},
        {"name": "设备明细结果表", "table": DEVICE_DETAILS_TABLE, "time_field": "settle_time"},
        {"name": "服务明细结果表", "table": SERVICE_DETAILS_TABLE, "time_field": "settle_time"}
    ]
    
    with engine.connect() as con:
        for item in tables_to_check:
            table_name = item["table"]
            if not table_name:
                continue
                
            try:
                # 1. 查询总数
                sql_count = f"SELECT COUNT(*) FROM {table_name} WHERE {item['time_field']} >= :min_time AND {item['time_field']} <= :max_time"
                count = con.execute(text(sql_count), {"min_time": min_time, "max_time": max_time}).scalar()
                
                stats.append({
                    "表格类型": item["name"],
                    "数据库表名": table_name,
                    "当月数据量": f"{count:,}" if count is not None else "0"
                })

                # 2. 抽取 5 条示例数据
                if count and count > 0:
                    sql_sample = f"SELECT * FROM {table_name} WHERE {item['time_field']} >= :min_time AND {item['time_field']} <= :max_time LIMIT 5"
                    df_sample = pd.read_sql(text(sql_sample), con, params={"min_time": min_time, "max_time": max_time})
                    samples[item["name"]] = df_sample
                else:
                    samples[item["name"]] = pd.DataFrame()
                    
            except Exception as e:
                stats.append({
                    "表格类型": item["name"],
                    "数据库表名": table_name,
                    "当月数据量": f"查询失败 (可能表不存在)"
                })
                samples[item["name"]] = pd.DataFrame()
                
    return {"summary": stats, "samples": samples}

def process_device_details(batch_path=None, batch_name=None, engine=None, progress_callback=None, is_rerun=None):
    if is_rerun is None:
        is_rerun = IS_RERUN_DEFAULT

    # 自动计算该月的第一天和最后一天
    min_time, max_time = calculate_batch_range(batch_name, batch_path)
    print(f"自动计算时间范围: {min_time} 至 {max_time}")
    
    # 提取年份并更新全局表名
    target_year = min_time[:4]
    if engine is None:
        connection_str = get_db_engine_config('device_detail_db')
        engine = create_engine(connection_str)
    
    update_global_tables_by_year(engine, target_year)
    
    # 如果提供了 batch_path,则使用 it,否则使用 settings.py 中的 FILE_PATH
    current_file_path = batch_path if batch_path else FILE_PATH

    print(f"开始处理数据,路径: {current_file_path}")

    # 3.将不同类型的表导入到mysql中
    counts = {}
    counts['huitong_raw'] = fill_huitong_sheet(engine, HUITONG_TABLE, current_file_path, progress_callback, min_time, max_time)
    counts['xufei_raw'] = fill_xufei_sheet(engine, XUFEI_TABLE, current_file_path, progress_callback, min_time, max_time)
    counts['channel_raw'] = fill_channel_sheet(engine, CHANNEL_TABLE, current_file_path, progress_callback, min_time, max_time)
    counts['qr_raw'] = fill_qr_sheet(engine, QR_TABLE, current_file_path, progress_callback, min_time, max_time)
    counts['lyf_raw'] = fill_lyf_sheet(engine, LYF_TABLE, current_file_path, progress_callback, min_time, max_time)

    # 4.生成明细数据
    # 计算用于 SQL 的相对路径
    sql_base_path = get_relative_path(current_file_path)
    if sql_base_path and not sql_base_path.endswith('/'):
        sql_base_path += '/'

    huitong_df = chaifen_huitong(engine, sql_base_path, progress_callback, min_time, max_time)
    xufei_df = chaifen_xufei(engine, sql_base_path, progress_callback, min_time, max_time)
    channel_df = chaifen_channel(engine, sql_base_path, progress_callback, min_time, max_time)
    qr_df = chaifen_qr(engine, sql_base_path, progress_callback, min_time, max_time)
    lyf_df = chaifen_lyf(engine, sql_base_path, progress_callback, min_time, max_time)

    counts['huitong_split'] = len(huitong_df)
    counts['xufei_split'] = len(xufei_df)
    counts['channel_split'] = len(channel_df)
    counts['qr_split'] = len(qr_df)
    counts['lyf_split'] = len(lyf_df)

    # 将非空的 DataFrame 存储在一个列表中
    df_list = [df for df in [huitong_df, xufei_df, channel_df, qr_df, lyf_df] if not df.empty]

    if not df_list:
        print("警告:没有读取到任何有效数据,程序将停止后续处理。")
        return {"status": "error", "message": "没有读取到任何有效数据", "counts": counts}

    # 使用 concat() 函数将它们合并成一个 DataFrame
    all_book_df = pd.concat(df_list, axis=0, ignore_index=True)
    
    # 校验结算时间是否在当前批次的月份范围内
    if not all_book_df.empty:
        # 确保 settle_time 为日期格式进行比较
        # 再次调用 date_format 确保格式统一为 YYYY-MM-DD,防止 1970 问题
        all_book_df['settle_time'] = date_format(all_book_df['settle_time'])
        temp_settle_dt = pd.to_datetime(all_book_df['settle_time'], format='%Y-%m-%d', errors='coerce')
        
        invalid_data = all_book_df[
            (temp_settle_dt < pd.to_datetime(min_time)) | 
            (temp_settle_dt > pd.to_datetime(max_time))
        ]
        if not invalid_data.empty:
            # 获取一个非 1970 的示例日期用于展示
            sample_date = invalid_data['settle_time'].iloc[0]
            error_msg = f"检测到非本月数据!当前批次应为 {min_time[:7]},但数据中包含 {sample_date} 等跨月记录(共 {len(invalid_data)} 条)。请检查数据源文件是否正确。处理已中止。"
            print(f"错误: {error_msg}")
            raise ValueError(error_msg)

    all_book_df = all_book_df.assign(active_merchant=None,active_time=None,device_type='8',delivery_time=None,delivery_merchant=None,calssid=None)

    if progress_callback: progress_callback(11, 15, "正在汇总所有拆分后的数据...")
    to_sql_native(all_book_df, ALL_TMP_TABLE, engine, if_exists="replace")

    all_book_df = pd.read_sql(text(f"select *,service_period as device_period from {ALL_TMP_TABLE}"), con=engine)

    # 读取数据库配置,如果是重跑
    temp_record = 44100102745
    last_record = 00000000000
    current_record = 00000000000
    sql = f" select * from {RERUN_CONF_TABLE} "
    with engine.connect() as con:
        rerun_df = pd.read_sql(text(sql), con=con)
    if is_rerun:
        temp_record = rerun_df['last_record'].max()
        last_record = rerun_df['last_record'].max()
    else:
        temp_record = rerun_df['current_record'].max()
        last_record = rerun_df['current_record'].max()

    # 设置重跑标识,造一些设备号
    for i in all_book_df.index:
        if len(str(all_book_df['sn'].at[i]).replace('.0', '')) < 5:
            all_book_df['sn'].at[i] = temp_record + 1
            temp_record = temp_record + 1
            active_num = int(random.randint(0, 16)) * -1
            delivery_num = int(random.randint(15, 31)) * -1
            all_book_df['active_time'].at[i] = str(
                datetime.datetime.strptime(str(all_book_df['settle_time'].at[i]), '%Y-%m-%d') + datetime.timedelta(
                    days=active_num))
            all_book_df['active_merchant'].at[i] = all_book_df['settle_merchant'].at[i]
            all_book_df['delivery_time'].at[i] = str(
                datetime.datetime.strptime(str(all_book_df['settle_time'].at[i]), '%Y-%m-%d') + datetime.timedelta(
                    days=delivery_num))
            all_book_df['delivery_merchant'].at[i] = all_book_df['settle_merchant'].at[i]

    current_record = temp_record
    print("上一次标志位为:" + str(last_record))
    print("当前标志位为:" + str(current_record))

    # 制作一个df 写入mysql
    if progress_callback: progress_callback(12, 15, "正在更新重跑配置位...")
    rec_df = pd.DataFrame({'last_record': [last_record], 'current_record': [current_record]})
    to_sql_native(rec_df, RERUN_CONF_TABLE, engine, if_exists="replace")

    all_book_df['sn'] = all_book_df['sn'].apply(lambda x: 0 if len(str(x)) < 5 else str(x).replace(".0", ""))
    sns = tuple(str(i) for i in all_book_df['sn'].values)

    # 获取设备激活相关信息
    if progress_callback: progress_callback(12.5, 15, "正在获取设备激活与发货详情...") # 中间步骤
    frms_df = get_frms_data(sns)
    frms_df.rename(columns={'activeDate': 'active_time'}, inplace=True)

    # .drop(['active_time','active_merchant','classid','delivery_time','delivery_merchant'],axis=1)

    merge_df = pd.merge(all_book_df, frms_df, on='sn', how='left')
    merge_df.rename(columns={'user_type': 'from_type'}, inplace=True)

    # 获取设备发货相关信息
    frms_deliver_df = get_som_supplychain_detail_data(sns)
    frms_deliver_df.rename(
        columns={'send_time': 'delivery_time', 'wh_merchant_name': 'delivery_merchant'},
        inplace=True)
    print(frms_deliver_df)
    merge_df = pd.merge(merge_df, frms_deliver_df, on='sn', how='left')

    # active_time active_merchant delivery_time delivery_merchant 数据填充
    merge_df['active_time'] = merge_df.apply(fill_data, axis=1, args=('active_time_x', 'active_time_y'))
    merge_df['active_merchant'] = merge_df.apply(fill_data, axis=1, args=('active_merchant_x', 'active_merchant_y'))
    merge_df['delivery_time'] = merge_df.apply(fill_data, axis=1, args=('delivery_time_x', 'delivery_time_y'))
    merge_df['delivery_merchant'] = merge_df.apply(fill_data, axis=1,
                                                   args=('delivery_merchant_x', 'delivery_merchant_y'))

    # 过滤 service_price 为空、'0'、0 或 NaN 的数据
    merge_service_df = merge_df.query(" service_price.notna() and service_price != 0 and service_price !='0' and service_price !='' ")
    merge_service_df = merge_service_df[[
        'sn', 'device_type', 'delivery_time', 'delivery_merchant', 'active_time', 'active_merchant', 'service_period',
        'settle_merchant', 'settle_order', 'settle_time', 'service_price', 'from_type', 'classId', 'from_table']]
    
    # 过滤 device_price 为空或 NaN 的数据 (且排除 from_type 为 '4' 的数据)
    merge_device_df = merge_df.query(" device_price.notna() and device_price!='' and from_type!='4' ")[[
        'sn', 'device_type', 'delivery_time', 'delivery_merchant', 'active_time', 'active_merchant', 'device_period',
        'settle_merchant', 'settle_order', 'settle_time', 'device_price', 'install_price', 'from_type', 'classId',
        'from_table']]
    merge_df = merge_df[[
        'sn', 'device_type', 'delivery_time', 'delivery_merchant', 'active_time', 'active_merchant', 'device_period',
        'service_period', 'settle_merchant', 'settle_order', 'settle_time', 'device_price', 'install_price',
        'service_price', 'from_type', 'classId', 'from_table']]

    if progress_callback: progress_callback(13, 15, "正在写入完整明细数据...")
    to_sql_native(merge_df, ALL_DETAILS_TABLE, engine, if_exists="replace")

    # 支持重跑数据
    min_settle_time = merge_df['settle_time'].min()
    max_settle_time = merge_df['settle_time'].max()
    print("当前最小结算时间为:" + str(min_settle_time) + "\r\n 当前最大结算时间为:" + str(max_settle_time))

    delete_sql = f"delete from {DEVICE_DETAILS_TABLE} where settle_time >= '" + str(min_settle_time) + "' and settle_time <='" + str(max_settle_time) + "'"
    print("当前执行的删除sql为:" + delete_sql)

    with engine.begin() as con:
        con.execute(text(delete_sql))

    delete_sql = f"delete from {SERVICE_DETAILS_TABLE} where settle_time >= '" + str(min_settle_time) + "' and settle_time <='" + str(max_settle_time) + "'"
    print("当前执行的删除sql为:" + delete_sql)

    with engine.begin() as con:
        con.execute(text(delete_sql))

    if progress_callback: progress_callback(14, 15, "正在写入服务明细数据...")
    to_sql_native(merge_service_df, SERVICE_DETAILS_TABLE, engine, if_exists="append")
    
    if progress_callback: progress_callback(15, 15, "正在写入设备明细数据...")
    to_sql_native(merge_device_df, DEVICE_DETAILS_TABLE, engine, if_exists="append")
    
    # 新增检查逻辑
    handle_duplicate_sns(engine, min_settle_time, max_settle_time, progress_callback)

    counts['total_service'] = len(merge_service_df)
    counts['total_device'] = len(merge_device_df)
    
    return {
        "status": "success", 
        "counts": counts,
        "min_time": min_time,
        "max_time": max_time
    }

if __name__ == "__main__":
    process_device_details()