import sys
import os

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from amazon_params.params import DB_CONN_DICT
from amazon_params.params import PG_CONN_DICT
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
import pymysql
import requests
import traceback
import time
from sqlalchemy.engine import URL

class connect_db():
    """
    构造 mysql 链接
        pg 数据库链接
        us 站点 链接
        推送消息通知
    """

    def __init__(self, site):
        self.site_name = site
        print('连接站点：', site)
        # self.mysql_db()

    def mysql_db(self):
        print('连接mysql')
        nums = 0
        while True:
            nums += 1
            try:
                if self.site_name == 'us':
                    connect_mysql_db = pymysql.connect(host=DB_CONN_DICT['mysql_host'], port=DB_CONN_DICT['mysql_port'],
                                                       user=DB_CONN_DICT['mysql_user'],
                                                       password=DB_CONN_DICT['mysql_pwd'], database="selection",
                                                       charset="utf8mb4")
                else:
                    connect_mysql_db = pymysql.connect(host=DB_CONN_DICT['mysql_host'], port=DB_CONN_DICT['mysql_port'],
                                                       user=DB_CONN_DICT['mysql_user'],
                                                       password=DB_CONN_DICT['mysql_pwd'],
                                                       database="selection_" + self.site_name,
                                                       charset="utf8mb4")
                self.cursor_mysql_db = connect_mysql_db.cursor()
                # 返回游标。链接
                return self.cursor_mysql_db, connect_mysql_db
            except Exception as e:
                time.sleep(nums * 20)
                print("error_mysql_connec:", e, f"\n{traceback.format_exc()}")
                continue

    def us_mysql_db(self):
        print('连接mysql us站点')
        nums = 0
        while True:
            nums += 1
            try:
                connect_us = pymysql.connect(host=DB_CONN_DICT['mysql_host'], port=DB_CONN_DICT['mysql_port'],
                                             user=DB_CONN_DICT['mysql_user'],
                                             password=DB_CONN_DICT['mysql_pwd'], database="selection",
                                             charset="utf8mb4")
                self.cursor_us = connect_us.cursor()
                # 只返回 us 站点的游标和链接
                return self.cursor_us, connect_us
            except Exception as e:
                time.sleep(nums * 20)
                print("us_mysql_db 函数:", e, f"\n{traceback.format_exc()}")
                continue

    def pg_db(self):
        print('连接pg')
        nums = 0
        while True:
            nums += 1
            try:
                if self.site_name == 'us':
                    db = 'selection'
                else:
                    db = f'selection_{self.site_name}'
                # self.engine_pg = create_engine(
                #     f"postgresql+psycopg2://{PG_CONN_DICT['pg_user']}:{PG_CONN_DICT['pg_pwd']}@{PG_CONN_DICT['pg_host']}:{PG_CONN_DICT['pg_port']}/{db}",
                #     encoding='utf-8', connect_args={"connect_timeout": 10}, poolclass=NullPool,pool_pre_ping=True,pool_recycle=1200)

                self.engine_pg = create_engine(
                    f"postgresql+psycopg2://{PG_CONN_DICT['pg_user']}:{PG_CONN_DICT['pg_pwd']}@{PG_CONN_DICT['pg_host']}:{PG_CONN_DICT['pg_port']}/{db}",
                    encoding='utf-8', connect_args={"connect_timeout": 10}, pool_size=5,
                    max_overflow=10,
                    pool_recycle=1200,     # recycle connections older than 20 min
                    pool_pre_ping=True)


                return self.engine_pg
            except Exception as e:
                print("error_pg_connect:", e, f"\n{traceback.format_exc()}")
                time.sleep(nums * 20)
                continue


    def mysql_engine(self):
        nums = 0
        while True:
            nums += 1
            try:
                if self.site_name == 'us':
                    db = 'selection'
                else:
                    db = f'selection_{self.site_name}'
                url = URL.create(
                    drivername="mysql+pymysql",
                    username=DB_CONN_DICT["mysql_user"],
                    password=DB_CONN_DICT["mysql_pwd"],  # 原始密码，含 @ 也没问题
                    host=DB_CONN_DICT["mysql_host"],
                    port=int(DB_CONN_DICT["mysql_port"]),
                    database=db,
                    query={"charset": "utf8mb4"}
                )
                return create_engine(url)
            except Exception as e:
                print("error_mysql_connect:", e, f"\n{traceback.format_exc()}")
                time.sleep(nums * 20)
                continue

    def send_mg(self, account, title, content):
        url = 'http://47.112.96.71:8082/selection/sendMessage'
        data = {
            'account': account,
            'title': title,
            'content': content
        }
        print(data)
        requests.post(url=url, data=data, timeout=15)

    # def run(self):
    #     self.cursor_us, connect_us = self.us_mysql_db()
    #     up_spider_state_sql = f"select id from workflow_progress where date_info='2024-23' and date_type='week' and site_name='us' and page='ASIN详情' and up_spider_state=3"
    #     print(up_spider_state_sql)
    #     self.cursor_us.execute(up_spider_state_sql)
    #     up_spider_state_list = self.cursor_us.fetchone()
    #     if up_spider_state_list:
    #         print(up_spider_state_list)
    #     else:
    #         print(333333)

# if __name__ == '__main__':
#     connect_db(site='us').run()