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
# from ..utils.utils import Utils
# 显示所有列
pd.set_option('display.max_columns', None)
# # 显示所有行
pd.set_option('display.max_rows', None)


class ListenWorkflow(Utils):

    def __init__(self, site_name='us', date_type='day', date_info='2022-01-01', status_val=1):
        super(ListenWorkflow, self).__init__()
        self.site_name = 'us'
        self.date_type = date_type
        self.date_info = date_info
        self.status_val = status_val
        self.status_val_dict = {
            4: ["搜索词爬取完成，停止监听", "搜索词还在爬取中，等待10分钟继续监听"],
            8: "ASIN导出完成",
            10: ["asin爬取完成，停止监听", "asin还在爬取中，等待10分钟继续监听"],
        }
        self.df_workflow = pd.DataFrame()
        self.connection(db_type="mysql", db_conn="mysql_aliyun")  # mysql连接
        self.site_name = site_name

    def read_data(self):
        sql = f"select * from workflow_everyday where report_date='{self.date_info}';"
        self.df_workflow = pd.read_sql(sql, con=self.engine)
        print(self.df_workflow.head())

    def listen_status(self):
        if self.status_val in [8]:
            self.change_status()
            quit()
        while True:
            sql = f"select * from workflow_everyday where report_date='{self.date_info}' and table_name='{self.site_name}_aba_last_day' and status_val={self.status_val};"
            df = pd.read_sql(sql, con=self.engine)
            if df.shape[0] > 0:
                print(self.status_val_dict[self.status_val][0])
                break
            else:
                sql = f"select * from workflow_everyday where report_date='{self.date_info}';"
                df = pd.read_sql(sql, con=self.engine)
                if list(df.status_val):
                    if list(df.status_val)[0] == self.status_val:
                        print(f"当前状态{list(df.status_val)[0]}等于监听的状态{self.status_val}, 停止")
                        break
                    else:
                        print(self.status_val_dict[self.status_val][1])
                        time.sleep(600)
                        continue
                print(self.status_val_dict[self.status_val][1])
                time.sleep(600)
                continue

    def change_status(self):
        with self.engine.begin() as conn:
            sql = f"""update selection.workflow_everyday set status_val={self.status_val},status='{self.status_val_dict[self.status_val]}' WHERE site_name='{self.site_name}' and report_date='{self.date_info}' and date_type='day'"""
            print("sql:", sql)
            conn.execute(sql)

    def run(self):
        self.read_data()
        self.listen_status()


if __name__ == '__main__':
    print("hello")
    site_name = sys.argv[1]  # 参数1：站点
    date_type = sys.argv[2]  # 参数2：类型：day/week/4_week/month/quarter
    date_info = sys.argv[3]  # 参数3：年-月-日/年-周/年-月/年-季, 比如: 2022-1
    status_val = int(sys.argv[4])  # 参数3：年-月-日/年-周/年-月/年-季, 比如: 2022-1
    handle_obj = ListenWorkflow(site_name=site_name, date_type=date_type, date_info=date_info, status_val=status_val)
    # handle_obj = ListenWorkflow(site_name='us', date_type='day', date_info='2022-11-28', status_val=8)
    handle_obj.run()