"""
   @Author      : hejiangming
   @Description : 店铺top20数据详情表
                  数据源优化: ods_seller_account_syn → dim_fb_detail(account_name)
                  dim_cal_asin_history_detail → dwt_flow_asin(asin详情)
   @SourceTable :
                  ①ods_asin_detail_product    (top20 seller_id+asin+row_num)
                  ②dwt_flow_asin              (asin详情+is_asin_new)
                  ③dim_fb_detail              (account_name)
   @SinkTable   : dwt_fb_top20_asin_info
   @CreateTime  : 2022/07/24 14:55
   @UpdateTime  : 2026/07/29
"""

import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))
from utils.hdfs_utils import HdfsUtils
from utils.common_util import CommonUtil
from utils.spark_util import SparkUtil
from pyspark.sql import functions as F


class DwtFbTop20Info(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_top20_asin_info"
        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_top20_asin_info = self.spark.sql(f"select 1+1;")
        self.df_seller_account = self.spark.sql(f"select 1+1;")

    def read_data(self):
        # top20 排名关系: 只读 seller_id + asin + row_num
        print("获取 ods_asin_detail_product (top20 排名)")
        sql = f"""
            select seller_id, asin, row_num as fb_row_num
            from ods_asin_detail_product
            where site_name = '{self.site_name}'
              and date_type = '{self.date_type}'
              and date_info = '{self.date_info}'
        """
        self.df_fb_top20_asin_info = self.spark.sql(sqlQuery=sql)
        self.df_fb_top20_asin_info = self.df_fb_top20_asin_info.drop_duplicates(['seller_id', 'asin'])
        print(sql)

        # asin 详情 + 新品标记从 flow 取(替代 dim_cal_asin_history_detail + UDF)
        print("获取 dwt_flow_asin (asin 详情)")
        sql = f"""
            select asin, asin_title, asin_img_url,
                   asin_price, asin_rating, asin_total_comments,
                   asin_volume, asin_weight, asin_launch_time,
                   asin_is_new as is_asin_new
            from dwt_flow_asin
            where site_name = '{self.site_name}'
              and date_type = '{self.date_type}'
              and date_info = '{self.date_info}'
        """
        df_flow = self.spark.sql(sqlQuery=sql).drop_duplicates(['asin'])
        self.df_fb_top20_asin_info = self.df_fb_top20_asin_info.join(df_flow, on='asin', how='left').cache()
        print(sql)

        # account_name 从 dim_fb_detail 取(替代 ods_seller_account_syn)
        print("获取 dim_fb_detail (account_name)")
        sql = f"""
            select seller_id, account_name
            from dim_fb_detail
            where site_name = '{self.site_name}'
              and date_type = '{self.date_type}'
              and date_info = '{self.date_info}'
        """
        self.df_seller_account = self.spark.sql(sqlQuery=sql)
        print(sql)

    def sava_data(self):
        df_save = self.df_fb_top20_asin_info.join(
            self.df_seller_account, on='seller_id', how='inner'
        )
        df_save = df_save.filter(F.col('account_name').isNotNull())

        df_save = df_save.select(
            F.col('seller_id'),
            F.col('account_name'),
            F.col('asin'),
            F.col('asin_title'),
            F.col('asin_img_url'),
            F.col('asin_price'),
            F.col('asin_rating'),
            F.col('asin_total_comments'),
            F.col('fb_row_num'),
            F.col('asin_volume'),
            F.col('asin_weight'),
            F.col('asin_launch_time'),
            F.col('is_asin_new'),
            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')
        )

        # CommonUtil.check_schema(self.spark, df_save, self.hive_tb)

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

        df_save = df_save.repartition(10)
        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")

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


if __name__ == '__main__':
    site_name = sys.argv[1]  # 参数1：站点
    date_type = sys.argv[2]  # 参数2：类型：week/4_week/month/quarter
    date_info = sys.argv[3]  # 参数3：年-周/年-月/年-季, 比如: 2022-1
    handle_obj = DwtFbTop20Info(site_name=site_name, date_type=date_type, date_info=date_info)
    handle_obj.run()
