import datetime
import time
import os


class ListenSearchTerm():

    def __init__(self, site_name='us', date_type='week', data_type=1, date=None):
        self.site_name = site_name
        self.date_type = date_type
        self.data_type = data_type
        self.listen_dict = {
            "data_type": {
                1: "search_term",  # 关键词抓取
                2: "asin_detail",  # asin详情抓取
            }
        }
        # 初始化日期相关变量
        self.date = date
        self.year = int()
        self.week = int()
        self.week_day = int()
        self.current_date = str()

    def get_week_from_date(self):
        if not self.date:
            # 以当前程序运行的日期为准
            self.year, self.week, self.week_day = datetime.datetime.now().isocalendar()
            self.current_date = time.strftime("%Y-%m-%d", time.localtime())
            print("current_date:", self.current_date)
        else:
            # 自定义输入日期, 如: 2022-09-08
            y, m, d = self.date.split("-")
            self.year, self.week, self.week_day = datetime.datetime(int(y), int(m), int(d)).isocalendar()
            print("current_date:", self.date)
        print("site_name, year, week, week_day:", self.site_name, self.year, self.week, self.week_day)

    def run_shell_by_judge_data_type(self):
        # ods层：执行关键词导入--search_term_rank_type, brand_analytics_week, asin_detail_simply
        os.system(f"/opt/module/spark/demo/sqoop_script/ods/search_term_rank_type.sh {self.site_name} all {self.year} {self.week}")
        os.system(f"/opt/module/spark/demo/sqoop_script/ods/brand_analytics_week.sh  {self.site_name} {self.year} {self.week}")
        os.system(f"/opt/module/spark/demo/sqoop_script/ods/asin_detail_simply.sh  {self.site_name} {self.year} {self.week}")
        # dim层：dim_st_year_week和dim_st_asin_base_info计算
        os.system(f"/opt/module/spark/demo/spark_demo/dim/spark_dim_st_year_week.sh {self.site_name} {self.year} {self.week}")
        os.system(f"/opt/module/anaconda3/envs/pyspark/bin/python3.8 /opt/module/spark/demo/py_demo/demo_sqoop/export_dim_st_year_week.py {self.site_name} {self.year}-{self.week}")
        os.system(f"/opt/module/spark/demo/spark_demo/dim/spark_dim_st_asin_base_info.sh {self.site_name} {self.year} {self.week}")
        # dwd层：
        os.system(f"/opt/module/spark/demo/spark_demo/dwd/spark_dwd_st_info.sh {self.site_name} {self.date_type} {self.year}-{self.week}")
        os.system(f"/opt/module/spark/demo/spark_demo/dwd/spark_dwd_asin_and_st_counts.sh {self.site_name} {self.date_type} {self.year}-{self.week}")

    def run(self):
        self.get_week_from_date()


if __name__ == '__main__':
    handle_obj = ListenSearchTerm(date='2022-09-08')
    handle_obj.run()