import datetime
import os
import sys
import time

import requests

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from listen_program.listen_program import ListenProgram


class WorkflowDimStYearWeek(ListenProgram):

    def __init__(self):
        super().__init__(site_name=site_name, year=year, week=week, listen_type=listen_type, listen_type_detail=listen_type_detail)

    def send_message_wx(self):
        url = 'http://47.112.96.71:8082/selection/sendMessage'
        data = {
            'account': 'wangfeng,fangxingjun',
            'title':  f'{self.site_name}_st_year_week',
            'content': f'{self.year}-{self.week}周, {self.site_name}_st_year_week计算完成并导出到mysql, 时间:{datetime.datetime.now()}'
        }
        for i in range(3):
            try:
                requests.post(url=url, data=data, timeout=15)
                break
            except Exception as e:
                print(f"第{i}次失败, 等待60s继续")
                time.sleep(60)
                continue

    def run(self):
        print("开始导入ods_brand_analytics_week数据")  # self.site_name, 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}")
        print("开始计算dim_st_year_week数据")
        os.system(f"/opt/module/spark/demo/spark_demo/dim/spark_dim_st_year_week.sh {self.site_name} {self.year} {self.week}")
        print("开始导出dim_st_year_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}")
        self.send_message_wx()


if __name__ == '__main__':
    if len(sys.argv) == 4:
        site_name = sys.argv[1]  # 参数1：站点
        listen_type = sys.argv[2]  # 参数2：监听类型
        listen_type_detail = sys.argv[3]  # 参数3：监听类型的详情
        year, week, week_day = datetime.datetime.now().isocalendar()
        current_date = time.strftime("%Y-%m-%d", time.localtime())
        print(f"默认按照程序开始执行的日期监听, current_date: {current_date}")
        print(f"year: {year}, week: {week}")
    else:
        site_name = sys.argv[1]  # 参数1：站点
        year = int(sys.argv[2])  # 参数2：年
        week = int(sys.argv[3])  # 参数3：周
        listen_type = sys.argv[4]  # 参数4：监听类型
        listen_type_detail = sys.argv[5]  # 参数5：监听类型的详情
        print(f"自定义周期监听")
        print(f"year: {year}, week: {week}")

    handle_obj = WorkflowDimStYearWeek()
    handle_obj.listen()
    handle_obj.run()
