import os
import sys
os.environ["PYARROW_IGNORE_TIMEZONE"] = "1"
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


class DimCalAsinTruncate(Templates):

    def __init__(self, site_name='us'):
        super().__init__()
        self.site_name = site_name
        self.db_save = f'dim_cal_asin_truncate'
        self.spark = self.create_spark_object(app_name=f"{self.db_save}: {self.site_name}")
        self.df_asin = self.spark.sql(f"select 1+1;")
        self.df_save = self.spark.sql(f"select 1+1;")
        self.partitions_by = ['site_name']
        self.reset_partitions(50)

    def read_data(self):
        sql = f"select asin, asin_img_url, site_name, asin_title, asin_title_len, asin_category_desc, " \
              f"asin_rank, asin_volume, asin_weight, asin_color, asin_size, asin_style, asin_price, " \
              f"asin_rating, asin_total_comments, asin_material, asin_brand_name, asin_page_inventory, " \
              f"bsr_cate_1_id, bsr_cate_current_id, asin_buy_box_seller_type " \
              f"from dim_cal_asin_history_detail where site_name='{self.site_name}';"
        self.df_asin = self.spark.sql(sql).cache()

    def handle_data(self):
        self.df_asin = self.df_asin.withColumn("asin_trun_1", F.substring(self.df_asin.asin, 1, 1))
        self.df_asin = self.df_asin.withColumn("asin_trun_2", F.substring(self.df_asin.asin, 1, 2))
        self.df_asin = self.df_asin.withColumn("asin_trun_3", F.substring(self.df_asin.asin, 1, 3))
        self.df_asin = self.df_asin.withColumn("asin_trun_4", F.substring(self.df_asin.asin, 1, 4))
        self.df_asin = self.df_asin.withColumn("asin_trun_5", F.substring(self.df_asin.asin, 1, 5))
        self.df_asin = self.df_asin.withColumn("asin_trun_6", F.substring(self.df_asin.asin, 1, 6))
        self.df_asin = self.df_asin.withColumn("asin_trun_7", F.substring(self.df_asin.asin, 1, 7))
        self.df_asin = self.df_asin.withColumn("asin_trun_8", F.substring(self.df_asin.asin, 1, 8))
        self.df_asin = self.df_asin.withColumn("asin_trun_9", F.substring(self.df_asin.asin, 1, 9))
        self.df_asin = self.df_asin.withColumn(
            "asin_img_path",
            F.concat(
                F.lit("/"), self.df_asin.asin_trun_1,
                F.lit("/"), self.df_asin.asin_trun_2,
                F.lit("/"), self.df_asin.asin_trun_3,
                F.lit("/"), self.df_asin.asin_trun_4,
                F.lit("/"), self.df_asin.asin_trun_5,
                F.lit("/"), self.df_asin.asin_trun_6,
                F.lit("/")
            )
        )
        self.df_save = self.df_asin
        self.df_save.show(10, truncate=False)


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