import os
import sys
import re

import numpy as np

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.types import StringType, FloatType, StructType, StructField


class DwtThemeBsOrders(Templates):

    def __init__(self, site_name='us', date_type="month", date_info='2022-1'):
        super().__init__()
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        self.db_save = f'dwt_theme_bs_orders'
        self.spark = self.create_spark_object(app_name=f"{self.db_save}: {self.site_name}, {self.date_type}, {self.date_info}")
        self.df_theme = self.spark.sql(f"select 1+1;")
        self.df_flow = self.spark.sql(f"select 1+1;")
        self.df_save = self.spark.sql(f"select 1+1;")
        self.partitions_by = ['site_name']
        self.partitions_num = 100

    def read_data(self):
        sql = f"select asin, theme_en, theme_ch from dim_asin_title_info_vertical where site_name='{self.site_name}';"
        print("sql:", sql)
        self.df_theme = self.spark.sql(sql).cache()
        self.df_theme.show(10, truncate=False)

        sql = f"select asin, bsr_orders, dt as date_info from selection_off_line.dwt_asin_month where site='{self.site_name}' and " \
              f"dt in ('2022_7', '2022_8', '2022_9', '2022_10', '2022_11', '2022_12') " \
              f"union all " \
              f"select asin, bsr_orders, date_info from dwt_flow_asin where site_name='{self.site_name}' and " \
              f"date_type='month' and date_info in ('2023-01', '2023-02', '2023-03', '2023-04', '2023-05', '2023-06');"
        print("sql:", sql)
        self.df_flow = self.spark.sql(sql).cache()
        self.df_flow.show(10, truncate=False)

    def handle_data(self):
        self.df_flow = self.df_flow.filter("bsr_orders >0")
        self.df_theme = self.df_theme.drop_duplicates(['asin', 'theme_ch'])
        self.df_save = self.df_flow.join(
            self.df_theme, on='asin', how='inner'
        )
        # self.df_save.show(30, truncate=False)
        # pivot_df1 = self.df_asin_title.groupBy("asin").pivot("theme_type_en_counts").agg(
        #     F.expr("IFNULL(count(*), 0) AS value"))
        self.df_save = self.df_save.groupBy("theme_ch").pivot("date_info").agg(
            F.sum("bsr_orders"), F.count("asin")
        )
        # self.df_save.show(50, truncate=False)
        self.df_save = self.df_save.withColumn('site_name', F.lit(self.site_name))
        df = self.df_save.toPandas()
        df.to_csv("/root/theme.csv", index=False)


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