"""
author: 方星钧(ffman)
description: 迁移数据
table_read_name: ods_search_term_rank_zr/sp/sb/ac/bs/er/tr
table_save_name: ods_search_term_zr/sp/sb/ac/bs/er/tr
table_save_level: ods
version: 1.0
created_date: 2022-12-14
updated_date: 2022-12-14
"""


import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from pyspark.storagelevel import StorageLevel
from utils.templates import Templates
# from ..utils.templates import Templates
from pyspark.sql import functions as F


class OdsBrandAnalytics(Templates):

    def __init__(self, site_name='us', st_type='zr', date_type="month", date_info='2022-01'):
        super().__init__()
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        self.st_type = st_type
        self.db_save = f'ods_search_term_{self.st_type}'
        self.spark = self.create_spark_object(app_name=f"{self.db_save}: {self.site_name}, {self.date_type}, {self.date_info}")
        self.df_date = self.get_year_week_tuple()  # pandas的df对象
        self.df_st_asin = self.spark.sql(f"select 1+1;")
        self.df_save = self.spark.sql(f"select 1+1;")
        self.partitions_num = 1
        self.reset_partitions(partitions_num=self.partitions_num)
        self.partitions_by = ['site_name', 'date_type', 'date_info']

    def read_data(self):
        print("1.1 读取ods_brand_analytics表")
        sql = f"select * from ods_search_term_rank_{self.st_type} where site_name='{self.site_name}' and dt='{self.date_info}';"
        print("sql:", sql)
        self.df_st_asin = self.spark.sql(sql).cache()
        self.df_st_asin.show(10, truncate=False)
        self.df_st_asin = self.df_st_asin.drop("id", "dt")

    def handle_data(self):
        self.df_save = self.df_st_asin
        self.df_save = self.df_save.withColumn("date_type", F.lit(self.date_type))
        self.df_save = self.df_save.withColumn("date_info", F.lit(self.date_info))
        self.df_save.show(10, truncate=False)


if __name__ == '__main__':
    site_name = sys.argv[1]  # 参数1：站点
    st_type = sys.argv[2]  # 参数2：关键词类型 zr/sp/sb/ac/bs/er/tr
    date_type = sys.argv[3]  # 参数3：类型：day/week/4_week/month/quarter
    date_info = sys.argv[4]  # 参数4：年-月-日/年-周/年-月/年-季, 比如: 2022-1
    handle_obj = OdsBrandAnalytics(site_name=site_name, st_type=st_type, date_type=date_type, date_info=date_info)
    handle_obj.run()