import os
import sys
import pandas as pd
import time
import datetime

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


class ListenProgram(Utils):

    def __init__(self, site_name='us', year=2022, week=1, listen_type="search_term", listen_type_detail='st_01'):
    # def __init__(self):
        super(ListenProgram, self).__init__()
        self.site_name = site_name
        self.year = year
        self.week = week
        self.listen_type = listen_type
        self.listen_type_detail = listen_type_detail
        self.table_spider = "selection.workflow_crawling"
        self.table_calculation = "selection.workflow_exhibition"
        self.connection(db_type="mysql", db_conn="mysql_aliyun")  # mysql连接
        self.listen_dict = {
            "search_term": {
                "st_01": "关键词导入",
                "st_02": "关键词抓取",
            },
            "asin": {
                "asin_01": "asin详情抓取"
            },
            "feedback": {
                "fd_01": "店铺抓取"
            }
        }
        self.listen_value = self.listen_dict[self.listen_type][self.listen_type_detail]

    def read_workflow(self):
        pass

    def listen_search_term(self):
        while True:
            try:
                if self.listen_type_detail == "st_01":
                    # 1. 关键词导入--计算dim_st_year_week
                    sql = f"select * from {self.table_spider} WHERE week='{self.year}_{self.week}' and site_name='{self.site_name}' and data_type=1 and status in(2, 3);"
                elif self.listen_type_detail == "st_02":
                    # 2. 关键词抓取完成--计算dwt_st_info_day/week/month/quarter
                    sql = f"select * from {self.table_spider} WHERE week='{self.year}_{self.week}' and site_name='{self.site_name}' and data_type=1 and status=3;"
                else:
                    print(f"监听类型输入错误,停止监听")
                    break
                # print("sql:", sql)
                df = pd.read_sql(sql, con=self.engine)
                if df.shape[0] == 1:
                    print(f"监听到{self.listen_value}成功,请继续下一步操作")
                    break
                else:
                    time.sleep(1800)
                    continue

            except Exception as e:
                print(f"监听程序异常,等待100s重新监听", e)
                time.sleep(100)
                self.connection(db_type="mysql", db_conn="mysql_aliyun")  # mysql连接
                continue

    def listen_asin(self):
        while True:
            try:
                if self.listen_type_detail == "asin_01":
                    # 2. 关键词抓取完成--计算dwt_st_info_day/week/month/quarter
                    sql = f"select * from {self.table_spider} WHERE week='{self.year}_{self.week}' and site_name='{self.site_name}' and data_type=1 and status=2;"
                    df = pd.read_sql(sql, con=self.engine)
                    if df.shape[0] == 1:
                        print(f"监听到{self.listen_value}成功,请继续下一步操作")
                        break
                    else:
                        time.sleep(1800)
                        continue
                else:
                    print(f"监听类型输入错误,停止监听")
                    break
            except Exception as e:
                print(f"监听程序异常,等待100s重新监听", e)
                time.sleep(100)
                self.connection(db_type="mysql", db_conn="mysql_aliyun")  # mysql连接
                continue

    def listen_feedback(self):
        pass

    def listen(self):
        if self.listen_type == 'search_term':
            self.listen_search_term()
        elif self.listen_type == 'asin':
            self.listen_asin()
        elif self.listen_type == 'feedback':
            self.listen_feedback()
        else:
            print("输入类型错误, 监听停止")


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 = ListenProgram()
    handle_obj.listen()