"""
author: 方星钧(ffman)
description: 清洗6大站点对应的 “ods_brand_analytics” 的表: 排名权重计算，用天补全周/30天/月，存储新增的关键词
table_read_name: ods_brand_analytics
table_save_name: ods_st_key
table_save_level: ods
version: 1.0
created_date: 2022-11-22
updated_date: 2022-11-22
"""

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 AmazonSpider.pyspark_job.utils.templates_test import Templates
from pyspark.sql.types import StringType
# 分组排序的udf窗口函数
from pyspark.sql.window import Window
from pyspark.sql import functions as F
import uuid


class OdsStKey(Templates):

    def __init__(self, site_name='us', date_type="month", date_info='2022-1'):
        super().__init__()
        self.site_name = site_name
        self.db_save = f'ods_st_key'
        self.spark = self.create_spark_object(app_name=f"{self.db_save}: {self.site_name}")
        self.df_st = self.spark.sql(f"select 1+1;")
        self.df_st_key = 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']

    def read_data(self):
        print("1.1 读取ods_brand_analytics表")
        sql = f"select search_term from ods_brand_analytics where site_name='{self.site_name}' and date_type in ('day', 'week', 'month', 'quarter');"
        print("sql:", sql)
        self.df_st = self.spark.sql(sql).cache()
        self.df_st.show(10, truncate=False)
        print("1.2 读取ods_st_key表")
        sql = f"select search_term, 1 as flag from ods_st_key where site_name='{self.site_name}';"
        print("sql:", sql)
        self.df_st_key = self.spark.sql(sql).cache()
        self.df_st_key.show(10, truncate=False)

    def handle_data(self):
        self.df_st = self.df_st.drop_duplicates(['search_term'])
        self.df_st = self.df_st.join(
            self.df_st_key, on=['search_term'], how='left'
        )
        self.df_st = self.df_st.filter('flag is null')
        if self.df_st.count() == 0:
            print("新增关键词数量为0, 退出")
            quit()
        window = Window.orderBy(
            self.df_st.search_term.asc()
        )
        self.df_st = self.df_st.withColumn("st_key", F.row_number().over(window=window))
        self.df_st = self.df_st.withColumn("st_key", self.df_st_key.count()+self.df_st.st_key)
        # self.df_st = self.df_st.withColumn("st_key", F.concat(F.lit("st_"), self.df_st.st_key))
        self.df_st.show(10, truncate=False)
        print("self.df_st新增:", self.df_st.count())
        self.df_st = self.df_st.drop("flag")
        self.df_st = self.df_st.withColumn("site_name", F.lit(self.site_name))
        self.df_save = self.df_st


if __name__ == '__main__':
    site_name = sys.argv[1]  # 参数1：站点
    handle_obj = OdsStKey(site_name=site_name)
    handle_obj.run()
