"""
   @Author      : hejiangming
   @Description : 店铺分类统计表
                  数据源从 ODS 切换到 flow:
                  - ods_seller_asin_account → dwt_flow_asin(seller-asin + asin_is_new + category)
                  - ods_seller_account_feedback → 不再读取(以 flow 为主表)
                  - dim_cal_asin_history_detail → 仅用于 bsr_asin_num 市场总量
   @SourceTable :
                  ①dwt_flow_asin
                  ②dim_cal_asin_history_detail
                  ③dim_bsr_category_tree
   @SinkTable   :
                  ①dwt_fb_category_report
   @CreateTime  : 2023/07/18 17:33
   @UpdateTime  : 2026/07/29
"""

import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))

from pyspark.sql import functions as F
from utils.common_util import CommonUtil
from utils.spark_util import SparkUtil
from utils.hdfs_utils import HdfsUtils


class DwtFbCategoryReport(object):
    def __init__(self, site_name, date_type, date_info):
        super().__init__()
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        self.hive_tb = f"dwt_fb_category_report"
        self.partition_dict = {
            "site_name": site_name,
            "date_type": date_type,
            "date_info": date_info
        }
        # 落表路径校验
        self.hdfs_path = CommonUtil.build_hdfs_path(self.hive_tb, partition_dict=self.partition_dict)

        # 创建spark_session对象相关
        app_name = f"{self.__class__.__name__}:{site_name}:{date_info}"
        self.spark = SparkUtil.get_spark_session(app_name)

        # 初始化全局df
        self.df_fb_asin_info = self.spark.sql(f"select 1+1;")
        self.df_asin_history = self.spark.sql(f"select 1+1;")
        self.df_cate_name = self.spark.sql(f"select 1+1;")
        self.df_fb_cate_asin_cal = self.spark.sql(f"select 1+1;")
        self.df_fb_asin_cal = self.spark.sql(f"select 1+1;")
        self.df_bsr_asin_cal = self.spark.sql(f"select 1+1;")
        self.df_result_cal = self.spark.sql(f"select 1+1;")

    def read_data(self):
        # 从 flow 读 seller-asin 关系 + asin_is_new + category_first_id, 以 flow 为主表
        # 替代原来的 ods_seller_account_feedback(seller集合) + ods_seller_asin_account(seller-asin)
        # + dim_cal_asin_history_detail(asin_launch_time+category)
        # asin_is_new 直接用 flow 已算好的值, 不再 UDF 重算
        print("获取 dwt_flow_asin (seller-asin + asin_is_new + category)")
        sql = f"""
        select account_id as seller_id, asin,
               asin_is_new as is_asin_new,
               category_first_id as bsr_cate_1_id
        from dwt_flow_asin
        where site_name = '{self.site_name}'
          and date_type = '{self.date_type}'
          and date_info = '{self.date_info}'
          and account_id is not null
        """
        # 原来从 ods_seller_asin_account 读, 有 created_at 过滤(爬虫先删后增导致活跃店铺被误筛)
        # 现在从 flow 读, 不存在该问题
        self.df_fb_asin_info = self.spark.sql(sqlQuery=sql)
        self.df_fb_asin_info = self.df_fb_asin_info.drop_duplicates(['seller_id', 'asin']).cache()
        print(sql)

        # dim_cal_asin_history_detail: 仅用于 bsr_asin_num(按一级分类统计全量 asin 数, 作为市场占比分母)
        # seller 的 asin_is_new 和 category 已从 flow 取, 这里不再取 asin_launch_time
        print("获取 dim_cal_asin_history_detail (bsr_asin_num)")
        sql = f"""
            select asin, category_first_id as bsr_cate_1_id
            from dim_cal_asin_history_detail
            where site_name = '{self.site_name}'
        """
        self.df_asin_history = self.spark.sql(sqlQuery=sql).cache()
        print(sql)

        # 一级分类名称
        print("获取 dim_bsr_category_tree")
        sql = f"""
            select category_id as bsr_cate_1_id, en_name as bsr_cate_1_name
            from big_data_selection.dim_bsr_category_tree
            where site_name = '{self.site_name}'
            and category_parent_id = 0
        """
        self.df_cate_name = self.spark.sql(sqlQuery=sql)
        print(sql)

    def run(self):
        # 读取数据
        self.read_data()
        # 逻辑处理
        self.handle_fb_agg()
        # 字段处理
        self.sava_data()

    def handle_fb_agg(self):
        # df_fb_asin_info 已含 is_asin_new 和 bsr_cate_1_id(从 flow 读取)
        # 不需要 join asin_history 取 category/launch_time, 也不需要 UDF 算新品
        self.df_fb_cate_asin_cal = self.df_fb_asin_info
        self.df_fb_cate_asin_cal = self.df_fb_cate_asin_cal.na.fill({'bsr_cate_1_id': '无'})

        # 按 seller_id + 一级分类聚合: 分类下 asin 数 + 新品数
        self.df_fb_cate_asin_cal = self.df_fb_cate_asin_cal.groupby(['seller_id', 'bsr_cate_1_id']).agg(
            F.count("asin").alias("fb_cate_asin_num"),
            F.sum("is_asin_new").alias("fb_cate_new_asin_num"),
        )

        # 店铺总 asin 数(flow 口径)
        self.df_fb_asin_cal = self.df_fb_asin_info.groupby(['seller_id']).agg(
            F.count("asin").alias("fb_asin_num"))

        # BSR 分类市场总量(仍用 dim_cal_asin_history_detail 全量 asin, 作为市场占比分母)
        self.df_bsr_asin_cal = self.df_asin_history.groupby(['bsr_cate_1_id']).agg(
            F.count("asin").alias("bsr_asin_num"))

        # 合并取到卖家分类的asin数量 和 bsr分类asin数量
        self.df_result_cal = self.df_fb_cate_asin_cal \
            .join(self.df_fb_asin_cal, on='seller_id', how='left') \
            .join(self.df_bsr_asin_cal, on='bsr_cate_1_id', how='left')

        # 分类店铺产品占比
        self.df_result_cal = self.df_result_cal.withColumn("fb_cate_asin_rate",
                                                           F.ceil((F.col("fb_cate_asin_num") / F.col(
                                                               "fb_asin_num") * 10000)) / 10000)

        # 分类店铺新品占比
        self.df_result_cal = self.df_result_cal.withColumn("fb_cate_new_asin_rate",
                                                           F.ceil((F.col("fb_cate_new_asin_num") / F.col(
                                                               "fb_asin_num") * 10000)) / 10000)

        # 分类市场占比
        self.df_result_cal = self.df_result_cal.withColumn("fb_market_rate",
                                                           F.ceil((F.col("fb_cate_asin_num") / F.col(
                                                               "bsr_asin_num") * 10000)) / 10000)

    def sava_data(self):
        df_save = self.df_result_cal.join(
            self.df_cate_name, on='bsr_cate_1_id', how='left'
        )

        # 未匹配到的分类名称置为无
        df_save = df_save.na.fill({'bsr_cate_1_name':'无'})

        df_save = df_save.select(
            F.col('seller_id'),
            F.col('bsr_cate_1_id'),
            F.col('bsr_cate_1_name'),
            F.col('fb_cate_asin_num'),
            F.col('fb_cate_new_asin_num'),
            F.col('fb_asin_num'),
            F.col('bsr_asin_num'),
            F.col('fb_cate_asin_rate'),
            F.col('fb_cate_new_asin_rate'),
            F.col('fb_market_rate'),
            F.date_format(F.current_timestamp(), 'yyyy-MM-dd HH:mm:SS').alias('created_time'),
            F.date_format(F.current_timestamp(), 'yyyy-MM-dd HH:mm:SS').alias('updated_time'),
            F.lit(self.site_name).alias('site_name'),
            F.lit(self.date_type).alias('date_type'),
            F.lit(self.date_info).alias('date_info')
        )

        print(f"清除hdfs目录中:{self.hdfs_path}")
        HdfsUtils.delete_file_in_folder(self.hdfs_path)

        df_save = df_save.repartition(1)
        partition_by = ["site_name", "date_type", "date_info"]
        print(f"当前存储的表名为：{self.hive_tb},分区为{partition_by}", )
        df_save.write.saveAsTable(name=self.hive_tb, format='hive', mode='append', partitionBy=partition_by)
        print("success")


if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, None)
    date_type = CommonUtil.get_sys_arg(2, None)
    date_info = CommonUtil.get_sys_arg(3, None)  # 参数3：年-周/年-月/年-季/年-月-日, 比如: 2022-1
    handle_obj = DwtFbCategoryReport(site_name=site_name, date_type=date_type, date_info=date_info)
    handle_obj.run()
