audit_calculation.py 40.9 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
#!/usr/bin/python
import pandas as pd
import pymysql
# from sqlalchemy import create_engine
import os
import yaml
from pandas import DataFrame
import datetime
import numpy as np
import re
from sqlalchemy import create_engine, engine, text
import datetime

import random
from dateutil.relativedelta import relativedelta
import calendar

def get_config():
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 向上寻找直到找到 project 目录,这里假设结构是 fixed: project/3-amortization_process/edun
    # 所以 config.yaml 在 ../../../config.yaml
    base_dir = os.path.dirname(os.path.dirname(os.path.dirname(current_dir)))
    config_path = os.path.join(base_dir, "config.yaml")
    
    # 如果找不到,尝试直接在上级目录找(兼容调试)
    if not os.path.exists(config_path):
        # 尝试 project 根目录
        base_dir = os.path.dirname(os.path.dirname(current_dir))
        config_path = os.path.join(base_dir, "config.yaml")

    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 fill_device_result_data(from_table, time_limit, table_name):
    query_sql = "select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,device_period,settle_merchant,settle_order,settle_time" \
                ",device_price,0 as install_price,type as from_type,classid,'" + from_table + "' as  from_table from d_eshield_device_details_new_place " \
                                                                                              " WHERE " + time_limit + " "

    df = pd.read_sql(query_sql, con=engine)
    df.to_sql(name=table_name, con=engine, if_exists="append", index=False, chunksize=1000)


'''
生成服务结果表
'''


def fill_service_result_data(from_table, time_limit, table_name):
    query_sql = """
        select A.sn,B.device_type,B.delivery_time,B.delivery_merchant,B.active_time,
        B.active_merchant,A.period as service_period,A.customer as settle_merchant,
        '' as settle_order,A.settle_date as settle_time,price as service_price,A.type as from_type,
        B.classid,'{0}' as from_table from  ( 
            SELECT * FROM device_detail.d_eshield_service_details_new_place
            WHERE {1} )  A
            left join
            device_detail.d_eshield_device_details_new_place  B on A.sn=B.sn and A.settle_date = B.settle_time
        """.format(from_table, time_limit)
    df = pd.read_sql(query_sql, con=engine)
    df.to_sql(name=table_name, con=engine, if_exists="append", index=False, chunksize=1000)


def fill_install_price(engine):
    sql1 = "SELECT customer,business_date,valuation_quantity,income " \
           " FROM t_invoice_for_accounts_receivable where business_date " \
           ">'2021-00-00' and business_date " \
           "<'2022-00-00' and product_type  ='安装' and valuation_quantity >0 and income >0 order by substring(business_date,1,7),customer"
    sql2 = " select * from d_eshield_device_details_2021_copy "
    df1 = pd.read_sql(sql1, con=engine)
    df1['business_date'] = df1['business_date'].astype(str).str.slice(stop=7)
    df2 = pd.read_sql(sql2, con=engine)
    df2['install_price'] = 0
    df2['settle_time'] = df2['settle_time'].astype(str).str.slice(stop=7)
    all_df = None
    temp_df = None
    current_index = 0
    last_merchant = None
    last_time = None
    print(df1)

    for index, row in df1.iterrows():
        count = int(row['valuation_quantity'])
        # print(row)
        # 在这里对每一行进行操作
        print(index)
        print(row['customer'])
        merchant_df = df2[
            (df2['settle_merchant'] == row['customer']) & (df2['settle_time'] == row['business_date'])]
        if not (last_merchant == row['customer'] and last_time == row['business_date']):
            current_index = 0

        min_index = merchant_df.index.min()
        # 需要取值大于当前的 current_index 的数据
        print("当前index的值为:" + str(current_index))
        # 此处代码会导致少计算index为的0的数据
        merchant_df = merchant_df.loc[current_index + 1:min_index + count - 1]
        # print(merchant_df)
        print("当前商户的明细数量为:" + str(merchant_df.shape[0]))
        print("当前商户为:" + row['customer'] + "\r\n当前月份:" + row['business_date'] + "\r\n当前数量为:" + str(
            row['valuation_quantity']))
        print(" 当前未匹配数量:" + str(int(row['valuation_quantity']) - merchant_df.shape[0]))

        if merchant_df.shape[0] > 0 and int(row['valuation_quantity']) > 0:
            # 遍历每条明细数据
            for index01, row01 in merchant_df.iterrows():
                # 按照数量给 install_price 赋值
                # for i in range(int(row['valuation_quantity'])):
                merchant_df.loc[index01, 'install_price'] = row['income'] / row['valuation_quantity']
                count = count - 1
                if count == 0:
                    current_index = index01
                    break
                # for i in range(merchant_df.shape[0]):
        last_merchant = row['customer']
        last_time = row['business_date']
        print(merchant_df[['settle_time', 'settle_merchant', 'install_price']])
        merchant_df.to_sql(name="new_table", con=engine, if_exists="append", index=False, chunksize=1000)


def fill_install_price_new(engine):
    update_table = "d_eshield_device_details_2022"
    sql1 = "SELECT customer,business_date,valuation_quantity,income " \
           " FROM t_invoice_for_accounts_receivable where business_date " \
           ">'2022-00-00' and business_date " \
           "<'2023-00-00' and product_type  ='安装' and valuation_quantity >0 and income >0 order by substring(" \
           "business_date,1,7),customer "
    sql2 = " select * from " + update_table + " "
    # sql1 = "SELECT customer,business_date,valuation_quantity,income " \
    #        " FROM t_invoice_for_accounts_receivable where business_date " \
    #        ">'2021-00-00' and business_date " \
    #        "<'2022-00-00' and product_type  ='安装' and valuation_quantity >0 and income >0 order by substring(" \
    #        "business_date,1,7),customer "
    # sql2 = " select * from "+update_table+" "
    df1 = pd.read_sql(sql1, con=engine)
    df1['business_date'] = df1['business_date'].astype(str).str.slice(stop=7)
    df2 = pd.read_sql(sql2, con=engine)
    df2['install_price'] = 0
    df2['settle_time'] = df2['settle_time'].astype(str).str.slice(stop=7)

    # 连接数据库
    conn = pymysql.connect(host='192.168.5.5', port=3310, user='biz_device_detail', password='M6khz3CQ',
                           db='device_detail')
    # 创建游标对象
    cursor = conn.cursor()

    for index, row in df1.iterrows():
        # 每条数据去 d_eshield_device_details_2021_copy 中找同一个商户,同一个月份的 设备并且安装价格为0的 更新为  row['income'] / row[
        # 'valuation_quantity']
        price = row['income'] / row['valuation_quantity']

        # 每次都要查询 当前商户和时间 的install_price为0的数量,如果小于当前 valuation_quantity ,则将 settle_merchant,substring(settle_time,1,7),valuation_quantity-install_price 为0的数量保存
        unfortable_sql = " select count(*) as count from " + update_table + "  where settle_merchant='" + row[
            'customer'] + "' and substring(settle_time,1,7) = '" + row['business_date'] + "'and install_price =0"
        unfortable_df = pd.read_sql(unfortable_sql, engine)

        un_find_count = int(unfortable_df['count'])
        if un_find_count < int(row['valuation_quantity']):
            data_list = [[row['customer'], row['business_date'], int(row['valuation_quantity']) - un_find_count, price]]
            un_find_df = pd.DataFrame(data_list, columns=['settle_merchant', 'settle_month', 'unfindcount', "price"])
            un_find_df.to_sql(name="unfind_table", con=engine, if_exists="append", index=False, chunksize=1000)

        update_query = "update " + update_table + " set install_price = " + str(
            price) + " where settle_merchant='" + row['customer'] + "' and substring(settle_time,1,7) = '" + row[
                           'business_date'] + "'and install_price=0 limit " + str(int(row['valuation_quantity'])) + ""
        print("当前执行的sql为:" + update_query)
        print("当前商户为:" + row['customer'] + "\r\n当前月份:" + row['business_date'] + "\r\n当前数量为:" + str(
            row['valuation_quantity']))
        cursor.execute(update_query)

        # # 执行SQL语句
        # sql = "UPDATE mytable SET column1 = 'new_value' WHERE id = 1"
        # cursor.execute(sql)

        # 提交事务
        conn.commit()

    # 关闭游标和连接
    cursor.close()
    conn.close()


def fill_unfind_install_price(engine):
    update_table = "d_eshield_device_details_2022"
    sql1 = "SELECT * from unfind_table "
    sql2 = " select * from " + update_table + " "
    df1 = pd.read_sql(sql1, con=engine)
    df2 = pd.read_sql(sql2, con=engine)
    df2['settle_time'] = df2['settle_time'].astype(str).str.slice(stop=7)

    # 连接数据库
    conn = pymysql.connect(host='192.168.5.5', port=3310, user='biz_device_detail', password='M6khz3CQ',
                           db='device_detail')
    # 创建游标对象
    cursor = conn.cursor()

    for index, row in df1.iterrows():
        update_query = "update " + update_table + " set install_price = " + str(
            row['price']) + " where substring(settle_time,1,7) = '" + row[
                           'settle_month'] + "'and install_price=0 limit " + str(int(row['unfindcount'])) + ""
        print("当前执行的sql为:" + update_query)
        print("当前月份:" + row['settle_month'] + "\r\n当前数量为:" + str(
            row['unfindcount']))
        cursor.execute(update_query)

        # 提交事务
        conn.commit()

    # 关闭游标和连接
    cursor.close()
    conn.close()


# 更新glsx_data表中2021年2022年的安装数据
def fill_out_install_price(engine1, raw_table_name, update_table_name):
    raw_table = raw_table_name
    update_table = update_table_name
    sql1 = " select * from " + raw_table + " "
    df1 = pd.read_sql(sql1, con=engine1)

    # 连接数据库
    conn = pymysql.connect(host='192.168.5.5', port=3310, user='biz_device_detail', password='M6khz3CQ',
                           db='glsx_data')
    # 创建游标对象
    cursor = conn.cursor()

    for index, row in df1.iterrows():
        update_query = "update " + update_table + " set install_price = " + str(
            row['install_price']) + " where id= " + str(row['id'])
        print("当前执行的sql为:" + update_query)
        cursor.execute(update_query)

        # 提交事务
        conn.commit()

    # 关闭游标和连接
    cursor.close()
    conn.close()


# 补充仲利国际的激活时间和激活商户(仲利国际迁移到了新E盾,新的库)
def fill_zl_active_info():
    # 读取d_eshield_device_details_2022表和t_vehicle_device表的数据
    d_eshield_device_details_2022 = pd.read_sql(
        'SELECT sn FROM d_eshield_service_details_2022 where active_time is null', engine)
    t_vehicle_device = pd.read_sql('SELECT sn, created_date as active_time FROM t_vehicle_device', newsheid_engine)

    # 合并两个数据帧,获取两个表sn相同的数据
    merged_data = pd.merge(d_eshield_device_details_2022, t_vehicle_device, on='sn', how='inner')

    # 写入临时表中存储
    merged_data.to_sql("space_table_tmp", engine, if_exists="replace", index=False)

    update_sql = " UPDATE d_eshield_service_details_2022 D, space_table_tmp DF SET D.active_time = DF.active_time WHERE D.sn = DF.sn; "
    print("当前执行的ql为:" + update_sql)
    with engine.connect() as con:
        con.execute(update_sql)


# 激活硬件数据调整
def active_data_adjustment(table_name, sub):
    # 激活时间需要在结算时间之后1-6个月随机
    random_number = random.randint(1, 6)
    # 读取指定表的数据
    adjustment_content = pd.read_sql(
        "SELECT id,sn,active_time,active_time as raw_active_time,settle_time FROM " + table_name + " where datediff(settle_time,active_time) >0 and from_type='2'  ",
        engine)

    # 将每条数据的 settle_time 延后随机的月份
    adjustment_content['active_time'] = adjustment_content['settle_time'].apply(shift_month)

    # 写入临时表中存储
    temp_table = "adjustment_table_tmp_tmp" + sub
    adjustment_content.to_sql(temp_table, engine, if_exists="replace", index=False)

    update_sql = " UPDATE " + table_name + " D, " + temp_table + " DF SET D.active_time = DF.active_time WHERE D.id = DF.id; "
    print("当前执行的ql为:" + update_sql)
    with engine.connect() as con:
        con.execute(update_sql)


# 激活服务数据调整
def active_data_adjustment_sub(service_name, device_name):
    update_sql = " UPDATE " + service_name + " D, " + device_name + " DF SET D.active_time = DF.active_time WHERE D.sn = DF.sn; "
    print("当前执行的ql为:" + update_sql)
    with engine.connect() as con:
        con.execute(update_sql)


# 定义一个函数来将日期向后推迟随机的月份
def shift_month(date):
    # 生成一个 1 到 6 之间的随机整数
    shift = random.randint(1, 6)
    # 使用 dateutil 库将日期向后推迟随机的月份
    new_date = date + relativedelta(months=shift)
    return new_date


# 生成备份表
def create_bak_table(table_name, bak_name, engine):
    query_sql = "select * from " + table_name + ""

    df = pd.read_sql(query_sql, con=engine)
    df.to_sql(name=bak_name, con=engine, if_exists="replace", index=False, chunksize=1000)


# 将本地CSV导入到数据库
def load_csv_to_databse(path, sheet_name, columns, table_name, engine):
    df = pd.read_excel(path, sheet_name=sheet_name)
    df.columns = columns
    df.to_sql(name=table_name, con=engine, if_exists='append', index=False)


# 调整分摊期限
def fill_period(table_name, financial_table, engine, sub):
    # sql = '''
    #         select *,settle_merchant as new_settle_merchant from d_eshield_device_details_2020_copy A left join financial_data B
    #       on A.settle_merchant = B.customer_name
    #       and substring(A.settle_time,1,7) = substring(B.start_billing_month,1,7) where A.settle_merchant not like '%%广汇%%' and A.settle_merchant not like '%%汇通%%'
    #        union all
    #        select *,'广汇' as new_settle_merchant from d_eshield_device_details_2020_copy A left join financial_data B
    #       on substring(A.settle_time,1,7) = substring(B.start_billing_month,1,7) where A.settle_merchant  like '%%广汇%%' or A.settle_merchant  like '%%汇通%%'
    #       '''
    # df1 = pd.read_sql(sql,con=engine)
    # df1.to_sql(name="fin_tmp", con=engine, if_exists="replace", index=False, chunksize=1000)
    query_sql = "select * from " + table_name + " "
    # 替换所有汇通数据为广汇
    df1 = pd.read_sql(query_sql, con=engine)
    df1['settle_merchant_new'] = df1['settle_merchant'].apply(
        lambda x: '广汇' if '汇通' in str(x) or '广汇' in str(x) or '宝信' in str(x) else x)
    query_sql02 = "select customer_name,substring(start_billing_month,1,7) as start_billing_month,service_period,quantity from " + financial_table + " where quantity > 0 group by customer_name,substring(start_billing_month,1,7),service_period"
    # 替换所有汇通数据为广汇
    df2 = pd.read_sql(query_sql02, con=engine)
    df2['customer_name_new'] = df2['customer_name'].apply(
        lambda x: '广汇' if '汇通' in str(x) or '广汇' in str(x) or '宝信' in str(x) else x)

    # 连接数据库
    conn = pymysql.connect(host='192.168.5.5', port=3310, user='biz_device_detail', password='M6khz3CQ',
                           db='device_detail')
    # 创建游标对象
    cursor = conn.cursor()

    # 新增一个标识广汇的字段
    for index, row in df1.iterrows():
        update_query = "update " + table_name + " set settle_merchant_new = '" + str(
            row['settle_merchant_new']) + "' where id = " + str(int(row['id'])) + " "
        print("当前执行的sql为:" + update_query)
        cursor.execute(update_query)

        # 提交事务
        conn.commit()

    for index, row in df2.iterrows():
        # count = int(row['quantity'])
        # for i in range(count):
        # 每条数据
        # merchant_df.loc[index01, 'install_price'] = row['income'] / row['valuation_quantity']
        # merchant_df = merchant_df.loc[current_index + 1:min_index + count - 1]
        update_query = "update " + table_name + " set device_period = " + str(
            row[
                'service_period']) + ",is_set = 'T' where (is_set !='T' or is_set is null) and (settle_merchant not like '%%广汇%%' or settle_merchant not like '%%汇通%%' or settle_merchant not like '%%宝信%%') and substring(settle_time,1,7) = '" + \
                       row[
                           'start_billing_month'] + "' and settle_merchant_new = '" + row[
                           'customer_name_new'] + "'  limit " + str(int(row['quantity'])) + ""
        print("当前执行的sql为:" + update_query)
        print("当前客户:" + row['customer_name_new'] + "\r\n当前月份为:" + str(row['start_billing_month']) + "\r\n当前数量为:" + str(
            row['quantity']))
        cursor.execute(update_query)

        # 提交事务
        conn.commit()

    # 关闭游标和连接
    cursor.close()
    conn.close()

    '''
    UPDATE d_eshield_device_details_2020_copy AS d
    INNER JOIN financial_data AS f
    ON d.settle_merchant = f.customer_name
    AND YEAR(d.settle_time) = YEAR(f.start_billing_month)
    AND MONTH(d.settle_time) = MONTH(f.start_billing_month)
    SET d.device_period = f.service_period
    '''

    # 写入临时表中存储
    # temp_table = "eshied_tmp"+sub
    # df1.to_sql(temp_table, engine, if_exists="replace", index=False)
    # df2.to_sql("fin_tmp", engine, if_exists="replace", index=False)
    #
    # update_sql = " UPDATE "+temp_table+" D, fin_tmp F SET D.device_period = F.service_period WHERE d.settle_merchant = f.customer_name and substring(d.settle_time,1,7) = substring(f.start_billing_month,1,7); "
    # print("当前执行的ql为:" + update_sql)
    # with engine.connect() as con:
    #     con.execute(update_sql)

    # df.to_sql(name=bak_name, con=engine, if_exists="replace", index=False, chunksize=1000)


def calculate_amortization(start_date, end_date, total_amount):
    """计算每年的分摊金额"""
    # 计算总共需要分摊的月份数
    duration_months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month) + 1
    # 计算每年的分摊金额
    yearly_amortization = []
    for i in range(start_date.year, end_date.year + 1):
        if i == start_date.year:
            # 计算第一年的分摊金额
            months_in_first_year = 12 - start_date.month + 1
            yearly_amortization.append(round(total_amount / duration_months * months_in_first_year))
        elif i == end_date.year:
            # 计算最后一年的分摊金额
            months_in_last_year = (end_date - datetime.date(end_date.year, 1, 1)).days // 30 + 1
            yearly_amortization.append(round(total_amount / duration_months * months_in_last_year))
        else:
            # 计算中间年份的分摊金额
            yearly_amortization.append(round(total_amount / duration_months * 12))
    return yearly_amortization


def load_data():
    # 将device_detail中的表导入到glsx_data 中
    raw_table_list = [
        # 'd_eshield_device_details_2014',
        # 'd_eshield_device_details_2015',
        # 'd_eshield_device_details_2016',
        'd_eshield_device_details_2017',
        # 'd_eshield_device_details_2018',
        # 'd_eshield_device_details_2019',
        'd_eshield_device_details_2020_copy'
        # 'd_eshield_device_details_2021_copy',
        # 'd_eshield_device_details_2022',
        # 'd_eshield_service_details_2014',
        # 'd_eshield_service_details_2015',
        # 'd_eshield_service_details_2016',
        # 'd_eshield_service_details_2017',
        # 'd_eshield_service_details_2018',
        # 'd_eshield_service_details_2019',
        # 'd_eshield_service_details_2020_copy',
        # 'd_eshield_service_details_2021_copy',
        # 'd_eshield_service_details_2022'
    ]

    table_list = [
        # 'd_eshield_device_details_2014',
        # 'd_eshield_device_details_2015',
        # 'd_eshield_device_details_2016',
        'd_eshield_device_details_2017',
        # 'd_eshield_device_details_2018',
        # 'd_eshield_device_details_2019',
        'd_eshield_device_details_2020'
        # 'd_eshield_device_details_2021',
        # 'd_eshield_device_details_2022',
        # 'd_eshield_service_details_2014',
        # 'd_eshield_service_details_2015',
        # 'd_eshield_service_details_2016',
        # 'd_eshield_service_details_2017',
        # 'd_eshield_service_details_2018',
        # 'd_eshield_service_details_2019',
        # 'd_eshield_service_details_2020',
        # 'd_eshield_service_details_2021',
        # 'd_eshield_service_details_2022'
    ]
    for i in range(len(table_list)):
        delete_sql = 'truncate table ' + table_list[i] + ''
        with engine01.connect() as con:
            con.execute(delete_sql)
        query_sql = 'select * from ' + raw_table_list[i] + ''
        df = pd.read_sql(query_sql, con=engine)
        df.to_sql(name=table_list[i], con=engine01, if_exists="append", index=False, chunksize=1000)


def load_data_customer(table_name, final_table):
    delete_sql = 'truncate table ' + final_table + ''
    with engine01.connect() as con:
        con.execute(delete_sql)
    query_sql = 'select * from ' + table_name + ''
    df = pd.read_sql(query_sql, con=engine)
    df.to_sql(name=final_table, con=engine01, if_exists="append", index=False, chunksize=1000)


# 调整登录设备
def fill_login_device(table_name, engine, month, out_tab):
    query_sql = "select * from " + table_name + " where login_month='" + month + "' "
    df1 = pd.read_sql(query_sql, con=engine)

    df1 = df1.sample(frac=1).reset_index(drop=True)

    df_count = df1.shape[0]

    rate = [0.03, 0.08, 0.8, 0.08, 0.01]
    df_split_index_01 = int(df_count * 0.03)
    df_split_index_02 = int(df_count * 0.08)
    df_split_index_03 = int(df_count * 0.8)
    df_split_index_04 = int(df_count * 0.08)
    df_split_index_05 = df_count - df_split_index_01 - df_split_index_02 - df_split_index_03 - df_split_index_04

    print("当前月份:" + month + " \n各个区间设备量分配:\n[3-20]==>" + str(df_split_index_01) + "\n(20-40]==>" + str(
        df_split_index_02) +
          " \n(40-80]==>" + str(df_split_index_03) + " \n(80-120]==>" + str(df_split_index_04) +
          " \n(120-150]==>" + str(df_split_index_05))

    print("当前开始索引:" + str(0) + "=== 当前结束索引" + str(df_split_index_01))
    print("当前开始索引:" + str(df_split_index_01) + "=== 当前结束索引" + str(df_split_index_02 + df_split_index_01))
    print("当前开始索引:" + str(df_split_index_02 + df_split_index_01) + "=== 当前结束索引" + str(
        df_split_index_02 + df_split_index_01 + df_split_index_03))
    print("当前开始索引:" + str(df_split_index_02 + df_split_index_01 + df_split_index_03) + "=== 当前结束索引" + str(
        df_split_index_02 + df_split_index_01 + df_split_index_03 + df_split_index_04))
    print("当前开始索引:" + str(
        df_split_index_02 + df_split_index_01 + df_split_index_03 + df_split_index_04) + "=== 当前结束索引" + str(
        df_split_index_02 + df_split_index_01 + df_split_index_03 + df_split_index_04 + df_split_index_05))
    for index in range(df_split_index_01):
        df1.loc[index, 'login_count'] = random.randrange(3, 20)
        print("当前第一阶段index为:" + str(index))
    for index in range(df_split_index_02):
        start_index = index + df_split_index_01
        df1.loc[start_index, 'login_count'] = random.randrange(20, 40)
        print("当前第二阶段index为:" + str(start_index))
    for index in range(df_split_index_03):
        start_index = index + df_split_index_01 + df_split_index_02
        df1.loc[start_index, 'login_count'] = random.randrange(40, 80)
        print("当前第三阶段index为:" + str(start_index))
    for index in range(df_split_index_04):
        start_index = index + df_split_index_01 + df_split_index_02 + df_split_index_03
        df1.loc[start_index, 'login_count'] = random.randrange(80, 120)
        print("当前第四阶段index为:" + str(start_index))
    for index in range(df_split_index_05):
        start_index = index + df_split_index_01 + df_split_index_02 + df_split_index_03 + df_split_index_04
        df1.loc[start_index, 'login_count'] = random.randrange(120, 150)
        print("当前第五阶段index为:" + str(start_index))
    df1.to_sql(out_tab, engine, if_exists="append", index=False)

    # print(df1)

    # # 新增一个标识广汇的字段
    # for index, row in df1.iterrows():
    #     if random.random() < 0.03:
    #         df1.loc[index,'login_count'] = random.randint(3, 20)
    #     elif random.random() < 0.11:
    #         df1.loc[index,'login_count'] = random.randint(20, 40)
    #     elif random.random() < 0.91:
    #         df1.loc[index,'login_count'] = random.randint(40, 80)
    #     elif random.random() < 0.99:
    #         df1.loc[index,'login_count'] = random.randint(80, 120)
    #     else:
    #         df1.loc[index,'login_count'] = random.randint(120, 150)
    #     print("当前index为:"+str(index))
    #     # count = int(row['quantity'])
    #     # for i in range(count):
    #     # 每条数据
    #     # merchant_df.loc[index01, 'install_price'] = row['income'] / row['valuation_quantity']
    #     # merchant_df = merchant_df.loc[current_index + 1:min_index + count - 1]
    # df1.to_sql('login_temptemp', engine, if_exists="replace", index=False)

    # for index, row in df2.iterrows():
    #     # count = int(row['quantity'])
    #     # for i in range(count):
    #     # 每条数据
    #     # merchant_df.loc[index01, 'install_price'] = row['income'] / row['valuation_quantity']
    #     # merchant_df = merchant_df.loc[current_index + 1:min_index + count - 1]
    #     update_query = "update " + table_name + " set device_period = " + str(
    #         row['service_period']) + ",is_set = 'T' where (is_set !='T' or is_set is null) and (settle_merchant not like '%%广汇%%' or settle_merchant not like '%%汇通%%' or settle_merchant not like '%%宝信%%') and substring(settle_time,1,7) = '" + row[
    #                        'start_billing_month'] + "' and settle_merchant_new = '"+row['customer_name_new']+"'  limit " + str(int(row['quantity'])) + ""
    #     print("当前执行的sql为:" + update_query)
    #     print("当前客户:" + row['customer_name_new']+ "\r\n当前月份为:" + str(row['start_billing_month']) + "\r\n当前数量为:" + str(row['quantity']))
    #     cursor.execute(update_query)
    #
    #     # 提交事务
    #     conn.commit()
    #
    #
    # # 关闭游标和连接
    # cursor.close()
    # conn.close()


# 造上点数据
def fill_login_time(table_name, engine, year_month, out_tab, engine2):
    query_sql = "select * from " + table_name + " where login_month='" + year_month + "'and sn in ('2691212724','1620621097','1510927788','2601015378','1590327491','1610517225','2600528795','2600918181','75108032720','1501013479','2600910378','3700401608','1510616128','1610522961','1610526564','1510917096','6200821559','1620316583','1510115398','44100227426','2601105030','44100137489','1610913606','1501229489','44100232042','44100141995','1610113910','1510616432','1611013157','1590924454','1501218195','1620528893','1500814940','1610516224','2600629483','44100221273','1510730244','2600804425') "
    df1 = pd.read_sql(query_sql, con=engine)

    sn_count = 0
    batch_df = None

    for index, row in df1.iterrows():
        count = int(row['login_count'])
        raw_actime = row['active_time']
        sn = row['sn']
        sn_count = sn_count + 1
        actimeTime = str(raw_actime)
        startTime = year_month + "-01 00:00:00"
        start_Time = int(datetime.datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S").timestamp())
        actime_Time = int(datetime.datetime.strptime(actimeTime, "%Y-%m-%d %H:%M:%S").timestamp())

        year = int(year_month.split('-')[0])
        month = int(year_month.split('-')[1])
        last_day = calendar.monthrange(year, month)[1]
        endTime = year_month + "-" + str(last_day) + " 23:59:59"
        end_time = datetime.datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S").timestamp()
        loginCount = count
        print("当前index为:" + str(index))
        # print("当前index为:"+str(index)+"\r\n 当前sn为:"+str(sn)+"\r\n 当前激活时间为:"+actimeTime+"\r\n当前月份结束时间为:"+endTime+"\r\n 当前登录数量为:"+str(count))
        loginTime = list(map(lambda x: datetime.datetime.fromtimestamp(x).strftime("%Y-%m-%d %H:%M:%S"),
                             np.random.randint(max(actime_Time, start_Time), end_time, size=loginCount)))
        sn = [f"" + sn + ""] * loginCount
        df = pd.DataFrame((zip(sn, loginTime)), columns=["sn", "login_time"], )
        if sn_count <= 5000:
            batch_df = pd.concat([batch_df, df], ignore_index=True)
        else:
            sn_count = 0
            batch_df.to_sql(out_tab, engine2, if_exists="append", index=False)
            batch_df = None
    batch_df.to_sql(out_tab, engine2, if_exists="append", index=False)
    print(batch_df)


def test(month):
    print(month.split('-')[0])
    print(month.split('-')[1])

    year = int(month.split('-')[0])
    month = int(month.split('-')[1])

    last_day = calendar.monthrange(year, month)[1]
    print(last_day)
    # 生成10个0到100之间的随机整数
    # random_numbers = np.random.randint(0, 100, size=10)
    #
    # print(random_numbers)

    # # 生成10个0到100之间的随机整数
    # random_numbers = random.sample(range(101), 10)
    #
    # print(random_numbers)


# def active_insert():
#     query_sql = "SELECT A.sn,login_month,login_count,B.active_time  FROM d_eshield_login_device_final_2022   A left join (\
#                     select sn,active_time from device_detail.d_eshield_device_details_2022 \
#                     ) B on A.sn = B.sn"
#
#     df = pd.read_sql(query_sql,con=engine)
#     df.to_sql(name='d_eshield_login_device_final_2022_active', con=engine, if_exists="append", index=False, chunksize=1000)

# 生成续费表
def make_renewal_data(table, engine, out_table, batch):
    print("续费表生成开始")
    query_sql = """
        select sn
        ,service_period
        ,settle_merchant
        ,settle_time
        ,service_price
        ,from_type
        ,classid
        ,from_table
        ,'{1}' as batch
        from {0} where from_type='4'
        """.format(table, batch)
    df = pd.read_sql(query_sql, con=engine)
    df.to_sql(name=out_table, con=engine, if_exists="append", index=False, chunksize=1000)
    print("续费表生成结束")

# 生成设备表
def make_device_data(table, engine, out_table, batch):
    print("设备表生成开始")
    query_sql = """
        select sn
        ,device_type
        ,delivery_time
        ,delivery_merchant
        ,active_time
        ,active_merchant
        ,device_period
        ,classid
        ,'{1}' as batch
        from {0}
        """.format(table, batch)
    df = pd.read_sql(query_sql,con=engine)
    df.to_sql(name=out_table, con=engine, if_exists="append", index=False, chunksize=1000)
    print("设备表生成结束")

# 生成设备明细表
def make_device_detail_data(device_table,service_table,engine,out_table, batch):
    print("设备明细表生成开始")
    query_sql = """
        select A.sn
        ,A.device_type
        ,A.active_merchant
        ,A.device_period
        ,A.settle_merchant
        ,A.settle_time
        ,A.device_price
        ,install_price
        ,A.from_type
        ,0 as hardware_price
        ,0 as install_cost
        ,'{2}' as batch
        ,B.service_price as service_price from
        ( select * from {0} ) A 
        left join
        ( select * from {1} where from_type !=4 )  B on A.sn=B.sn and A.settle_order = B.settle_order
        """.format(device_table,service_table, batch)
    df = pd.read_sql(query_sql,con=engine)
    df.to_sql(name=out_table, con=engine, if_exists="append", index=False, chunksize=1000)
    print("设备明细表生成结束")

# 生成对外应收单表
def make_receivables_data(device_detail_table,engine,out_table, batch):
    print("应收单表生成开始")
    query_sql = """
        select
            substring(settle_time, 1, 7) as settle_time,
            settle_merchant,
            count(*) as num,
            device_price,
            service_price,
            '{1}' as batch
        from
            {0}
        group by
            substring(settle_time, 1, 7),
            settle_merchant,
            device_price,
            service_price
        """.format(device_detail_table, batch)
    df = pd.read_sql(query_sql,con=engine)
    df.to_sql(name=out_table, con=engine, if_exists="append", index=False, chunksize=1000)
    print("应收单表生成结束")

# 将 from_engine中的库中的 table_list (表列表)  写入到 to_engine 中的对应表
# 需要保证表存在,直接生成的话,字段的类型过于宽泛,最好自己新建表
def load_data_to_out(from_engine,table_list,to_engine):
    # 从配置中读取需要排除 batch 列的表
    # 通常是带年份的明细表,或者明确需要区分批次的表
    # 根据用户需求,['d_eshield_renewal','t_eshield_device','t_eshield_device_detail','t_eshield_receivables'] 这几个表的batch不需要同步过去
    try:
        config = get_config()
        exclude_batch_tables = config.get('amortization_process', {}).get('edun', {}).get('exclude_batch_tables')
        if exclude_batch_tables is None:
            raise ValueError("配置项 amortization_process.edun.exclude_batch_tables 未找到")
    except Exception as e:
        raise Exception(f"读取 exclude_batch_tables 配置失败,请检查 config.yaml: {e}")

    for i in range(len(table_list)):
        table_name = table_list[i]
        delete_sql = 'truncate table '+table_name+''
        print("正在执行:"+delete_sql)
        try:
            with to_engine.connect() as con:
                con.execute(text(delete_sql))
        except Exception as e:
            if "1146" in str(e):
                print(f"表 {table_name} 不存在,将在写入数据时自动创建")
            else:
                raise e
        query_sql = 'select * from '+table_name+''
        df = pd.read_sql(query_sql,con=from_engine)
        
        # 如果表在排除列表中,且 dataframe 中包含 'batch' 列,则删除该列
        if table_name in exclude_batch_tables and 'batch' in df.columns:
            print(f"正在移除表 {table_name} 的 batch 列...")
            df = df.drop(columns=['batch'])
            
        df.to_sql(name=table_name, con=to_engine, if_exists="append", index=False, chunksize=1000)
        print("写入"+table_name+"成功!")

def delete_batch_data(engine, table_list, batch):
    """
    根据 batch 字段删除表中的数据
    """
    if not batch:
        print("警告: 未指定 batch,跳过删除操作")
        return

    with engine.connect() as con:
        # 开启事务
        trans = con.begin()
        try:
            for table in table_list:
                # 检查表中是否存在 batch 列 (简单处理,直接尝试删除,如果列不存在会报错)
                # 或者默认这些表都有 batch 列,因为是我们自己生成的
                delete_sql = f"DELETE FROM {table} WHERE batch = '{batch}'"
                print(f"执行删除: {delete_sql}")
                con.execute(text(delete_sql))
                print(f"表 {table} 中 batch='{batch}' 的数据已删除")
            
            # 提交事务
            trans.commit()
            
        except Exception as e:
            # 回滚事务
            trans.rollback()
            print(f"删除表数据时出错: {e}")
            # 重新抛出异常,以便上层终止流程
            raise Exception(f"删除旧数据失败,流程终止: {e}")

def process_audit_calculation(year, batch=None):
    """
    执行审计分摊计算流程
    :param year: 年份,如 2024, 2025
    :param batch: 批次号,通常为年份字符串,如 '2024'。如果未提供,默认使用 year 参数
    """
    if batch is None:
        batch = str(year)
        
    config = get_config()
    db_conf = config['database']

    # 创建数据库连接
    engine = create_engine(get_db_url(db_conf['device_detail_db']))
    # newsheid_engine = create_engine(get_db_url(db_conf['neshield_db']))
    # engine01 = create_engine(get_db_url(db_conf['glsx_data_db']))
    # engine02 = create_engine(get_db_url(db_conf['device_log_db']))

    print(f"开始执行 {year} 年的审计分摊计算流程 (Batch: {batch})...")

    # 动态构造表名
    service_details_table = f'd_eshield_service_details_{year}'
    device_details_table = f'd_eshield_device_details_{year}'
    
    # 目标表名(固定)
    renewal_target = 'd_eshield_renewal'
    device_target = 't_eshield_device'
    device_detail_target = 't_eshield_device_detail'
    receivables_target = 't_eshield_receivables'

    # 删除旧数据
    target_tables = [renewal_target, device_target, device_detail_target, receivables_target]
    print(f"正在清理旧数据 (Batch: {batch})...")
    delete_batch_data(engine, target_tables, batch)

    results = []

    #### 对内数据库操作
    # 插入新的续费数据
    print(f"正在处理续费数据: {service_details_table} -> {renewal_target}")
    make_renewal_data(service_details_table, engine, renewal_target, batch)
    results.append({
        "数据内容": "续费数据",
        "源表": service_details_table,
        "目标表": renewal_target,
        "状态": "✅ 已完成"
    })

    # 插入新的设备数据
    print(f"正在处理设备数据: {device_details_table} -> {device_target}")
    make_device_data(device_details_table, engine, device_target, batch)
    results.append({
        "数据内容": "设备数据",
        "源表": device_details_table,
        "目标表": device_target,
        "状态": "✅ 已完成"
    })

    # 插入新的设备明细数据
    # 重复插入数据时记住先删除之前插入的数据,但是不要清空整张表,因为还有历史数据
    print(f"正在处理设备明细数据: {device_details_table} + {service_details_table} -> {device_detail_target}")
    make_device_detail_data(device_details_table, service_details_table, engine, device_detail_target, batch)
    results.append({
        "数据内容": "设备明细数据",
        "源表": f"{device_details_table} + {service_details_table}",
        "目标表": device_detail_target,
        "状态": "✅ 已完成"
    })

    # 插入新的应收单数据
    print(f"正在处理应收单数据: {device_detail_target} -> {receivables_target}")
    make_receivables_data(device_detail_target, engine, receivables_target, batch)
    results.append({
        "数据内容": "应收单数据",
        "源表": device_detail_target,
        "目标表": receivables_target,
        "状态": "✅ 已完成"
    })

    print(f"{year} 年审计分摊计算流程执行完毕!")
    return results

if __name__ == "__main__":
    # 默认执行当前年份,或者指定年份测试
    current_year = datetime.datetime.now().year
    # 这里可以根据需要改为手动指定,例如 process_audit_calculation(2024)
    # 为了安全起见,暂时注释掉直接调用,或者默认使用一个测试年份
    # process_audit_calculation(2024)
    pass

def sync_to_external_db(table_list=None, year=None):
    """
    将内部库中的表导入到对外的数据库
    """
    config = get_config()
    db_conf = config['database']
    engine = create_engine(get_db_url(db_conf['device_detail_db']))
    engine01 = create_engine(get_db_url(db_conf['glsx_data_db']))

    if table_list is None:
        try:
            config = get_config()
            table_list = config.get('amortization_process', {}).get('edun', {}).get('default_sync_tables')
            if table_list is None:
                raise ValueError("配置项 amortization_process.edun.default_sync_tables 未找到")
        except Exception as e:
            raise Exception(f"读取 default_sync_tables 配置失败,请检查 config.yaml: {e}")
        
        # 如果指定了年份,则添加带年份的明细表
        if year:
            table_list.append(f'd_eshield_device_details_{year}')
            table_list.append(f'd_eshield_service_details_{year}')
    
    # 默认使用全局的 engine 和 engine01
    load_data_to_out(from_engine=engine, table_list=table_list, to_engine=engine01)
    print("数据同步到外部数据库完成。")