import os
import re
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.types import StringType, StructType, StructField, IntegerType
# 分组排序的udf窗口函数
from pyspark.sql.window import Window
from pyspark.sql import functions as F


class DimAsinBsCategoryDesc(Templates):

    def __init__(self, site_name='us'):
        super().__init__()
        self.site_name = site_name
        self.db_save = f'dim_asin_bs_category_desc'
        self.spark = self.create_spark_object(app_name=f"{self.db_save}: {self.site_name}")
        self.df_bs_detail = self.spark.sql(f"select 1+1;")
        # 分区参数
        self.partitions_by = ['site_name']
        self.partitions_num = 100
        schema = StructType([
            StructField('bs_rank_str', StringType(), True),
            StructField('bs_category_str', StringType(), True),
        ])
        self.u_rank_and_category = self.spark.udf.register("u_rank_and_category", self.udf_rank_and_category, schema)

    @staticmethod
    def udf_rank_and_category(best_sellers_rank):
        pattern = r"#([\d,]+) in ([\w&' ]+)"
        matches = re.findall(pattern, best_sellers_rank)

        bs_rank_str = ",".join([rank.replace(",", "") for rank, category in matches])
        bs_category_str = ",".join([category.strip().replace(",", " ") for rank, category in matches])
        return bs_rank_str, bs_category_str

    def read_data(self):
        sql = f"select asin, best_sellers_rank, last_herf, site_name, date_info from ods_bs_category_asin_detail where site_name='{self.site_name}' and date_type='week'"
        print("sql:", sql)
        self.df_bs_detail = self.spark.sql(sql).cache()
        self.df_bs_detail.show(10, truncate=False)

    def handle_data(self):
        # 去重取最新
        window = Window.partitionBy(['asin']).orderBy(F.desc("date_info"))
        self.df_bs_detail = self.df_bs_detail.withColumn(f"row_number", F.row_number().over(window)) \
            .filter(f'row_number = 1')
        # 提取排名和分类
        self.df_bs_detail = self.df_bs_detail.withColumn(
            'bs_str', self.u_rank_and_category('best_sellers_rank')
        )
        self.df_bs_detail = self.df_bs_detail.withColumn('bs_rank_str', self.df_bs_detail.bs_str.getField('bs_rank_str')) \
            .withColumn('bs_category_str', self.df_bs_detail.bs_str.getField('bs_category_str')) \
            .drop('bs_str')
        self.df_bs_detail.show(10, truncate=False)
        self.df_save = self.df_bs_detail


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