import os
import sys

import pandas as pd
from pyspark.sql.window import Window

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 pyspark.sql import functions as F
from pyspark.sql.types import StructType,StructField, StringType, IntegerType


class DwdStMeasure(Templates):

    def __init__(self, site_name='us', date_type="month", date_info='2022-01'):
        super().__init__()
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        self.db_save = f'dwd_st_rank'
        self.spark = self.create_spark_object(
            app_name=f"{self.db_save}: {self.site_name}, {self.date_type}, {self.date_info}")
        # self.df_date = self.get_year_week_tuple()  # pandas的df对象
        self.df_st_month = self.spark.sql(f"select 1+1;")
        self.df_st_week = self.spark.sql(f"select 1+1;")

    def read_data(self):
        pdf = pd.read_csv(f"/root/bs_category_rank.csv")
        schema = StructType([
            StructField("category_name", StringType(), True),
            StructField("bsr_rank", StringType(), True),
            StructField("category_first_id", StringType(), True),
        ])
        self.df_bsr_rank = self.spark.createDataFrame(pdf, schema=schema).cache()
        self.df_bsr_rank.show(20, truncate=False)
        #
        sql = f"select asin, asin_title, asin_category_desc as asin_category, asin_launch_time, created_time from dim_asin_detail WHERE site_name ='us' and date_type ='month' and date_info ='2023-11' and LOWER(asin_title) like '%halloween%';"
        print("sql:", sql)
        self.df_asin_detail = self.spark.sql(sql).cache()
        self.df_asin_detail.show(20, truncate=False)
        print("df_asin_detail:", self.df_asin_detail.count())

        sql = f"SELECT asin, asin_bs_cate_1_id as category_first_id, asin_bs_cate_1_rank as asin_bsr_rank  from dim_asin_bs_info WHERE  site_name ='us' and date_type ='month' and date_info ='2023-11';"
        print("sql:", sql)
        self.df_asin_bsr = self.spark.sql(sql).cache()
        self.df_asin_bsr.show(20, truncate=False)
        print("df_asin_detail:", self.df_asin_detail.count())
        #

        # sql = f"select asin, asin_title, category_first_id, asin_launch_time, asin_rank, asin_category_desc as asin_category  from dwt_flow_asin  WHERE site_name ='us' and date_type ='month' and date_info ='2023-11' and LOWER(asin_title) like '%halloween%'"
        # self.df_flow_asin = self.spark.sql(sql).cache()
        # self.df_flow_asin.show(20, truncate=False)
        # print("df_flow_asin:", self.df_flow_asin.count())

    def handle_data(self):

        self.df_asin_bsr = self.df_asin_bsr.join(
            self.df_bsr_rank, on='category_first_id', how='inner'
        )

        self.df_save = self.df_asin_detail.join(
            self.df_asin_bsr, on='asin', how='inner'
        )
        # self.df_save = self.df_flow_asin.join(
        #     self.df_bsr_rank, on='category_first_id', how='inner'
        # )

        self.df_save = self.df_save.withColumn("rank_flag", F.when(self.df_save["asin_bsr_rank"] <= self.df_save["bsr_rank"], 1).otherwise(0))
        print("df_save:", self.df_save.count())
        print("df_save--1:", self.df_save.filter('rank_flag=1').count())
        self.df_save = self.df_save.filter('rank_flag=1')
        # # 合并两个DataFrame
        # df_combined = self.df_st_month.union(self.df_st_week)
        #
        # # 只选择 row_number 为 1 的行
        # df_unique = df_combined.drop_duplicates(['asin_brand_name'])
        #
        # self.df_combined_unique = df_unique
        # self.df_combined_unique.show(20, truncate=False)
        # self.df_combined_unique = self.df_st_month.join(self.df_st_week, on='asin', how='inner')
        #
        # # , 'search_term'
        # window = Window.partitionBy(['asin']).orderBy(
        #     self.df_combined_unique.st_asin_zr_page_row.asc(),
        # )
        # self.df_combined_unique = self.df_combined_unique. \
        #     withColumn("page_rank_top", F.row_number().over(window=window))
        # # print("self.df_st_asin_info, 开窗去重前:", self.df_st_asin_info.count())
        # self.df_combined_unique = self.df_combined_unique.filter("page_rank_top<=3")
        # print("combined:", self.df_combined_unique.count())

    def save_data(self):
        # 转换为 Pandas DataFrame
        pdf = self.df_save.toPandas()

        # 根据需求将每100万行数据保存为一个CSV文件
        num_rows_per_file = 1000000
        num_files = (len(pdf) // num_rows_per_file) + (1 if len(pdf) % num_rows_per_file != 0 else 0)

        for i in range(num_files):
            start_idx = i * num_rows_per_file
            end_idx = start_idx + num_rows_per_file
            output_path = os.path.join("/root", f"asin_bsr_rank_{i + 1}.csv")

            # 将子集保存为CSV
            pdf.iloc[start_idx:end_idx].to_csv(output_path, index=False)

        print(f"Data saved into {num_files} CSV files.")


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