import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from utils.hdfs_utils import HdfsUtils
from utils.spark_util import SparkUtil
from utils.templates import Templates
from pyspark.sql import functions as F, Window


class DwtTitleMatchingDegree(Templates):

    def __init__(self, site_name='us', date_type="month", date_info='2023-01'):
        super().__init__()
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        self.db_save = f'dwt_title_matching_degree'
        self.spark = self.create_spark_object(
            app_name=f"{self.db_save}: {self.site_name}, {self.date_type}, {self.date_info}")
        self.reset_partitions(partitions_num=5)
        self.partitions_by = ['site_name', 'date_type', 'date_info']
        self.df_dwd = self.spark.sql(f"select 1+1;")
        self.df_save = self.spark.sql(f"select 1+1;")

    def read_data(self):
        # 读取dwd_title_matching_degree
        sql = f"""
        select 
            asin,
            asin_title,
            search_term,
            contains_flag
        from 
            dwd_title_matching_degree
        where
            site_name = '{self.site_name}' 
        and date_type = '{self.date_type}' 
        and date_info = '{self.date_info}';
        """
        print(sql)
        self.df_dwd = self.spark.sql(sqlQuery=sql).cache()

    def handle_data(self):
        hdfs_path = f"/home/{SparkUtil.DEF_USE_DB}/dwt/{self.db_save}/site_name={self.site_name}/date_type={self.date_type}/date_info={self.date_info}"
        print(f"清除hdfs目录中.....{hdfs_path}")
        HdfsUtils.delete_hdfs_file(hdfs_path)

        # 按照asin分区统计asin的数量
        window = Window.partitionBy("asin")
        self.df_dwd = self.df_dwd.withColumn("asin_count", F.count("asin").over(window))
        # 统计每个asin中，flag为1的数量
        self.df_dwd = self.df_dwd.withColumn("contains_count", F.sum("contains_flag").over(window))
        self.df_dwd = self.df_dwd.withColumn("proportion", F.round(F.col("contains_count") / F.col("asin_count"), 4))

        self.df_dwd = self.df_dwd.withColumn("site_name", F.lit(self.site_name))
        self.df_dwd = self.df_dwd.withColumn("date_type", F.lit(self.date_type))
        self.df_dwd = self.df_dwd.withColumn("date_info", F.lit(self.date_info))
        self.df_save = self.df_dwd


if __name__ == '__main__':
    site_name = sys.argv[1]
    date_type = sys.argv[2]
    date_info = sys.argv[3]
    handle_obj = DwtTitleMatchingDegree(site_name=site_name, date_type=date_type, date_info=date_info)
    handle_obj.run()


