import os
import sys
os.environ["PYARROW_IGNORE_TIMEZONE"] = "1"
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 DimCalAsinTruncateCategory(Templates):

    def __init__(self, site_name='us'):
        super().__init__()
        self.site_name = site_name
        self.db_save = f'dim_cal_asin_truncate_category'
        self.spark = self.create_spark_object(app_name=f"{self.db_save}: {self.site_name}")
        self.df_asin = self.spark.sql(f"select 1+1;")
        self.partitions_by = ['site_name']
        self.reset_partitions(1)

    def read_data(self):
        sql = f"select asin_trun_1, asin_trun_2, asin_trun_3, asin_trun_4, asin_trun_5, asin_trun_6, asin_img_path, site_name  from dim_cal_asin_truncate where site_name='{self.site_name}';"
        self.df_asin = self.spark.sql(sql).cache()

    def handle_data(self):
        group_list = ['asin_trun_1', 'asin_trun_2', 'asin_trun_3', 'asin_trun_4', 'asin_trun_5', 'asin_trun_6', 'asin_img_path', 'site_name']
        self.df_save = self.df_asin.groupby(group_list).agg(F.count('asin_img_path').alias('asin_img_path_counts'))
        self.df_save = self.df_save.withColumn('state', F.lit(1))
        self.df_save.show(10, truncate=False)


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