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
from pyspark.sql.window import Window


class DimAsinImgInfo(Templates):

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

    def read_data(self):
        sql = f"select asin, img_url as asin_img_url, date_info " \
              f"from ods_asin_detail where site_name='{self.site_name}' and date_type='week';"
        print("sql:", sql)
        self.df_asin_img = self.spark.sql(sql).cache()
        self.df_asin_img.show(10, truncate=False)

    def handle_data(self):
        self.df_asin_img = self.df_asin_img.filter("asin_img_url is not null")
        self.df_asin_img = self.df_asin_img.filter(self.df_asin_img.asin_img_url.contains('amazon'))  # 保留包含amazon的字符串记录

        window = Window.partitionBy('asin').orderBy(F.desc('date_info'))  # 按照 date_info 列进行分区，并按照 date 列进行排序
        self.df_asin_img = self.df_asin_img.withColumn('row_number', F.row_number().over(window))  # 使用窗口函数为每个分区的行编号
        self.df_asin_img = self.df_asin_img.filter(self.df_asin_img.row_number == 1).drop('row_number')  # 只保留每个分区中 row_number 最大的行，并删除 row_number 列
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_1", F.substring(self.df_asin_img.asin, 1, 1))
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_2", F.substring(self.df_asin_img.asin, 1, 2))
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_3", F.substring(self.df_asin_img.asin, 1, 3))
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_4", F.substring(self.df_asin_img.asin, 1, 4))
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_5", F.substring(self.df_asin_img.asin, 1, 5))
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_6", F.substring(self.df_asin_img.asin, 1, 6))
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_7", F.substring(self.df_asin_img.asin, 1, 7))
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_8", F.substring(self.df_asin_img.asin, 1, 8))
        self.df_asin_img = self.df_asin_img.withColumn("asin_trun_9", F.substring(self.df_asin_img.asin, 1, 9))
        self.df_asin_img = self.df_asin_img.withColumn(
            "asin_img_path",
            F.concat(
                F.lit("/"), self.df_asin_img.asin_trun_1,
                F.lit("/"), self.df_asin_img.asin_trun_2,
                F.lit("/"), self.df_asin_img.asin_trun_3,
                F.lit("/"), self.df_asin_img.asin_trun_4,
                F.lit("/"), self.df_asin_img.asin_trun_5,
                F.lit("/"), self.df_asin_img.asin_trun_6,
                F.lit("/")
            )
        )
        self.df_asin_img = self.df_asin_img.withColumn("state", F.lit(1))
        self.df_asin_img = self.df_asin_img.withColumn("site_name", F.lit(self.site_name))
        self.df_save = self.df_asin_img
        self.df_save.show(10, truncate=False)


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