import os
import sys
from datetime import datetime

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

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("导出到PG测试库中")
    else:
        CommonUtil.judge_is_work_hours(site_name=site_name, date_type=date_type, date_info=date_info,
                                       principal='chenyuanjie', priority=2, export_tools_type=1,  belonging_to_process=f'新ABA流程_{date_type}')
        if date_type in (DateTypes.month.name, DateTypes.week.name, DateTypes.month_week.name):
            db_type = 'postgresql_cluster'
            print("导出到PG-Cluster库中")
        else:
            db_type = "postgresql"
            print("导出到PG库中")

    # 获取数据库连接
    engine = DBUtil.get_db_engine(db_type, site_name)

    # 导出表
    export_base_tb = f"{site_name}_aba_last_change_rate"

    # last30day和last365day导出
    if date_type in (DateTypes.last30day.name, DateTypes.last365day.name,DateTypes.month_week.name):
        if date_type == DateTypes.month_week.name:
            export_tb_target = f"{export_base_tb}_last30day"
        else:
            export_tb_target = f"{export_base_tb}_{date_type}"  # us_aba_last_change_rate_last30day / _last365day
        export_tb_copy = f"{export_tb_target}_copy"
        export_tb = export_tb_copy
        # 如果copy表不存在则创建copy表
        sql = f"""
               create table if not exists {export_tb_copy} 
              (
                  like {export_tb_target} including indexes including comments
              );
              truncate table {export_tb_copy};
              """
        DBUtil.engine_exec_sql(engine, sql)
    else:
        # day,week,month这种时间类型的数据导出
        date_partition = str(date_info).replace("-", "_")
        export_tb = f"{site_name}_aba_last_change_rate_{date_type}_{date_partition}"
        next_val = CommonUtil.get_next_val(date_type, date_info)
        # 创建分区，并清空导出分区
        sql = f"""
              create table if not exists {export_tb} partition of {export_base_tb} for values from ('{date_type}', '{date_info}') to ('{date_type}', '{next_val}');
              truncate table {export_tb};
              """
        DBUtil.engine_exec_sql(engine, sql)

    if test_flag == "month_append":
        partition_dict = {
            "site_name": site_name,
            "date_type": "month",
            "date_info": date_info
        }
    else:
        partition_dict = {
            "site_name": site_name,
            "date_type": date_type,
            "date_info": date_info
        }
    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_aba_last_change_rate",
        export_tb=export_tb,
        col=[
            "search_term",
            "search_term_id",
            "date_type",
            "date_info",
            "rank_change_rate",
            "bsr_orders_change_rate",
            "cn_seller_change_rate",
            "fbm_change_rate",
            "amazon_change_rate",
            "rank_rate_of_change",
            "bsr_orders_rate_of_change",
            "cn_seller_rate_of_change",
            "fbm_rate_of_change",
            "amazon_rate_of_change",
            "created_time",
            "updated_time"
        ],
        partition_dict=partition_dict
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()
    # 关闭链接
    engine.dispose()


    if date_type in (DateTypes.last30day.name, DateTypes.last365day.name,DateTypes.month_week.name):
        #  需要通过备份表替换形式替换数据
        DBUtil.exchange_tb(engine, export_tb_copy, export_tb_target, cp_index_flag=False)
        update_workflow_sql = f"""
            replace INTO selection.workflow_everyday
            (site_name, report_date, status, status_val, table_name, date_type, page, is_end, remark,export_db_type)
            VALUES('{site_name}', '{datetime.now().date()}', '导出PG数据库完成', 14, 'us_aba_last_30_day', '30_day', 'ABA搜索词', '是', 'ABA搜索词最近30天表','{db_type}');
        """
    else:
        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)
