import time
import uuid

from pymysql.cursors import DictCursor
import json
import pymysql
import  os,sys
from dbutils.pooled_db import PooledDB


DB_CONFIG = {
    'host': "tenant-2101894307-cn-beijing-public.bytehouse.volces.com",
    'port': 3306,
    'user': "bytehouse",
    'password': "JkoyoRV3PH:7YaWLXRwAO",
    'database': "douchacha_data",
    'charset': 'utf8mb4',
}
#

POOL = PooledDB(
    creator=pymysql,
    maxconnections=50,
    mincached=5,
    maxcached=20,
    blocking=True,
    ping=4,
    cursorclass=DictCursor,
    autocommit=True,
    connect_timeout=5,
    read_timeout=30,
    write_timeout=30,
    **DB_CONFIG
)


def query_data(sql, params=None, size=None):
    conn = None
    try:
        conn = POOL.connection()
        with conn.cursor() as cursor:

            cursor.execute(sql, params)
            if size is None:
                return cursor.fetchall()
            return cursor.fetchmany(size)
    except Exception as e:
        print(f"查询数据失败: {e}")
        return None
    finally:
        if conn is not None:
            conn.close()


def insert_data(table_name, items) -> bool:
    conn = None
    try:
        # 检查输入是否为空
        if not items:
            return False

        conn = POOL.connection()
        with conn.cursor() as cursor:

            cols = items[0].keys()
            cols_str = ", ".join(cols)
            placeholders = ", ".join(["%s"] * len(cols))

            processed_data = []
            for item in items:
                row = []
                for key in cols:
                    value = item[key]
                    if isinstance(value, list):
                        row.append(json.dumps(value, ensure_ascii=False))
                    else:
                        row.append(value)
                processed_data.append(tuple(row))

            insert_sql = f"INSERT INTO {table_name} ({cols_str}) VALUES ({placeholders})"
            cursor.executemany(insert_sql, processed_data)

            return True
    except Exception as e:
        print(f"插入数据失败: {str(e)}")
        return False
    finally:
        if conn is not None:
            conn.close()


# 示例调用
if __name__ == "__main__":
    import time
    from concurrent.futures import ThreadPoolExecutor, as_completed

    TASK_ID = "6751e32e-d87a-4ed4-a914-5b9893c45371"
    PLATFORM = "KIMI"

    SQL = f"""
        INSERT INTO geo_commit_task (brandWords, comWords, platform, prompt, reqId, searchEnabled, taskId, thinkingEnabled, type, thinking_enabled, search_enabled, insertime, status) VALUES ('[\"爱搜\", \"AIDSO\"]', '[]', 'DOUBA', '视频内容优化服务适用于哪些具体场景？', '51f7307e004449e9a30acd87394fca1b', 1, '875eee49002a4182b4c8b1ce7a4d09b1', 1, 'stream_batch', '1', '1', 1774323442, 'ING')
    """

    import uuid


    def run_query():
        random_uuid = str(uuid.uuid4())
        data = [
            {
                "brandWords": '[\"爱搜\", \"AIDSO\"]',
                "comWords": "[]",
                "platform": 'DOUBA',
                "prompt": '视频内容优化服务适用于哪些具体场景',
                "reqId": random_uuid,
                "searchEnabled": ["程序员", "Go"],
                "taskId": random_uuid,
                "thinkingEnabled": 3,
                "search_enabled":3,
                "insertime": 1774323442,
                "status": 'SUCCESS',
            }]
        return insert_data("geo_commit_task",data)


    while True:
        with ThreadPoolExecutor(max_workers=200) as executor:
            futures = [executor.submit(run_query) for _ in range(50)]

            for future in as_completed(futures):
                try:
                    result = future.result()
                    print(result)
                except Exception as e:
                    print("查询异常:", e)