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 DwtMerchantwordsKeywordDetail(Templates):

    def __init__(self, site_name='us'):
        super().__init__()
        self.site_name = site_name
        self.db_save = f'dwt_merchantwords_keyword_detail'
        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_merchantwords = 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 
            keyword,
            volume,
            avg_3m,
            avg_12m,
            depth,
            results_count,
            sponsored_ads_count,
            page_1_reviews,
            appearance,
            last_seen,
            update_time,
            source_type,
            api_json,
            lang
        from 
            dwt_merchantwords_st_detail
        where
            site_name = '{self.site_name}';
        """
        print(sql1)
        self.df_merchantwords = self.spark.sql(sqlQuery=sql1).cache()

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

    def handle_data(self):
        self.df_save = self.df_merchantwords.join(self.df_keyword, 'keyword', 'inner')
        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 = DwtMerchantwordsKeywordDetail(site_name=site_name)
    handle_obj.run()
