import time
from concurrent.futures import ThreadPoolExecutor,as_completed

import requests
import json

from py_spider.utils.secure_db_client import get_remote_engine

url = "http://192.168.200.210:5000/api/search_image"
# url = "http://127.0.0.1:5000/api/search_image"

# 请求参数
payload = {
    # 图片链接
    # "image_url": "https://m.media-amazon.com/images/I/31Yq1IRqKGL._SR240,220_.jpg", # ok
    # "image_url": "https://m.media-amazon.com/images/I/21cOsqYwDjL._SR480,440_.jpg", # ok
    # "image_url": "https://m.media-amazon.com/images/I/21cOsqYwDjL._SR480,440_.jpg", # ok
    # "image_url": "https://m.media-amazon.com/images/I/41vTSMa6mNL._SR480,440_.jpg", # ok
    # "image_url": "https://m.media-amazon.com/images/I/71G1BAeYlNL._AC_SX300_SY300_QL70_FMwebp_.jpg", # no
    # "image_url": "https://m.media-amazon.com/images/I/41ryNvEnNCL._AC_SL1500_.jpg", # ok
    # "image_url": "https://m.media-amazon.com/images/I/71IFE6W6THL._AC_SY550_.jpg", # ok
    # "image_url": "https://soundasia.oss-cn-shenzhen.aliyuncs.com/yswg-img-test/SoundasiaAmazon/competitor_image/2025/1124/84759f5d6514435e83d0fb728a57451c.jpg", # ok
    "image_url": "https://imgtool.net/cdn/image/2023/20230401_1.jpg", # ok
    # 站点
    "site_name": "us",
    # 模式 (default: 普通模式, full_image: 全图模式) 主要针对app端识别
    # "search_mode": "full_image" # 不传走默认 default
}

def send_request(url1):
    """发送单个请求，返回（是否成功、响应时间）"""
    start = time.time()
    try:
        payload = {
            # 图片链接
            "image_url": url1,  # ok
            # 站点
            "site_name": "us",
        }
        response = requests.post(url, json=payload, timeout=120,allow_redirects=False )
        print(response.json())
        return (response.status_code == 200, round(time.time() - start, 4))
    except:
        return (False, 5)  # 失败时响应时间记为超时时间
try:
    print("开始请求!")
    # 发送 POST 请求
    # response = requests.post(url, json=payload, timeout=120)
    thread_num = 5 # 线程数
    # 2. 多线程测试
    success = 0
    response_times = []
    start_total = time.time()
    engine = get_remote_engine(site_name='us', db_type="mysql")
    sql_get = "SELECT  img_url FROM us_inv_img_info  ORDER BY updated_at DESC LIMIT 10, 10"
    get_df_data = engine.read_sql(sql_get).to_dict("records")
    total_req_list = [i.get('img_url') for i in get_df_data]
    print(total_req_list)
    # 线程池执行任务
    with ThreadPoolExecutor(max_workers=thread_num) as executor:
        # 提交所有请求任务
        tasks = [executor.submit(send_request,url1) for url1 in total_req_list]
        # 遍历结果
        for task in as_completed(tasks):
            ok, t = task.result()
            if ok:
                success += 1
                response_times.append(t)
    total_time = round(time.time() - start_total, 2)
    success_rate = (success / len(total_req_list)) * 100
    avg_time = round(sum(response_times)/len(response_times), 4) if response_times else 0

    print(f"总请求数：{len(total_req_list)} | 成功数：{success} | 成功率：{success_rate:.2f}%")
    print(f"总耗时：{total_time}秒 | 平均响应时间：{avg_time}秒")
    print(f"QPS（每秒请求数）：{len(total_req_list)/total_time:.2f}")

    # 解析结果
    # response = requests.post(url, json=payload, timeout=120)
    # if response.status_code == 200:
    #     result = response.json()
    #     print("\n 请求成功!")
    #     print(f"状态码: {result['code']}")
    #     print(f"消息: {result['msg']}")
    #
    #
    #     data = result.get('data', {})
    #     print(f"识别成功: {data.get('success')}")
    #     print(f"找到商品数: {data.get('total_items')}")
    #     print(f"耗时: {data.get('duration')}")
    #     print(f"搜索url: {data.get('search_url')}")
    #     # 打印前3个商品看看
    #     # items = data.get('items', [])
    #     # if items:
    #     #     print("\n--- 商品示例 ---")
    #     #     for item in items:
    #     #         print(f"ASIN: {item['asin']} | 价格: {item['price']} | 评分：{item['rating']}  | img_url：{item['img_url']}  | 品牌名：{item['brand']}  | 销量：{item['bought']}  | 评论数：{item['total_comments']}  | asin来源：{item['source']}  | 标题: {item['title'][:50]}...")
    # else:
    #     print(f" 请求失败: {response.status_code}")
    #     print(response.text)

except Exception as e:
    print(f" 发生错误: {e}")