import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))
from utils.db_util import DBUtil

from utils.ssh_util import SSHUtil
from utils.common_util import CommonUtil, DateTypes

if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, None)
    date_type = CommonUtil.get_sys_arg(2, None)
    date_info = CommonUtil.get_sys_arg(3, None)
    #  获取最后一个参数
    test_flag = CommonUtil.get_sys_arg(len(sys.argv) - 1, None)
    print(f"执行参数为{sys.argv}")

    if test_flag == 'test':
        db_type = 'postgresql_test'
        print("导出到测试库中")
    else:
        CommonUtil.judge_is_work_hours(site_name=site_name, date_type=date_type, date_info=date_info,
                                       principal='wujicang',
                                       priority=2, export_tools_type=1, belonging_to_process=f'新ABA流程_{date_type}')
        if date_type == DateTypes.month.name:
            db_type = 'postgresql_cluster'
            print("导出到PG-Cluster库中")
        else:
            db_type = "postgresql"
            print("导出到PG库中")

    assert date_type == DateTypes.month.name, "date_type 数据不合法"

    suffix = str(date_info).replace("-", "_")
    export_master_tb = f"{site_name}_market_cycle"
    export_tb = f"{export_master_tb}_{suffix}"
    next_val = CommonUtil.get_month_offset(date_info, 1)

    engine = DBUtil.get_db_engine(db_type, site_name)
    with engine.connect() as connection:
        sql = f"""
                create table if not exists {export_tb} partition of {export_master_tb} for values from ('{date_info}') to ('{next_val}');
                truncate table {export_tb};
                """
        print("================================执行sql================================")
        print(sql)
        connection.execute(sql)

    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_st_market",
        export_tb=export_tb,
        col=[
            "id",
            "search_term",
            "rank_1",
            "rank_2",
            "rank_3",
            "rank_4",
            "rank_5",
            "rank_6",
            "rank_7",
            "rank_8",
            "rank_9",
            "rank_10",
            "rank_11",
            "rank_12",
            "rank_1_search_volume",
            "rank_2_search_volume",
            "rank_3_search_volume",
            "rank_4_search_volume",
            "rank_5_search_volume",
            "rank_6_search_volume",
            "rank_7_search_volume",
            "rank_8_search_volume",
            "rank_9_search_volume",
            "rank_10_search_volume",
            "rank_11_search_volume",
            "rank_12_search_volume",
            "month_growth_rate_1",
            "month_growth_rate_2",
            "month_growth_rate_3",
            "month_growth_rate_4",
            "month_growth_rate_5",
            "month_growth_rate_6",
            "max_avg_val",
            "date_type",
            "date_info",
            "market_cycle_type"
        ],
        partition_dict={
            "site_name": site_name,
            "date_type": date_type,
            "date_info": date_info
        }
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()
    # 往导出流程表插入导出完成数据，方便监听导出脚本是否全部完成
    update_workflow_sql = f"""
            UPDATE selection.workflow_everyday SET status='导出PG数据库完成', status_val=14,is_end ='是',export_db_type = '{db_type}'  
            WHERE site_name= '{site_name}' and date_type='{date_type}' and report_date= '{date_info}'  and page ='ABA搜索词'
        """
    CommonUtil.modify_export_workflow_status(update_workflow_sql, site_name, date_type, date_info)

    print("success")
