import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))
from utils.ssh_util import SSHUtil
from utils.common_util import CommonUtil
from utils.db_util import DBUtil, DbTypes

if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, None)
    date_info = CommonUtil.get_sys_arg(2, None)
    #  获取最后一个参数
    test_flag = CommonUtil.get_sys_arg(len(sys.argv) - 1, None)
    print(f"执行参数为{sys.argv}")
    # 工作时间不导出
    # CommonUtil.judge_is_work_hours(site_name=site_name,
    #                                date_type="day",
    #                                date_info=date_info,
    #                                principal='wujicang',
    #                                priority=1,
    #                                export_tools_type=1)

    if test_flag == 'test':
        db_type = DbTypes.postgresql_test.name
    else:
        db_type = DbTypes.postgresql_cluster.name
    print(f"导出到{db_type}库中")

    suffix = CommonUtil.reformat_date(date_info, "%Y-%m-%d", "%Y_%m_%d", )
    export_master_tb = f"{site_name}_nsr_asin_detail_all"
    export_tb = f"{export_master_tb}_{suffix}"
    next_day = CommonUtil.get_day_offset(date_info, 1)

    engine = DBUtil.get_db_engine(db_type, site_name)
    sql = f"""
                drop table if exists {export_tb};
                create table if not exists {export_tb} (like {export_master_tb}  including comments);
                """
    DBUtil.engine_exec_sql(engine, sql=sql)

    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_nsr_asin_detail_all",
        export_tb=export_tb,
        col=[
            'date_info',
            'id',
            'asin',
            'category_id',
            'bsr_rank',
            'is_1_day_flag',
            'is_7_day_flag',
            'is_30_day_flag',
            'bsr_count',
            'is_asin_new',
            'is_asin_bsr_new',
            'last_bsr_day',
            'title',
            'img_url',
            'ao_val',
            'rating',
            'total_comments',
            'bsr_orders',
            'bsr_orders_change',
            'price',
            'weight',
            'launch_time',
            'brand_name',
            'buy_box_seller_type',
            'account_name',
            'volume',
            'img_type',
            'last_update_time',
            'asin_type',
            'asin_air_freight_gross_margin',
            'asin_ocean_freight_gross_margin',
            'asin_unlaunch_time',
        ],
        partition_dict={
            "site_name": site_name,
            "date_info": date_info
        }
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    # 创建索引并交换分区
    DBUtil.add_pg_part(
        engine,
        source_tb_name=export_tb,
        part_master_tb=export_master_tb,
        part_val={
            "from": [date_info],
            "to": [next_day]
        },
        cp_index_flag=True,
    )
    client.close()
    print("success")

    # if test_flag != 'test':
    #     #  正式环境更新workflow_everyday
    #     engine = DBUtil.get_db_engine("mysql", "us")
    #     with engine.connect() as connection:
    #         sql = f"""
    #                 insert ignore into workflow_everyday (site_name, report_date, status, status_val, table_name, date_type, page, is_end, remark)
    #                 values ('{site_name}', '{date_info}', '导出PG数据库', 14, '{site_name}_bsr_asin_rank', 'day', 'BSR榜单', '是', 'BS榜单对应的TOP100ASIN')
    #                 """
    #         print("================================更新workflow_everyday================================")
    #         print(sql)
    #         connection.execute(sql)
    #         connection.close()
    #
    # print("success")
