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

import pandas as pd

from utils.templates import Templates
from utils.DolphinschedulerHelper import DolphinschedulerHelper
from utils.db_util import DbTypes, DBUtil
from utils.common_util import CommonUtil


class DolProcessApi(Templates):

    def __init__(self, site_name='us', date_type="month", date_info='2024-03'):
        super().__init__()
        self.site_name = site_name
        self.date_type = date_type
        self.date_info = date_info
        self.engine_pg14 = DBUtil.get_db_engine(db_type=DbTypes.postgresql_14.name, site_name=self.site_name)
        self.engine_mysql = DBUtil.get_db_engine(db_type=DbTypes.mysql.name, site_name=self.site_name)

    def truncate_table_image_and_variation(self):
        """
        存储到pg集群之后的图片表和变体表，会清空爬虫库当前周期消费的图片表和详情表数据
        """
        with self.engine_pg14.begin() as conn:
            sql_truncate_image = f"truncate {self.site_name}_asin_image;"
            sql_truncate_variation = f"truncate {self.site_name}_asin_variation;"
            conn.execute(sql_truncate_image)
            conn.execute(sql_truncate_variation)
            print(f"清空爬虫库: {self.site_name}_asin_image表和{self.site_name}_asin_image完成, 启动{self.site_name}站点的30天/月调度")

    def start_process_instance(self):
        # if self.site_name == 'us':
            # 最后一周走月流程
            # year, week = self.year_week_tuple[-1].split("-")
            # sql = f"select count(*) as st_count from {self.site_name}_brand_analytics_{year} where week={week} ;"
            # print("sql:", sql)
        year, month = self.date_info.split("-")
        sql = f"select count(*) as st_count from {self.site_name}_brand_analytics_month_{year} where year={year} and month={int(month)} ;"
        print(f"sql: {sql}")
        df = pd.read_sql(sql, con=self.engine_mysql)
        if list(df.st_count)[0] >= 1_0000:
            # 表示月搜索词正常导入
            process_df_name = f"ALL-月流程-ABA+反查+流量选品"
        else:
            # 表示月搜索词未正常导入
            self.date_type = "month_week"
            process_df_name = f"ALL-30day+反查+流量选品"

        DolphinschedulerHelper.start_process_instance(
            project_name="big_data_selection",
            process_df_name=process_df_name,
            startParams={
                "site_name": self.site_name,
                "date_type": self.date_type,
                "date_info": self.date_info
            },
            warning_Type="ALL"
        )
        users = ["fangxingjun", "wangrui4", "pengyanbing", "chenyuanjie"]
        title = f"参数信息--{self.site_name}, {self.date_type}, {self.date_info}"
        content = f"触发调度--{process_df_name}"
        CommonUtil().send_wx_msg(users=users, title=title, content=content)

    def run(self):
        self.truncate_table_image_and_variation()
        self.start_process_instance()


if __name__ == '__main__':
    site_name = sys.argv[1]  # 参数1：站点
    date_type = sys.argv[2]  # 参数2：类型：week/4_week/month/quarter/day
    date_info = sys.argv[3]  # 参数3：年-周/年-月/年-季/年-月-日, 比如: 2022-1
    handle_obj = DolProcessApi(site_name=site_name, date_type=date_type, date_info=date_info)
    # handle_obj = DolProcessApi(site_name='uk', date_type='week', date_info='2024-14')
    handle_obj.run()
