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, DateTypes
from utils.db_util import DBUtil
from sqlalchemy import text
from datetime import datetime


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)

    if test_flag == 'test':
        db_type = 'postgresql_test'
        print("导出到测试库中")
    else:
        db_type = 'postgresql'
        print("导出到pg单节点库中")

    engine = DBUtil.get_db_engine(db_type, site_name)
    export_tb = 'user_store_collections_info'

    sql = f"""
        truncate table {export_tb};
    """

    DBUtil.engine_exec_sql(engine, sql)

    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_user_store_collections_info",
        export_tb=export_tb,
        col=[
            "seller_id",
            "store_asin_total_num",
            "store_page20_asin_total_num",
            "store_page20_variant_rate",
            "store_page20_new_asin_total_num",
            "store_page20_new_asin_num_percent",
            "store_page20_old_asin_total_num",
            "store_page20_old_asin_num_percent",
            "store_page20_asin_avg_price",
            "store_page20_asin_avg_rating",
            "store_page20_asin_avg_comments",
            "store_page20_raise_asin_num",
            "store_page20_raise_asin",
            "store_page20_popular_asin_num",
            "store_page20_popular_asin",
            "store_page20_high_quantity_asin_num",
            "store_page20_high_quantity_asin",
            "store_page20_new_asin_sales_surge_num",
            "store_page20_new_asin_sales_surge",
            "store_page20_old_asin_sales_surge_num",
            "store_page20_old_asin_sales_surge",
            "store_location",
            "store_crawl_time",
            "store_first_category_percent",
            "store_current_category_percent",
            "store_label_type",
            "store_name",
            "store_page20_price_raise_asin_num",
            "store_page20_price_raise_asin",
            "store_page20_price_decline_asin_num",
            "store_page20_price_decline_asin",
            "store_page20_rank_raise_asin_num",
            "store_page20_rank_raise_asin",
            "store_page20_rank_decline_asin_num",
            "store_page20_rank_decline_asin",
            "store_new_flag"
        ],
        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()
    engine = DBUtil.get_db_engine('postgresql', site_name)
    after_delete_sql = f"""
          delete from us_self_asin_detail_base where data_type='9' and not exists (
            SELECT 1 FROM us_user_seller_collections collects
            WHERE us_self_asin_detail_base.account_id = collects.account_id
            AND us_self_asin_detail_base.asin = collects.asin)
        """
    after_update_sql = f"""
            update us_self_asin_detail_base set data_type = '8'
            where (account_id, asin) in (
                SELECT a.account_id, a.asin
                FROM us_self_asin_detail_base a
                LEFT JOIN us_user_seller_collections c ON a.account_id = c.account_id AND a.asin = c.asin
                WHERE c.asin IS null and (a.data_type = '8,9' or a.data_type = '9,8') 
            ) 
        """
    DBUtil.engine_exec_sql(engine, after_delete_sql)
    DBUtil.engine_exec_sql(engine, after_update_sql)
    print("success")
