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'
        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)
        sql = f"select rank, search_sum as st_orders from ods_rank_search_rate_repeat where site_name='{self.site_name}'"
        self.df_rank_repeat = self.spark.sql(sqlQuery=sql)

    def handle_data(self):
        self.df_brand_day = self.df_brand_day.join(self.df_rank_repeat, on='rank', how='left')
        self.df_brand_day = self.df_brand_day.withColumn('st_orders_day', self.df_brand_day.st_orders / 30)
        self.df_brand_day = self.df_brand_day.withColumn(
            "st_orders_pivot", F.concat(F.lit("st_orders_month"), self.df_brand_day.month, )
        ).withColumn(
            "st_counts_pivot", F.concat(F.lit("st_counts_month"), self.df_brand_day.month, )
        )
        self.df_brand_day.show(10, truncate=False)
        df_orders = self.df_brand_day.groupby(['search_term']).pivot(
            "st_orders_pivot"
        ).agg(F.sum('st_orders_day'))
        df_orders = df_orders.fillna(0)
        df_orders = df_orders.withColumn(
            "st_orders_quarter1", df_orders.st_orders_month1 + df_orders.st_orders_month2 + df_orders.st_orders_month3
        ).withColumn(
            "st_orders_quarter2", df_orders.st_orders_month4 + df_orders.st_orders_month5 + df_orders.st_orders_month6
        ).withColumn(
            "st_orders_quarter3", df_orders.st_orders_month7 + df_orders.st_orders_month8 + df_orders.st_orders_month9
        ).withColumn(
            "st_orders_quarter4",
            df_orders.st_orders_month10 + df_orders.st_orders_month11 + df_orders.st_orders_month12
        )
        df_orders = df_orders.withColumn(
            "st_orders_year",
            df_orders.st_orders_quarter1 + df_orders.st_orders_quarter2 + df_orders.st_orders_quarter3 + df_orders.st_orders_quarter4
        )
        df_orders.filter("search_term='sageholm leggings'").show(10, truncate=False)
        # df_orders.show(10, truncate=False)
        # print(df_orders.count())
        df_counts = self.df_brand_day.groupby(['search_term']).pivot(
            "st_counts_pivot"
        ).agg(F.count('search_term'))
        df_counts = df_counts.fillna(0)
        df_counts = df_counts.withColumn(
            "st_counts_quarter1", df_counts.st_counts_month1 + df_counts.st_counts_month2 + df_counts.st_counts_month3
        ).withColumn(
            "st_counts_quarter2", df_counts.st_counts_month4 + df_counts.st_counts_month5 + df_counts.st_counts_month6
        ).withColumn(
            "st_counts_quarter3", df_counts.st_counts_month7 + df_counts.st_counts_month8 + df_counts.st_counts_month9
        ).withColumn(
            "st_counts_quarter4",
            df_counts.st_counts_month10 + df_counts.st_counts_month11 + df_counts.st_counts_month12
        )
        df_counts = df_counts.withColumn(
            "st_counts_year",
            df_counts.st_counts_quarter1 + df_counts.st_counts_quarter2 + df_counts.st_counts_quarter3 + df_counts.st_counts_quarter4
        )
        # df_counts.show(10, truncate=False)
        # print(df_counts.count())
        self.df_save = df_orders.join(df_counts, on='search_term', how='left')
        self.df_save = self.df_save.withColumn("site_name", F.lit(self.site_name))
        # print(self.df_save.count())
        # print(self.df_save.columns)
        # self.df_save.show(10, truncate=False)


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

