import os
import sys

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


class DwdStInfoDay(Templates):

    def __init__(self, site_name='us', date_type="month", date_info='2022-1'):
        super(DwdStInfoDay, self).__init__()
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        self.db_save = f'dwd_st_info_day_word'
        self.spark = self.create_spark_object(app_name=f"{self.db_save}: {self.site_name}, {self.date_info}")
        self.df_date = self.get_year_week_tuple()
        self.df_save = self.spark.sql(f"select 1+1;")
        self.df_brand_day = self.spark.sql(f"select 1+1;")
        self.df_rank_repeat = self.spark.sql(f"select 1+1;")
        self.partitions_by = ['site_name']
        self.reset_partitions(partitions_num=5)

    def read_data(self):
        sql = f"select year, month, search_term, rank, report_date from ods_brand_analytics_day where site_name='{self.site_name}' " \
              f"and dm in ('2021-9', '2021-10', '2021-11', '2021-12', '2022-1', '2022-2', '2022-3', '2022-4', '2022-5', '2022-6', '2022-7', '2022-8')"
        self.df_brand_day = self.spark.sql(sqlQuery=sql)
        self.df_brand_day = self.df_brand_day.withColumn("st_word", F.explode(F.split(self.df_brand_day.search_term, " ")))
        print(self.df_brand_day.count())
        quit()
        self.df_brand_day = self.df_brand_day.groupby(['st_word']).count()
        self.df_brand_day = self.df_brand_day.withColumnRenamed("count", "st_word_counts")
        self.df_brand_day = self.df_brand_day.orderBy('st_word_counts', ascending=False)
        self.df_brand_day = self.df_brand_day.withColumn('site_name', F.lit(self.site_name))
        self.df_brand_day.show(20, truncate=False)
        self.df_save = self.df_brand_day


if __name__ == '__main__':
    handle_obj = DwdStInfoDay()
    handle_obj.run()

