import os
import sys

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

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


class RerunDemo(object):
    def __init__(self, site_name, date_type, date_info):
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        app_name = f"{self.__class__.__name__}:{self.site_name}:{self.date_type}:{self.date_info}"
        self.spark = SparkUtil.get_spark_session(app_name)
        self.db_save = "dwt_flow_asin"
        self.partitions_num = 200
        # 分区字段
        self.partitions_by = ['site_name', 'date_type', 'date_info']
        # 拼接where条件
        self.partitions_dict = {
            'site_name': self.site_name,
            'date_type': self.date_type,
            'date_info': self.date_info
        }

    def run(self):
        sql = f"""
            select * from {self.db_save} where site_name = '{self.site_name}' and date_type = '{self.date_type}' and date_info = '{self.date_info}';
        """
        df_history_data = self.spark.sql(sql).repartition(self.partitions_num).cache()
        print("重跑前历史数据如下:")
        df_history_data.show(10, True)

        sql = f"""
            select asin, 1 as flag from {self.site_name}_asin_detail_2025_buysales_err where date_info = '{self.date_info}'
        """
        pg_con_info = DBUtil.get_connection_info("postgresql_14", self.site_name)
        df_asin = SparkUtil.read_jdbc_query(
            session=self.spark,
            url=pg_con_info['url'],
            username=pg_con_info['username'],
            pwd=pg_con_info['pwd'],
            query=sql
        )
        df_asin = df_asin.dropDuplicates(['asin']).cache()
        print("爬虫表数据量为：", df_asin.count())

        df_save = df_history_data.join(
            df_asin, 'asin', 'left'
        ).withColumn(
            'asin_bought_month', F.when(F.col('flag') == 1, F.lit(None)).otherwise(F.col('asin_bought_month'))
        ).drop('flag').cache()

        if df_history_data.count() == df_save.count():
            print(f"当前存储的表名为：{self.db_save}, 分区为{self.partitions_by}")
            hdfs_path = CommonUtil.build_hdfs_path(self.db_save, self.partitions_dict)
            HdfsUtils.delete_file_in_folder(hdfs_path)
            df_save.repartition(self.partitions_num).write.saveAsTable(name=self.db_save, format='hive', mode='append', partitionBy=self.partitions_by)
            print("重跑成功！")
        else:
            print("重跑失败！")
            exit()


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)
    obj = RerunDemo(site_name=site_name, date_type=date_type, date_info=date_info)
    obj.run()
