"""
计算买家搜索词
"""

import os
import sys

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


class DwdBuyerSt(Templates):

    def __init__(self, site_name='us', date_type="month", date_info='2022-1'):
        super().__init__()
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        self.db_save = f'dwd_buyer_st'
        self.start_day = ''
        self.end_day = ''
        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=10)
        self.partitions_by = ['site_name', 'date_type', 'date_info']
        self.get_date_info()
        self.df_search_for_buyer_term = self.spark.sql(f"select 1+1;")
        self.df_positioning_for_buyer_term = self.spark.sql(f"select 1+1;")
        self.site_dict = {
            "us": 3,
            "uk": 4,
            "de": 6,
            "fr": 1,
            "es": 7,
            "it": 8
        }

    def get_date_info(self):
        df_date = self.spark.sql(f"select * from dim_date_20_to_30;")
        df = df_date.toPandas()
        if self.date_type == 'week':
            df_week_start_day = df.loc[(df.year_week == f'{self.date_info}') & (df.week_day == 1)]
            self.start_day = str(list(df_week_start_day.date)[0]).replace("-", "")
            df_week_end_day = df.loc[(df.year_week == f'{self.date_info}') & (df.week_day == 7)]
            self.end_day = str(list(df_week_end_day.date)[0]).replace("-", "")

    def read_data(self):
        # 1.读取搜索词买家词信息
        sql = f"""
            SELECT replace(replace(replace(customerSearchText, '\\t', ' '), '\\n', ' '), '\\001', ' ') as search_term, attributedSales7d as sales,
            attributedConversions7d as orders, clicks, startDate as report_date
            from advertising_manager.customer_search_report where site={self.site_dict[f'{self.site_name}']} and LENGTH(customerSearchText) <100
            and startDate >= '{self.start_day}' and startDate <= '{self.end_day}'
            and customerSearchText is not null and trim(customerSearchText) != ''
        """
        print("sql = " + sql)
        self.df_search_for_buyer_term = DorisHelper.spark_import_with_sql(session=self.spark, query=sql, use_type='adv')
        # 2.读取定位买家词
        sql = f"""
             SELECT replace(replace(replace(`query`, '\\t', ' '), '\\n', ' '), '\\001', ' ') as search_term, attributedSales7d as sales,
             attributedConversions7d as orders, clicks, startDate as report_date
             from advertising_manager.customer_search_target_report where site={self.site_dict[f'{self.site_name}']} and targetingExpression
             in('close-match','loose-match') and LENGTH(query) >10  and LENGTH(query) < 100 and
             startDate >= '{self.start_day}' and startDate <= '{self.end_day}'
             and `query` is not null and trim(`query`) != ''
        """
        print("sql = " + sql)
        self.df_positioning_for_buyer_term = DorisHelper.spark_import_with_sql(session=self.spark, query=sql, use_type='adv')

    def handle_data(self):
        df_all_search_term = self.df_search_for_buyer_term.unionByName(
            self.df_positioning_for_buyer_term)
        window = Window.partitionBy(['search_term', 'report_date']).orderBy(
            df_all_search_term.orders.desc()
        )
        df_all_search_term = df_all_search_term.withColumn("st_rank", F.row_number().over(window=window))
        self.df_save = df_all_search_term.filter("st_rank = 1")
        self.df_save = self.df_save.select("search_term", F.col("sales").cast("double").alias("sales"),
                                           "orders", "clicks", "report_date")
        self.df_save = self.df_save.withColumn("created_time",
                                               F.date_format(F.current_timestamp(), 'yyyy-MM-dd HH:mm:SS')). \
            withColumn("updated_time", F.date_format(F.current_timestamp(), 'yyyy-MM-dd HH:mm:SS'))
        self.df_save = self.df_save.withColumn("string_field1", F.lit("null"))
        self.df_save = self.df_save.withColumn("string_field2", F.lit("null"))
        self.df_save = self.df_save.withColumn("string_field3", F.lit("null"))
        self.df_save = self.df_save.withColumn("int_field1", F.lit(0))
        self.df_save = self.df_save.withColumn("int_field2", F.lit(0))
        self.df_save = self.df_save.withColumn("int_field3", F.lit(0))
        self.df_save = self.df_save.withColumn("site_name", F.lit(self.site_name))
        self.df_save = self.df_save.withColumn("date_type", F.lit(self.date_type))
        self.df_save = self.df_save.withColumn("date_info", F.lit(self.date_info))


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 = DwdBuyerSt(site_name=site_name, date_type=date_type, date_info=date_info)
    handle_obj.run()
    cmd = f"""
          set mapred.output.compress=true;
          set hive.exec.compress.output=true;
          set mapred.output.compression.codec=com.hadoop.compression.lzo.LzopCodec;
          insert overwrite table big_data_selection.dwd_buyer_st partition(site_name="{site_name}", date_type="{date_type}", date_info="{date_info}") select search_term, sales, orders, clicks, report_date, created_time, updated_time, string_field1, string_field2, string_field3, int_field1, int_field2, int_field3 from big_data_selection.dwd_buyer_st where site_name="{site_name}" and date_type="{date_type}" and date_info="{date_info}" and report_date is not null;
          msck repair table big_data_selection.dwd_buyer_st;
      """
    print("cmd=", cmd)
    CommonUtil.hive_cmd_exec(cmd)
