import os
import sys


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

class tmpAbaKeywordAnalytics(Templates):

    def __init__(self, site_name='us'):
        super().__init__()
        self.site_name = site_name
        self.db_save = f'tmp_aba_keyword'
        self.spark = self.create_spark_object(
            app_name=f"{self.db_save}: {self.site_name}")
        self.reset_partitions(partitions_num=10)
        self.partitions_by = ['site_name']
        self.df_aba = self.spark.sql(f"select 1+1;")
        self.df_keyword = self.spark.sql(f"select 1+1;")
        self.df_save = self.spark.sql(f"select 1+1;")

    def read_data(self):
        sql1 = f"""
        select 
            st_key,
            search_term
        from 
            ods_st_key
        where
            site_name = '{self.site_name}';
        """
        print(sql1)
        self.df_aba = self.spark.sql(sqlQuery=sql1).cache()

        sql2 = f"""
        select 
            keywordText as search_term,
            keywordText
        from 
            ods_adv_keyword
        where
            site_name = '{self.site_name}'
        group by keywordText;
        """
        print(sql2)
        self.df_keyword = self.spark.sql(sqlQuery=sql2).cache()

    def handle_data(self):
        self.df_save = self.df_aba.join(self.df_keyword, 'search_term', 'left')
        print(self.site_name)
        # 填充分区字段
        self.df_save = self.df_save.withColumn("site_name", F.lit(self.site_name))
        self.df_save.show(10)


if __name__ == '__main__':
    site_name = sys.argv[1]
    handle_obj = tmpAbaKeywordAnalytics(site_name=site_name)
    handle_obj.run()
