import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))

from utils.common_util import CommonUtil
from utils.secure_db_client import get_remote_engine

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)
    assert site_name is not None, "site_name 不能为空！"
    assert date_type is not None, "date_type 不能为空！"
    assert date_info is not None, "date_info 不能为空！"
    assert date_type in ('week', 'month', 'month_week'), "入参date_type类型存在问题，请检查！"

    db_type = "mysql"
    engine = get_remote_engine(
        site_name=site_name,
        db_type=db_type
    )

    # 该表为月表，因此如果传入week周期进行判断，获取周对应的月维度
    if (date_type == 'week') and (date_info is not None):
        sql = f"""select `year_month` from date_20_to_30 where `year_week`='{date_info}' and week_day = 1 """
        result = engine.read_sql(sql=sql)
        year_month = result.scalar()
        print(f"当前传入的周期为周维度，date_type：{date_type},date_info:{date_info};对应转换月为：{year_month}")
        date_type = 'month'
        date_info = year_month

    year, month = date_info.split("-")
    import_tb = f"{site_name}_one_category_report"
    query = f"""
        select 
            id,
            cate_1_id,
            name,
            rank,
            orders,
            orders_day,
            `year_month`,
            week,
            created_at,
            updated_at,
            category_id
        from {import_tb}
        where `year_month` = '{year}_{int(month)}'
        and \$CONDITIONS
    """

    hive_tb = "ods_one_category_report"
    partition_dict = {
        "site_name": site_name,
        "date_type": date_type,
        "date_info": date_info
    }
    hdfs_path = CommonUtil.build_hdfs_path(hive_tb, partition_dict=partition_dict)

    engine.sqoop_raw_import(
        query=query,
        hive_table=hive_tb,
        hdfs_path=hdfs_path,
        partitions=partition_dict
    )

    pass
