dijia_sync.py 53 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
import streamlit as st
import pandas as pd
from sqlalchemy import create_engine, text
import yaml
import os
import datetime
import random
from MysqlUtility import MySQL, paddstr, paddnum
import logging


g_papdev_dbcfg = {
        "host": "192.168.5.23",
        "port": 3307,
        "user": "data_house_user",
        "passwd": "ZhaiMiAxIg",
        "db": "glsx_pap",
        "charset": "utf8",
    }

g_fmrs_dbcfg = {
    "host": "192.168.5.22",
    "port": 3307,
    "user": "data_house_user",
    "passwd": "ZhaiMiAxIg",
    "db": "allocate_gps",
    "charset": "utf8",
}

# g_gldj_dbcfg = {'host': '172.16.0.161', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
#                'db': 'glsx_dj', 'charset': 'utf8'}

g_gldj_dbcfg = {
    "host": "192.168.5.23",
    "port": 3306,
    "user": "data_house_user",
    "passwd": "ZhaiMiAxIg",
    "db": "glsx_dj",
    "charset": "utf8",
}

g_ghdj_dbcfg = {
    "host": "47.97.203.216",
    "port": 3306,
    "user": "user_wangxl",
    "passwd": "BbuJbiPM",
    "db": "glsx_dj",
    "charset": "utf8",
}


g_xydj_dbcfg = {
    "host": "121.18.128.91",
    "port": 3306,
    "user": "biz_glsx_dj",
    "passwd": "fdaewip",
    "db": "glsx_dj",
    "charset": "utf8",
}

g_cyb_dbcfg = {
    "host": "172.16.0.161",
    "port": 3306,
    "user": "data_house_user",
    "passwd": "ZhaiMiAxIg",
    "db": "cyb_os",
    "charset": "utf8",
}

g_supply_dbcfg = {
    "host": "192.168.5.23",
    "port": 3306,
    "user": "data_house_user",
    "passwd": "ZhaiMiAxIg",
    "db": "glsx_supplychain",
    "charset": "utf8",
}

glsx_sales_dbcfg = {
    "host": "172.16.0.161",
    "port": 3306,
    "user": "data_house_user",
    "passwd": "ZhaiMiAxIg",
    "db": "glsx_sales",
    "charset": "utf8",
}

g_audit_dbcfg = {
    "host": "192.168.5.2",
    "port": 3307,
    "user": "data_house_user",
    "passwd": "ZhaiMiAxIg",
    "db": "glsx_audit",
    "charset": "utf8",
}

g_biz_snmap_dbcfg = {
    "host": "192.168.5.2",
    "port": 3306,
    "user": "biz_glsx_data",
    "passwd": "unEKczDc",
    "db": "glsx_biz_data",
    "charset": "utf8",
}

# g_biz_dbcfg = {
#     "host": "192.168.5.25",
#     "port": 3310,
#     "user": "biz_device_detail",
#     "passwd": "M6khz3CQ",
#     "db": "device_detail",
#     "charset": "utf8",
# }

g_biz_dbcfg = {
    "host": "192.168.5.2",
    "port": 3306,
    "user": "biz_glsx_data",
    "passwd": "unEKczDc",
    "db": "glsx_biz_data",
    "charset": "utf8",
}

g_glsx_ddh_dbcfg = {
    "host": "192.168.5.5",
    "port": 3311,
    "user": "user_wangxl",
    "passwd": "BbuJbiPM",
    "db": "glsx_ddh",
    "charset": "utf8",
}


g_dev_map_dict = {}
fetchsize = 1500
# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("dijia_sync.log", encoding='utf-8')
    ]
)
logger = logging.getLogger(__name__)

# --- Config Helpers ---
def get_config():
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # project/4-data_sync/dijia -> project/config.yaml (2 levels up)
    base_dir = os.path.dirname(os.path.dirname(current_dir))
    config_path = os.path.join(base_dir, "config.yaml")
    
    # 如果找不到,尝试往上一级找(兼容可能的目录结构差异)
    if not os.path.exists(config_path):
         base_dir = os.path.dirname(base_dir) # try 3 levels up
         config_path = os.path.join(base_dir, "config.yaml")

    if not os.path.exists(config_path):
         st.error(f"配置文件未找到: {config_path}")
         return None

    with open(config_path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f)

def get_db_url(db_config):
    return f"mysql+pymysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['db_name']}?charset={db_config['charset']}"

def sync_table(from_engine, to_engine, from_table, to_table):
    """
    Syncs a single table from source to destination.
    Truncates destination first. If destination doesn't exist, creates it.
    """
    st.write(f"正在同步: `{from_table}` -> `{to_table}` ...")
    
    # 1. Read from source
    try:
        query = f"SELECT * FROM {from_table}"
        df = pd.read_sql(query, con=from_engine)
    except Exception as e:
        st.error(f"读取源表 {from_table} 失败: {e}")
        return False

    if df.empty:
        st.warning(f"源表 {from_table} 为空。")
        # 继续执行以清空目标表
    
    # 2. Truncate destination (if exists)
    truncate_sql = f"TRUNCATE TABLE {to_table}"
    try:
        with to_engine.connect() as con:
            con.execute(text(truncate_sql))
    except Exception as e:
        # Error 1146: Table doesn't exist. Ignore.
        if "1146" in str(e):
            st.info(f"目标表 {to_table} 不存在,将在写入时自动创建。")
        else:
            st.error(f"清空目标表 {to_table} 失败: {e}")
            return False

    # 3. Write to destination
    if not df.empty:
        # 如果源表包含 batch 字段,则移除该字段不同步
        if 'batch' in df.columns:
            st.info(f"检测到源表 {from_table} 包含 'batch' 字段,将在同步时忽略该字段。")
            df = df.drop(columns=['batch'])
        
        # 如果源表包含 id 字段,则移除该字段不同步
        cols_to_drop = [col for col in df.columns if col.lower() == 'id']
        if cols_to_drop:
            df = df.drop(columns=cols_to_drop)
            
        try:
            # chunksize to avoid packet too large errors
            df.to_sql(name=to_table, con=to_engine, if_exists="append", index=False, chunksize=1000)
            st.success(f"成功写入 `{to_table}` ({len(df)} 行)")
        except Exception as e:
            st.error(f"写入目标表 {to_table} 失败: {e}")
            return False
    else:
        st.success(f"源表为空,目标表 `{to_table}` 已清空。")

    return True

def sync_extra_info_table(from_engine, to_engine, from_table, to_table, year):
    """
    Syncs extra info table from source to destination for a specific year.
    1. Deletes data in destination table for the given year (based on created_date).
    2. Selects data from source table for the given year (based on created_date).
    3. Inserts data into destination table.
    """
    st.write(f"正在同步: `{from_table}` -> `{to_table}` (年份: {year}) ...")
    
    date_col = "created_date"
    
    delete_sql = f"DELETE FROM {to_table} WHERE {date_col} >= '{year}-01-01' AND {date_col} < '{year + 1}-01-01'"
    try:
        with to_engine.begin() as con:
            con.execute(text(delete_sql))
            st.info(f"已清理目标表 {to_table} {year} 年数据 ({date_col})")
    except Exception as e:
        # Error 1146: Table doesn't exist.
        if "1146" in str(e):
             st.info(f"目标表 {to_table} 不存在,将在写入时自动创建。")
        else:
            st.error(f"清理目标表 {to_table} 失败: {e}")
            return False

    # 2. Read from source
    try:
        query = f"SELECT * FROM {from_table} WHERE {date_col} >= '{year}-01-01' AND {date_col} < '{year + 1}-01-01'"
        df = pd.read_sql(query, con=from_engine)
    except Exception as e:
        st.error(f"读取源表 {from_table} 失败: {e}")
        return False

    if df.empty:
        st.warning(f"源表 {from_table} {year} 年数据为空。")
        return True
    
    # 3. Write to destination
    if not df.empty:
        batch_cols = [col for col in df.columns if col.lower() == 'batch']
        if batch_cols:
             df = df.drop(columns=batch_cols)
        
        # 如果源表包含 id 字段,则移除该字段不同步
        cols_to_drop = [col for col in df.columns if col.lower() == 'id']
        if cols_to_drop:
            df = df.drop(columns=cols_to_drop)
        
        # 过滤掉 SN 为空的数据 (针对 ddh_rescue_event 等表)
        sn_cols = [col for col in df.columns if col.lower() == 'sn']
        if sn_cols:
            sn_col = sn_cols[0]
            original_len = len(df)
            df = df[df[sn_col].notna() & (df[sn_col].astype(str).str.strip() != '')]
            if len(df) < original_len:
                st.warning(f"表 {from_table} 已过滤 {original_len - len(df)} 条 SN 为空的数据")
             
        try:
            df.to_sql(name=to_table, con=to_engine, if_exists="append", index=False, chunksize=1000)
            st.success(f"成功写入 `{to_table}` ({len(df)} 行)")
        except Exception as e:
            st.error(f"写入目标表 {to_table} 失败: {e}")
            return False

    return True


def sync_car_maintain(dataFrom, fromTime, endTime, year=None):

    """同步维修保养"""
    fetch = fetchsize
    if dataFrom == "DJ":  # 广联嘀加
        srcDbConn = MySQL(g_gldj_dbcfg)
        tblName = "dj_car_maintain_gl"
    elif dataFrom == "GUARD":  # 广汇嘀加
        srcDbConn = MySQL(g_ghdj_dbcfg)
        tblName = "dj_car_maintain_gh"
    else:
        return
    auditConn = MySQL(g_biz_dbcfg)
    bizscreenConn = MySQL(g_biz_dbcfg)

    st.write(f"正在清理 dj_car_maintain created_date 在 {fromTime} 到 {endTime} 之间的旧数据...")
    bizscreenConn.update(f"DELETE FROM dj_car_maintain WHERE created_date >= '{fromTime}' AND created_date < '{endTime}'")

    strColunms = (
        "sn,stand_no,total_mileage,in_time,prev_mileage,first_time,"
        "remind_type,remind_rule,diff_mileage,diff_time,is_new,number_of_shops,"
        "numbers,distance,svrtime,merchant_id,merchant_name,created_by,created_date,updated_by,deleted_flag,batch"
    )
    """
    "plate_number,name,mobile,current_day_time,company,car_brand,car_model,car_system,regist_time,insurance_time," \
    "status,diff_backshop_mileage,diff_backshop_time,vehicle_id,follow_result,follow_time,follow_remarks,maintain_source" \
    """

    count = 0
    startId = 0
    while True:
        # 注意:这里 select 的字段不包含 batch,batch 是我们在 insert 时补进去的
        # select 的列数必须与 strColunms 减去 batch 后的列数一致
        select_cols = (
            "sn,stand_no,total_mileage,in_time,prev_mileage,first_time,"
            "remind_type,remind_rule,diff_mileage,diff_time,is_new,number_of_shops,"
            "numbers,distance,svrtime,merchant_id,merchant_name,created_by,created_date,updated_by,deleted_flag"
        )
        
        sql = (
                "select id,%s from dj_car_maintain where created_date>'%s' and created_date<'%s' and id > %d and deleted_flag = 'N' order by id limit %d"
                % (select_cols, fromTime, endTime, startId, fetch)
        )
        if False == srcDbConn.query(sql):
            logger.error("sync_car_maintain query error, sql=" + sql)
            return
        arrValues = []
        result = srcDbConn.fetchAllRows()
        if len(result) == 0:
            logger.info("sync_car_maintain total count=%d" % count)
            break
            
        for v in result:
            startId = v[0]
            sn = v[1]
            if not sn or str(sn).strip() == '':
                continue
                
            arr = []
            count += 1

            merId = v[16]
            merName = v[17]

            arr.append(paddstr(sn))
            arr.append(paddstr(v[2]))
            arr.append(paddnum(v[3]))
            arr.append(paddstr(v[4]))
            arr.append(paddnum(v[5]))
            arr.append(paddstr(v[6]))
            arr.append(paddnum(v[7]))
            arr.append(paddnum(v[8]))
            arr.append(paddnum(v[9]))
            arr.append(paddnum(v[10]))
            arr.append(paddnum(v[11]))
            arr.append(paddnum(v[12]))
            arr.append(paddnum(v[13]))
            arr.append(paddnum(v[14]))
            arr.append(paddstr(str(v[15])))
            arr.append(paddnum(merId))
            arr.append(paddstr(merName))
            arr.append(paddstr(v[18]))
            arr.append(paddstr(str(v[19])))
            arr.append(paddstr(v[20]))
            arr.append(paddstr(v[21]))
            arr.append(paddnum(year if year else 0)) # Add batch value

            value = "(" + ",".join(arr) + ")"
            arrValues.append(value)

        if len(arrValues) > 0:
            insSql = (
                    "insert into dj_car_maintain ("
                    + strColunms
                    + ") values "
                    + ",".join(arrValues)
            )
            if False == bizscreenConn.insert(insSql):
                logger.error("sync_car_maintain dst_conn.insert failed:%s" % insSql)
                break
            logger.info(
                f"sync_car_maintain dataFrom={dataFrom} progress count={count}"
            )

def sync_car_shop_warning(dataFrom, fromTime, endTime, year=None):
    """到店"""
    fetch = fetchsize
    if dataFrom == "DJ":  # 广联嘀加
        srcDbConn = MySQL(g_gldj_dbcfg)
        tblName = "dj_car_shop_warning_gl"
    elif dataFrom == "GUARD":  # 广汇嘀加
        srcDbConn = MySQL(g_ghdj_dbcfg)
        tblName = "dj_car_shop_warning_gh"
    else:
        return

    auditConn = MySQL(g_biz_dbcfg)
    bizscreenConn = MySQL(g_biz_dbcfg)


    st.write(f"正在清理 dj_car_shop_warning created_date 在 {fromTime} 到 {endTime} 之间的旧数据...")
    bizscreenConn.update(f"DELETE FROM dj_car_shop_warning WHERE created_date >= '{fromTime}' AND created_date < '{endTime}'")

    strColunms = (
        "sn,stand_no,enter_time,out_time,trigger_time,alarm_type,is_new,last_time_distance,last_time_day,"
        "merchant_id,merchant_name,created_by,created_date,updated_by,updated_date,deleted_flag,batch"
    )
    # "plate_number,name,mobile,merchant_type,task_id,vehicle_id"

    count = 0
    startId = 0
    while True:
        select_cols = (
            "sn,stand_no,enter_time,out_time,trigger_time,alarm_type,is_new,last_time_distance,last_time_day,"
            "merchant_id,merchant_name,created_by,created_date,updated_by,updated_date,deleted_flag"
        )
        sql = (
                "select id,%s from dj_car_shop_warning where created_date >='%s' and created_date < '%s' and id > %d and deleted_flag = 'N' order by id limit %d"
                % (select_cols, fromTime, endTime, startId, fetch)
        )
        if False == srcDbConn.query(sql):
            logger.error("sync_car_shop_warning query error, sql=" + sql)
            return
        arrValues = []
        result = srcDbConn.fetchAllRows()
        if len(result) == 0:
            logger.info("sync_car_shop_warning total count=%d" % count)
            break
            
        for v in result:
            startId = v[0]
            sn = v[1]
            if not sn or str(sn).strip() == '':
                continue
                
            arr = []
            count += 1
            
            merId = v[10]
            merName = v[11]

            arr.append(paddstr(sn))
            arr.append(paddstr(v[2]))
            arr.append(paddstr(v[3]))
            arr.append(paddstr(v[4]))
            arr.append(paddstr(v[5]))
            arr.append(paddnum(v[6]))
            arr.append(paddnum(v[7]))
            arr.append(paddnum(v[8]))
            arr.append(paddnum(v[9]))
            arr.append(paddnum(merId))
            arr.append(paddstr(merName))
            arr.append(paddstr(v[12]))
            arr.append(paddstr(str(v[13])))
            arr.append(paddstr(str(v[14])))
            arr.append(paddstr(str(v[15])))
            arr.append(paddstr(v[16]))
            arr.append(paddnum(year if year else 0)) # Add batch value

            value = "(" + ",".join(arr) + ")"
            arrValues.append(value)
            
        if len(arrValues) > 0:
            insSql = (
                    "insert into dj_car_shop_warning ("
                    + strColunms
                    + ") values "
                    + ",".join(arrValues)
            )
            if False == bizscreenConn.insert(insSql):
                logger.error("sync_car_shop_warning dst_conn.insert failed:%s" % insSql)
                break
            logger.info(
                f"sync_car_shop_warning datafrom={dataFrom} progress count={count}"
            )

def sync_ddh_rescue_event(fromTime, endTime, year=None):
    """同步救援事件"""
    
    # 构造数据库连接URL
    src_conf = g_glsx_ddh_dbcfg
    dst_conf = g_biz_dbcfg
    
    src_url = f"mysql+pymysql://{src_conf['user']}:{src_conf['passwd']}@{src_conf['host']}:{src_conf['port']}/{src_conf['db']}?charset={src_conf['charset']}"
    dst_url = f"mysql+pymysql://{dst_conf['user']}:{dst_conf['passwd']}@{dst_conf['host']}:{dst_conf['port']}/{dst_conf['db']}?charset={dst_conf['charset']}"
    
    try:
        src_engine = create_engine(src_url)
        dst_engine = create_engine(dst_url)
    except Exception as e:
        st.error(f"无法连接数据库: {e}")
        return

    # 如果明确了年份,则执行删除
    if year:
        st.write(f"正在清理 ddh_rescue_event {year} 的旧数据(根据 CREATED_DATE)...")
        # 使用 CREATED_DATE 进行删除,确保与 select 逻辑一致,避免重复或遗漏
        delete_sql = f"DELETE FROM ddh_rescue_event WHERE CREATED_DATE >= '{year}-01-01' AND CREATED_DATE < '{int(year) + 1}-01-01'"
        try:
            with dst_engine.connect() as conn:
                conn.execute(text(delete_sql))
                # Explicit commit might be needed depending on driver/sqlalchemy version, 
                # but with .connect() usually auto-commit unless transaction started.
                # However, for safety:
                try:
                    conn.commit()
                except:
                    pass
        except Exception as e:
            st.error(f"清理旧数据失败: {e}")
            return

    # select 时不包含 batch
    select_cols = (
        "SN,EVENT_TYPE,EVENT_ADDRESS,EVENT_LNG,EVENT_LAT,EVENT_DATE,CREATED_BY,"
        "CREATED_DATE,UPDATED_BY,UPDATED_DATE,DELETED_FLAG,TYPE_ID"
    )

    if year:
        # 如果指定了年份,严格按年份筛选数据,忽略传入的 fromTime 和 endTime
        # 确保写入目标表的数据确实属于该年份,避免数据污染
        # 使用 CREATED_DATE 而不是 EVENT_DATE
        sql = (
            "select "
            + select_cols
            + f" from ddh_rescue_event where CREATED_DATE >= '{year}-01-01' and CREATED_DATE < '{int(year) + 1}-01-01' and event_type ='COLLIDE' "
        )
    else:
        sql = (
            "select "
            + select_cols
            + " from ddh_rescue_event where CREATED_DATE >= '%s' and CREATED_DATE < '%s' and event_type ='COLLIDE'"
            % (fromTime, endTime)
        )
    
    try:
        # 使用 pandas 读取数据,自动处理类型
        df = pd.read_sql(sql, src_engine)
    except Exception as e:
        print(f"sync_ddh_rescue_event read failed: {e}")
        st.error(f"读取源数据失败: {e}")
        return

    if df.empty:
        print("sync_ddh_rescue_event: No data found.")
        st.warning("未查询到数据")
        return
    
    # 过滤掉 SN 为空的数据
    if 'SN' in df.columns:
        original_count = len(df)
        # Drop rows where SN is NaN or empty string (after stripping whitespace)
        # Convert to string to safely strip, but be careful with NaNs becoming 'nan'
        # Best approach: use pd.notna() & check for empty string
        df = df[df['SN'].notna() & (df['SN'].astype(str).str.strip() != '')]
        filtered_count = len(df)
        if original_count > filtered_count:
            st.warning(f"已过滤 {original_count - filtered_count} 条 SN 为空的数据")

    # 添加 batch 字段
    # 如果 year 为 None,batch 为 0 (与原逻辑保持一致: paddnum(year if year else 0))
    batch_val = int(year) if year else 0
    df['batch'] = batch_val
    
    total_count = len(df)
    st.write(f"读取到 {total_count} 条数据,准备写入...")

    # 使用 pandas 分批写入,chunksize=1000
    try:
        df.to_sql(name='ddh_rescue_event', con=dst_engine, if_exists='append', index=False, chunksize=1000)
        print(f"sync_ddh_rescue_event done count={total_count}")
        st.success(f"成功同步 {total_count} 条数据到 ddh_rescue_event")
    except Exception as e:
        print(f"sync_ddh_rescue_event insert failed: {e}")
        st.error(f"写入目标表失败: {e}")


# 同步门店数据开始
def sync_merchants(target_engine, source_engine, year):
    """
    同步商户信息:
    1. 从 target_engine 的 dj_{year}_settle_details 获取 distinct merchant_name。
    2. 遍历每个 merchant_name:
       - 去 source_engine 的 dj_system_merchant 查找是否相同。
       - 如果相同,则从 source_engine 更新/插入到 target_engine。
       - 如果没有找到,则自己造一个,创建时间为该年份内随机时间,并插入 target_engine。
    """
    st.info(f"开始同步 {year} 年度的商户信息...")
    try:
        # 清理该年份的数据,保持幂等性 (可选,这里根据需求可以选择是否保留)
        st.write(f"正在清理目标库中 created_date 为 {year} 年的门店数据...")
        start_date = f"{year}-01-01 00:00:00"
        end_date = f"{year}-12-31 23:59:59"
        with target_engine.begin() as conn:
            conn.execute(text("DELETE FROM dj_system_merchant WHERE created_date >= :start_date AND created_date <= :end_date"), {"start_date": start_date, "end_date": end_date})

        # 1. 从 target_engine 的对应结算明细表中获取商户名
        table_name = "dj_2021_settle_details"
        
        # 检查表是否存在
        with target_engine.connect() as conn:
            result = conn.execute(text(f"SHOW TABLES LIKE '{table_name}'"))
            if not result.fetchone():
                # 如果没有当前年的表,则去 2021 的总表里取数据
                table_name = "dj_2021_settle_details"
                st.warning(f"表 dj_{year}_settle_details 不存在,降级从 {table_name} 获取数据。")
        
        # 对于降级到总表的情况,增加时间过滤条件
        year_filter = f"AND settle_time >= '{year}-01-01' AND settle_time < '{year+1}-01-01'" if table_name == "dj_2021_settle_details" else ""

        sql_get_merchants = f"""
            SELECT DISTINCT settle_merchant 
            FROM {table_name}
            WHERE settle_merchant IS NOT NULL AND settle_merchant != '' {year_filter}
        """
        
        with target_engine.connect() as conn:
            result = conn.execute(text(sql_get_merchants))
            merchant_names = [row[0] for row in result.fetchall()]
            
        st.write(f"在 {table_name} 中发现 {len(merchant_names)} 个不重复的商户名。")

        if not merchant_names:
            st.success("没有需要同步的商户!")
            return True

        progress_bar = st.progress(0)
        total = len(merchant_names)
        
        # 为了防止和真实门店号冲突,造数据时使用一个基准值,比如从 9000000 开始累加
        mock_merchant_id_base = 9000000
        
        for i, m_name in enumerate(merchant_names):
            # 2. 去 source_engine 对照
            source_merchant = get_merchant_from_source(source_engine, m_name)
            
            if source_merchant:
                # 找到了,将 source_merchant 同步到 target
                source_merchant['batch'] = year
                if not source_merchant.get('settle_merchant_name'):
                    source_merchant['settle_merchant_name'] = m_name
                
                # 检查 target_engine 是否已经存在(防止重复执行插入报错,虽然上面删除了当年的)
                target_merchant = get_merchant_from_target_by_id(target_engine, source_merchant['merchant_id'])
                if target_merchant:
                    update_merchant_in_target(target_engine, source_merchant, target_merchant['id'])
                else:
                    insert_merchant_into_target(target_engine, source_merchant)
            else:
                # 没找到,自己造一个
                mock_merchant_id_base += 1
                mock_merchant = generate_mock_merchant_data(m_name, mock_merchant_id_base, year)
                insert_merchant_into_target(target_engine, mock_merchant)
                
            if total > 0:
                progress_bar.progress((i + 1) / total)
                
        st.success("商户信息同步完成!")
        return True
        
    except Exception as e:
        st.error(f"Error in sync_merchants: {e}")
        import traceback
        st.error(traceback.format_exc())
        return False

def get_source_merchants_by_year(source_engine, year):
    sql = """
    SELECT * FROM dj_system_merchant 
    WHERE created_date >= :start_date AND created_date <= :end_date
    """
    start_date = f"{year}-01-01 00:00:00"
    end_date = f"{year}-12-31 23:59:59"
    
    with source_engine.connect() as conn:
        result = conn.execute(text(sql), {"start_date": start_date, "end_date": end_date})
        rows = result.mappings().all()
    return [dict(row) for row in rows]

def get_merchant_from_target_by_id(target_engine, merchant_id):
    sql = "SELECT * FROM dj_system_merchant WHERE merchant_id = :merchant_id LIMIT 1"
    with target_engine.connect() as conn:
        result = conn.execute(text(sql), {"merchant_id": merchant_id})
        row = result.mappings().fetchone()
    return dict(row) if row else None

# 保留旧函数以防其他地方调用,虽然在此流程中不再使用
def get_distinct_merchants(target_engine, year):
    table_name = f"dj_{year}_settlment_order"
    
    with target_engine.connect() as conn:
        # Check if table exists
        result = conn.execute(text(f"SHOW TABLES LIKE '{table_name}'"))
        if not result.fetchone():
            st.error(f"Table {table_name} does not exist in target DB.")
            return []
            
        sql = f"""
        select DISTINCT a.cus_name 
        from {table_name} a
        WHERE a.business_type = 'SAAS系统订阅服务—旧版本' 
        AND a.cus_name NOT IN ('东台宝通汽车服务有限责任公司', '广汇汽车服务有限责任公司东台分公司', '广汇汽车服务有限责任公司天津武清分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司')
        """
        
        # st.info(f"Executing query to find merchants in {table_name}...")
        result = conn.execute(text(sql))
        rows = result.mappings().all()
        
    return [row['cus_name'] for row in rows if row['cus_name']]

def get_merchant_from_target(target_engine, merchant_name):
    sql = "SELECT * FROM dj_system_merchant WHERE settle_merchant_name = :name LIMIT 1"
    with target_engine.connect() as conn:
        result = conn.execute(text(sql), {"name": merchant_name})
        row = result.mappings().fetchone()
    return dict(row) if row else None

def get_merchant_from_source(source_engine, merchant_name):
    sql = "SELECT * FROM dj_system_merchant WHERE merchant_name = :name LIMIT 1"
    with source_engine.connect() as conn:
        result = conn.execute(text(sql), {"name": merchant_name})
        row = result.mappings().fetchone()
    return dict(row) if row else None

def update_merchant_in_target(target_engine, merchant_data, target_id):
    # 目标表允许的字段列表
    target_columns = {
        'id', 'merchant_id', 'account_name', 'merchant_name', 'short_name',
        'user_type', 'merchant_type', 'contact_name', 'phone', 'channel_id',
        'address', 'province_id', 'province_name', 'city_id', 'city_name',
        'area_id', 'area_name', 'lng', 'lat', 'shop_photo', 'business_hours',
        'parent_merchant_id', 'parent_merchant_name', 'svr_merchant_id',
        'settle_merchant_name', 'svr_merchant_name', 'created_by',
        'created_date', 'updated_by', 'updated_date', 'deleted_flag', 'batch'
    }

    if 'id' in merchant_data:
        del merchant_data['id']
        
    # 移除目标表中不存在的字段,防止报错
    keys_to_remove = [k for k in merchant_data.keys() if k not in target_columns]
    for k in keys_to_remove:
        del merchant_data[k]

    keys = list(merchant_data.keys())
    # SQLAlchemy style named parameters
    set_clause = ', '.join([f"`{k}` = :{k}" for k in keys])
    
    # Prepare params dict
    params = merchant_data.copy()
    params['target_id'] = target_id
    
    sql = f"UPDATE dj_system_merchant SET {set_clause} WHERE id = :target_id"
    
    try:
        with target_engine.begin() as conn: # Use begin() for transaction
            conn.execute(text(sql), params)
        return True
    except Exception as e:
        st.error(f"Failed to update merchant {merchant_data.get('merchant_name')}: {e}")
        return False

def get_max_merchant_id(target_engine):
    sql = "SELECT MAX(merchant_id) as max_id FROM dj_system_merchant"
    with target_engine.connect() as conn:
        result = conn.execute(text(sql))
        row = result.mappings().fetchone()
        return row['max_id'] if row and row['max_id'] else 1000000

def generate_mock_merchant_data(merchant_name, next_merchant_id, year):
    # Generate random contact name
    surnames = ['张', '李', '王', '赵', '刘', '陈', '杨', '黄', '周', '吴']
    names = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '军', '杰', '磊', '洋', '勇', '艳']
    contact_name = random.choice(surnames) + random.choice(names)
    
    # Generate random phone
    phone = f"1{random.choice(['3', '5', '7', '8', '9'])}{random.randint(100000000, 999999999)}"
    
    # Generate random date in the target year
    start_date = datetime.datetime(year, 1, 1)
    end_date = datetime.datetime(year, 12, 31, 23, 59, 59)
    random_seconds = random.randint(0, int((end_date - start_date).total_seconds()))
    random_date = start_date + datetime.timedelta(seconds=random_seconds)
    
    return {
        'merchant_id': next_merchant_id,
        'account_name': f"user_{next_merchant_id}",
        'merchant_name': merchant_name,
        'short_name': merchant_name[:20],
        'user_type': 2,
        'merchant_type': 2,
        'contact_name': contact_name,
        'phone': phone,
        'channel_id': 0,
        'address': f"{merchant_name}附近",
        'province_id': 0,
        'province_name': '',
        'city_id': 0,
        'city_name': '',
        'area_id': 0,
        'area_name': '',
        'lng': 0.0,
        'lat': 0.0,
        'shop_photo': '',
        'business_hours': '',
        'parent_merchant_id': 0,
        'parent_merchant_name': '',
        'svr_merchant_id': 0,
        'settle_merchant_name': merchant_name,
        'svr_merchant_name': '',
        'created_by': f'admin_wxz_{year}',
        'created_date': random_date,
        'updated_by': f'audio_wxz_{year}',
        'updated_date': random_date,
        'deleted_flag': 'N',
        'batch': year
    }

def insert_merchant_into_target(target_engine, merchant_data):
    # 目标表允许的字段列表
    target_columns = {
        'id', 'merchant_id', 'account_name', 'merchant_name', 'short_name',
        'user_type', 'merchant_type', 'contact_name', 'phone', 'channel_id',
        'address', 'province_id', 'province_name', 'city_id', 'city_name',
        'area_id', 'area_name', 'lng', 'lat', 'shop_photo', 'business_hours',
        'parent_merchant_id', 'parent_merchant_name', 'svr_merchant_id',
        'settle_merchant_name', 'svr_merchant_name', 'created_by',
        'created_date', 'updated_by', 'updated_date', 'deleted_flag', 'batch'
    }

    if 'id' in merchant_data:
        del merchant_data['id']
        
    # 移除目标表中不存在的字段,防止报错
    keys_to_remove = [k for k in merchant_data.keys() if k not in target_columns]
    for k in keys_to_remove:
        del merchant_data[k]

    keys = list(merchant_data.keys())
    columns = ', '.join([f"`{k}`" for k in keys])
    placeholders = ', '.join([f":{k}" for k in keys])
    
    sql = f"INSERT INTO dj_system_merchant ({columns}) VALUES ({placeholders})"
    
    try:
        with target_engine.begin() as conn:
            conn.execute(text(sql), merchant_data)
        return True
    except Exception as e:
        st.error(f"Failed to insert merchant {merchant_data.get('merchant_name')}: {e}")
        return False
# 同步门店数据结束

def update_dj_car_shop_warning(target_engine, year):
    """
    更新 dj_car_shop_warning 表里的数据,保证逻辑:
    每个月的数量要比上个月的数量要少一些,通过删除一些数据进行保证。
    具体策略:
    1. 统计该年份每个月的数据量。
    2. 从1月到12月遍历,如果当前月(N月)的数量大于或等于上个月(N-1月)的数量,
       则计算需要删除的数量 = 当前月数量 - 上个月数量 + 一个随机的小量(例如1-10%,或者直接减去一个固定值,这里简单起见,保证比上月少5%左右)。
       公式:目标数量 = 上个月数量 * 0.95 (向下取整)
       需要删除数量 = 当前月数量 - 目标数量
    3. 随机删除当前月的对应数量的数据。
    """
    st.info(f"正在调整 {year} 年 dj_car_shop_warning 各月数据量,确保逐月递减...")
    try:
        with target_engine.begin() as conn:
            # 统计每个月的数据量(包括上一年的12月,作为当年1月的对比基准)
            sql_count = f"""
            SELECT YEAR(created_date) as year, MONTH(created_date) as month, COUNT(1) as cnt 
            FROM dj_car_shop_warning 
            WHERE (YEAR(created_date) = {year}) OR (YEAR(created_date) = {year - 1} AND MONTH(created_date) = 12)
            GROUP BY YEAR(created_date), MONTH(created_date) 
            ORDER BY year, month
            """
            result = conn.execute(text(sql_count)).fetchall()
            
            if not result:
                st.write(f"  {year} 年及其前一年12月没有 dj_car_shop_warning 数据,无需调整。")
                return

            # 解析结果:(year, month) -> count
            month_counts = {(row[0], row[1]): row[2] for row in result}
            
            # 准备待处理月份列表,包含上一年12月,以及当年的1到12月
            # months_data 中的结构:[(year, month, count), ...]
            months_data = []
            
            # 先加入上一年12月的数据作为初始基准
            prev_year_dec_cnt = month_counts.get((year - 1, 12), 0)
            months_data.append({'year': year - 1, 'month': 12, 'cnt': prev_year_dec_cnt})
            
            # 加入当年的1-12月数据
            for m in range(1, 13):
                months_data.append({'year': year, 'month': m, 'cnt': month_counts.get((year, m), 0)})

            # 从索引1开始遍历调整(即从当年的1月开始,与它前面的一个元素对比)
            import random
            total_deleted = 0
            
            for i in range(1, 13): # i=1对应当年1月, i=12对应当年12月
                prev_month_cnt = months_data[i-1]['cnt']
                curr_month_cnt = months_data[i]['cnt']
                curr_year = months_data[i]['year']
                curr_month = months_data[i]['month']
                
                if prev_month_cnt == 0:
                    # 如果上个月是0,为了保证递减,这个月也必须是0
                    target_cnt = 0
                else:
                    # 如果当前月 >= 上个月,或者需要强制递减
                    if curr_month_cnt >= prev_month_cnt:
                        # 目标数量设为上个月的 90%~98% 之间的一个随机比例
                        ratio = random.uniform(0.90, 0.98)
                        target_cnt = int(prev_month_cnt * ratio)
                    else:
                        target_cnt = curr_month_cnt
                
                # 如果当前数量大于目标数量,执行删除
                if curr_month_cnt > target_cnt:
                    delete_cnt = curr_month_cnt - target_cnt
                    
                    st.write(f"  - {curr_year}年{curr_month}月: 原始数量 {curr_month_cnt}, 目标数量 {target_cnt}, 需要删除 {delete_cnt} 条")
                    
                    # 获取该月所有记录的 ID
                    sql_get_ids = f"""
                    SELECT id FROM dj_car_shop_warning 
                    WHERE YEAR(created_date) = {curr_year} AND MONTH(created_date) = {curr_month}
                    """
                    ids_result = conn.execute(text(sql_get_ids)).fetchall()
                    all_ids = [r[0] for r in ids_result]
                    
                    # 随机选取需要删除的 ID
                    if delete_cnt > len(all_ids):
                        delete_cnt = len(all_ids)
                    
                    ids_to_delete = random.sample(all_ids, delete_cnt)
                    
                    # 分批删除,避免 IN 子句过长
                    batch_size = 1000
                    for j in range(0, len(ids_to_delete), batch_size):
                        batch_ids = ids_to_delete[j:j+batch_size]
                        if batch_ids:
                            # 格式化 IN 子句
                            ids_str = ",".join(map(str, batch_ids))
                            sql_delete = f"DELETE FROM dj_car_shop_warning WHERE id IN ({ids_str})"
                            conn.execute(text(sql_delete))
                    
                    total_deleted += delete_cnt
                    months_data[i]['cnt'] = target_cnt # 更新当前月的数量为目标数量,供下个月比较
            
            if total_deleted > 0:
                st.success(f"调整完成!共删除了 {total_deleted} 条记录,已保证逐月递减逻辑。")
            else:
                st.write("各月数据量已符合逐月递减逻辑,无需删除。")

    except Exception as e:
        st.error(f"调整 dj_car_shop_warning 各月数据量失败: {e}")
        import traceback
        st.code(traceback.format_exc())

# 同步外部额外数据
# def sync_extra_data(target_engine,source_engine, year):
#     sync_merchants(target_engine,source_engine,year)
#     sync_car_maintain(dataFrom="DJ",fromTime=f"{year}-01-01",endTime=f"{year+1}-01-01", year=year)
#     sync_car_shop_warning(dataFrom="DJ",fromTime=f"{year}-01-01",endTime=f"{year+1}-01-01", year=year)
#     sync_ddh_rescue_event(fromTime=f"{year}-01-01",endTime=f"{year+1}-01-01", year=year)


def get_table_max_time(engine, table_name, time_col):
    """获取表中指定时间字段的最大值,用于展示同步进度"""
    try:
        with engine.connect() as conn:
            sql_str = f"SELECT MAX({time_col}) FROM {table_name}"
            result = conn.execute(text(sql_str)).scalar()
            return str(result) if result else "无数据"
    except Exception as e:
        return "未同步/不存在"

def show():


    # Year Selection
    current_year = datetime.datetime.now().year
    years = [current_year, current_year - 1, current_year - 2, 2021, 2020]
    selected_year = st.selectbox("选择年份", years, index=0)

    st.divider()
    st.subheader("同步到研发数据库 (glsx_biz_data)")
    st.info("说明:此部分将业务数据(救援、发货结算门店)同步到研发侧数据库。")
    st.markdown("""
    **同步列表:**
    1. 救援事件表 `ddh_rescue_event`
    2. 车辆保养表 `dj_car_maintain`
    3. 车辆门店预警表 `dj_car_shop_warning`
    4. 发货结算门店表 `dj_system_merchant`
    """)

    # 获取当前各表最新时间状态
    try:
        biz_db_url = f"mysql+pymysql://{g_biz_dbcfg['user']}:{g_biz_dbcfg['passwd']}@{g_biz_dbcfg['host']}:{g_biz_dbcfg['port']}/{g_biz_dbcfg['db']}?charset={g_biz_dbcfg['charset']}"
        biz_engine = create_engine(biz_db_url)
        
        data_status = [
            {"表名": "救援事件表 (ddh_rescue_event)", "时间字段": "created_date", "最新时间": get_table_max_time(biz_engine, "ddh_rescue_event", "EVENT_DATE")},
            {"表名": "车辆保养表 (dj_car_maintain)", "时间字段": "created_date", "最新时间": get_table_max_time(biz_engine, "dj_car_maintain", "created_date")},
            {"表名": "车辆门店预警表 (dj_car_shop_warning)", "时间字段": "created_date", "最新时间": get_table_max_time(biz_engine, "dj_car_shop_warning", "created_date")},
            {"表名": "发货结算门店表 (dj_system_merchant)", "时间字段": "created_date", "最新时间": get_table_max_time(biz_engine, "dj_system_merchant", "created_date")},
        ]
        
        st.info("💡 **数据更新状态参考:** 下表展示了研发数据库中的最新业务时间。如果显示的最新时间落后于预期(例如源数据已有更新),建议执行‘同步’或‘重跑’操作。")
        st.dataframe(pd.DataFrame(data_status))
        
    except Exception as e:
        st.warning(f"无法获取数据状态: {e}")

    st.write("**单独同步操作:**")
    cols_biz = st.columns(4)
    
    with cols_biz[0]:
        if st.button("同步 ddh_rescue_event", key="btn_biz_ddh_rescue_event"):
            from_time = f"{selected_year}-01-01"
            end_time = f"{selected_year+1}-01-01"
            try:
                with st.spinner(f"正在同步 ddh_rescue_event..."):
                    sync_ddh_rescue_event(fromTime=from_time, endTime=end_time, year=selected_year)
                st.success("✅ ddh_rescue_event 同步完成!")
            except Exception as e:
                st.error(f"同步失败: {e}")

    with cols_biz[1]:
        if st.button("同步 dj_car_maintain", key="btn_biz_dj_car_maintain"):
            from_time = f"{selected_year}-01-01"
            end_time = f"{selected_year+1}-01-01"
            try:
                with st.spinner(f"正在同步 dj_car_maintain..."):
                    sync_car_maintain(dataFrom="DJ", fromTime=from_time, endTime=end_time, year=selected_year)
                st.success("✅ dj_car_maintain 同步完成!")
            except Exception as e:
                st.error(f"同步失败: {e}")

    with cols_biz[2]:
        if st.button("同步 dj_car_shop_warning", key="btn_biz_dj_car_shop_warning"):
            from_time = f"{selected_year}-01-01"
            end_time = f"{selected_year+1}-01-01"
            try:
                with st.spinner(f"正在同步 dj_car_shop_warning..."):
                    target_url = f"mysql+pymysql://{g_biz_dbcfg['user']}:{g_biz_dbcfg['passwd']}@{g_biz_dbcfg['host']}:{g_biz_dbcfg['port']}/{g_biz_dbcfg['db']}?charset={g_biz_dbcfg['charset']}"
                    target_engine = create_engine(target_url)
                    sync_car_shop_warning(dataFrom="DJ", fromTime=from_time, endTime=end_time, year=selected_year)
                    update_dj_car_shop_warning(target_engine, selected_year)
                st.success("✅ dj_car_shop_warning 同步完成!")
            except Exception as e:
                st.error(f"同步失败: {e}")

    with cols_biz[3]:
        if st.button("同步 dj_system_merchant", key="btn_biz_dj_system_merchant"):
            try:
                with st.spinner(f"正在同步 dj_system_merchant..."):
                    target_url = f"mysql+pymysql://{g_biz_dbcfg['user']}:{g_biz_dbcfg['passwd']}@{g_biz_dbcfg['host']}:{g_biz_dbcfg['port']}/{g_biz_dbcfg['db']}?charset={g_biz_dbcfg['charset']}"
                    dj_url = f"mysql+pymysql://{g_gldj_dbcfg['user']}:{g_gldj_dbcfg['passwd']}@{g_gldj_dbcfg['host']}:{g_gldj_dbcfg['port']}/{g_gldj_dbcfg['db']}?charset={g_gldj_dbcfg['charset']}"
                    target_engine = create_engine(target_url)
                    dj_engine = create_engine(dj_url)
                    sync_merchants(target_engine, dj_engine, selected_year)
                st.success("✅ dj_system_merchant 同步完成!")
            except Exception as e:
                st.error(f"同步失败: {e}")

    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("全部同步业务数据", type="primary"):
            config = get_config()
            if config:
                st.info(f"开始同步 {selected_year} 业务数据 (增量模式)...")
                from_time = f"{selected_year}-01-01"
                end_time = f"{selected_year+1}-01-01"
                try:
                    with st.spinner(f"正在同步 {selected_year} 业务数据..."):
                        # 0. 准备数据库连接 (For sync_merchants)
                        target_url = f"mysql+pymysql://{g_biz_dbcfg['user']}:{g_biz_dbcfg['passwd']}@{g_biz_dbcfg['host']}:{g_biz_dbcfg['port']}/{g_biz_dbcfg['db']}?charset={g_biz_dbcfg['charset']}"
                        dj_url = f"mysql+pymysql://{g_gldj_dbcfg['user']}:{g_gldj_dbcfg['passwd']}@{g_gldj_dbcfg['host']}:{g_gldj_dbcfg['port']}/{g_gldj_dbcfg['db']}?charset={g_gldj_dbcfg['charset']}"

                        target_engine = create_engine(target_url)
                        dj_engine = create_engine(dj_url)

                        # 1. 救援事件表 (Always overwrites if year is passed, due to current implementation)
                        st.write("正在同步 ddh_rescue_event ...")
                        sync_ddh_rescue_event(fromTime=from_time, endTime=end_time, year=selected_year)
                        
                        # 2. 车辆保养表 (Append mode)
                        st.write("正在同步 dj_car_maintain (DJ) ...")
                        sync_car_maintain(dataFrom="DJ", fromTime=from_time, endTime=end_time, year=selected_year)
                        
                        # 3. 车辆门店预警表 (Append mode)
                        st.write("正在同步 dj_car_shop_warning (DJ) ...")
                        sync_car_shop_warning(dataFrom="DJ", fromTime=from_time, endTime=end_time, year=selected_year)
                        #新增函数,用于更新dj_car_shop_warning表里面的数据,要保证一个逻辑,每个月的数量要比上个月的数量要少一些,通过删除一些数据进行保证
                        update_dj_car_shop_warning(target_engine, selected_year)

                        # 4. 发货结算门店表 (Incremental: clear_batch=False)
                        st.write("正在同步 dj_system_merchant (DJ) ...")
                        sync_merchants(target_engine, dj_engine, selected_year)

                    st.success(f"✅ {selected_year} 业务数据同步全部完成!")
                except Exception as e:
                    st.error(f"执行过程中出错: {e}")
                    import traceback
                    st.code(traceback.format_exc())

    st.divider()
    st.subheader("同步到对外审计库 (glsx_data)")
    st.info("将嘀加业务数据同步到外部审计数据库 (glsx_data)。")
    st.info("""
    **需要完成如下任务**
    1. 同步数据到对外审计库 glsx_data
    2. 需要确认给到审计的脚本
    3. 需要自己先推导一遍输出结果,看是否和基础数据一致
    """)
    st.markdown(f"""
    **同步任务列表:**
    1. 同步本年度应收单表 `dj_{selected_year}_settlment_order`
    2. 生成本年度发货设备明细表 `dj_{selected_year}_basic_device_info`
    3. 生成历史发货设备明细表 `dj_basic_device_info`
    4. 重算结算发货设备明细表 `dj_device_details`
    5. 生成历史退货设备明细表 `dj_device_details_return`
    6. 同步本年度退货结算单 `dj_{selected_year}_settle_details_return`
    """)
    
    config = get_config()
    if not config:
        st.error("无法加载配置")
        return

    db_conf = config.get('database', {})
    src_conf = db_conf.get('dijia_db')
    dst_conf = db_conf.get('glsx_data_db')
    
    if not src_conf or not dst_conf:
        st.error("数据库配置缺失 (dijia_db 或 glsx_data_db),请检查 config.yaml")
        return
        
    tasks_audit = [
        (f"dj_{selected_year}_settlment_order", f"dj_{selected_year}_settlment_order", "1. 同步本年度应收单表"),
        (f"dj_{selected_year}_basic_device_info", f"dj_{selected_year}_basic_device_info", "2. 生成本年度发货设备明细表"),
        ("dj_basic_device_info", "dj_basic_device_info", "3. 生成历史发货设备明细表"),
        ("dj_device_details", "dj_device_details", "4. 重算结算发货设备明细表"),
        ("dj_device_details_return", "dj_device_details_return", "5. 生成历史退货设备明细表"),
        (f"dj_{selected_year}_settle_details_return", f"dj_{selected_year}_settle_details_return", "6. 同步本年度退货结算单"),
    ]

    # Individual sync buttons for Audit DB
    st.write("**单独同步操作:**")
    cols_audit = st.columns(3)
    for i, (src, dst, desc) in enumerate(tasks_audit):
        with cols_audit[i % 3]:
            if st.button(f"同步 {src}", key=f"btn_audit_{src}"):
                 try:
                    with st.spinner(f"正在同步 {src}..."):
                        src_engine = create_engine(get_db_url(src_conf))
                        dst_engine = create_engine(get_db_url(dst_conf))
                        if sync_table(src_engine, dst_engine, src, dst):
                            st.success(f"✅ {src} 同步成功!")
                        else:
                            st.error(f"❌ {src} 同步失败!")
                 except Exception as e:
                    st.error(f"执行出错: {e}")

    if st.button("开始全部同步 (对外审计库)", type="primary"):
        try:
            with st.spinner("正在连接数据库..."):
                src_engine = create_engine(get_db_url(src_conf))
                dst_engine = create_engine(get_db_url(dst_conf))
            
            progress_bar = st.progress(0)
            status_text = st.empty()
            success_count = 0
            total_tasks = len(tasks_audit)

            for i, (src_table, dst_table, _) in enumerate(tasks_audit):
                current_idx = i + 1
                status_text.text(f"正在处理 {current_idx}/{total_tasks}: {src_table} ...")
                if sync_table(src_engine, dst_engine, src_table, dst_table):
                    success_count += 1
                else:
                    st.error(f"同步 {src_table} 失败,流程终止。")
                    break
                progress_bar.progress(current_idx / total_tasks)
                
            if success_count == total_tasks:
                status_text.text("同步完成!")
                st.success(f"✅ {selected_year} 年数据同步全部完成!")
                
        except Exception as e:
            st.error(f"执行过程中出错: {e}")
            import traceback
            st.code(traceback.format_exc())

    st.divider()
    st.subheader("同步额外信息到对外审计库 (glsx_data)")
    st.info("将嘀加额外业务数据同步到外部审计数据库 (glsx_data)。")
    st.markdown("""
    **同步任务列表:**
    1. 救援事件表 `ddh_rescue_event`
    2. 车辆保养表 `dj_car_maintain`
    3. 车辆门店预警表 `dj_car_shop_warning`
    4. 发货结算门店表 `dj_system_merchant`
    """)
    
    tasks_extra = [
        ("ddh_rescue_event", "ddh_rescue_event", "1. 救援事件表"),
        ("dj_car_maintain", "dj_car_maintain", "2. 车辆保养表"),
        ("dj_car_shop_warning", "dj_car_shop_warning", "3. 车辆门店预警表"),
        ("dj_system_merchant", "dj_system_merchant", "4. 发货结算门店表"),
    ]

    # Individual sync buttons for Extra Info
    st.write("**单独同步操作:**")
    cols_extra = st.columns(2)
    for i, (src, dst, desc) in enumerate(tasks_extra):
        with cols_extra[i % 2]:
             if st.button(f"同步 {src}", key=f"btn_extra_{src}"):
                 try:
                    with st.spinner(f"正在同步 {src}..."):
                        src_engine = create_engine(get_db_url(src_conf))
                        dst_engine = create_engine(get_db_url(dst_conf))
                        if sync_extra_info_table(src_engine, dst_engine, src, dst, selected_year):
                            st.success(f"✅ {src} 同步成功!")
                        else:
                            st.error(f"❌ {src} 同步失败!")
                 except Exception as e:
                    st.error(f"执行出错: {e}")

    if st.button("开始全部同步 (额外信息)", type="primary"):
        try:
            with st.spinner("正在连接数据库..."):
                src_engine = create_engine(get_db_url(src_conf))
                dst_engine = create_engine(get_db_url(dst_conf))
            
            progress_bar = st.progress(0)
            status_text = st.empty()
            success_count = 0
            total_tasks = len(tasks_extra)

            for i, (src_table, dst_table, _) in enumerate(tasks_extra):
                current_idx = i + 1
                status_text.text(f"正在处理 {current_idx}/{total_tasks}: {src_table} ...")
                if sync_extra_info_table(src_engine, dst_engine, src_table, dst_table, selected_year):
                    success_count += 1
                else:
                    st.error(f"同步 {src_table} 失败,流程终止。")
                    break
                progress_bar.progress(current_idx / total_tasks)
                
            if success_count == total_tasks:
                status_text.text("同步完成!")
                st.success(f"✅ 额外信息数据同步全部完成!")
                
        except Exception as e:
            st.error(f"执行过程中出错: {e}")
            import traceback
            st.code(traceback.format_exc())