import ddddocr
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import traceback
import re

DRIVER_PATH = "chromedriver-win64\\chromedriver.exe"
VOTE_URL = "https://test-h5.hudongtang.cn/doings/?eid=144&channel=web&withUserAgent=true#/home/aqe"
CAPTCHA_CONFIG = {
    "tip_locator": (By.CLASS_NAME, "code-thumb"),    # 顶部提示
    "img_locator": (By.CLASS_NAME, "code-picture"),  # 验证码图片
    "success_locator": (By.XPATH, "//*[contains(text(), '验证成功') or contains(text(), '投票成功')]")
}

# 初始化ddddocr
ocr = ddddocr.DdddOcr(det=True)
# 初始化浏览器
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(service=Service(DRIVER_PATH), options=options)
driver.maximize_window()
wait = WebDriverWait(driver, 15)

def test_point_captcha_auto_verify():
    is_pass = False
    target_rects = [] 
    try:
        # 1. 打开页面+触发验证码
        driver.get(VOTE_URL)
        print("打开投票链接，等待加载...")
        time.sleep(4)
        
        # 点击投票按钮
        vote_btn = wait.until(EC.element_to_be_clickable((By.TAG_NAME, "button")))
        vote_btn.click()
        print("点击投票按钮，触发点选验证码")
        time.sleep(3)

        # 定位验证码图片
        captcha_img = wait.until(EC.presence_of_element_located(CAPTCHA_CONFIG["img_locator"]))
        print("定位到验证码图片（code-picture）")

        # 截图+识别
        captcha_img.screenshot("captcha.png")
        with open("captcha.png", "rb") as f:
            target_rects = ocr.detection(f.read())
        print(f"机器识别到 {len(target_rects)} 个目标矩形坐标：{target_rects}")

        # 4点击
        action = ActionChains(driver)
        for rect in target_rects:
            x1, y1, x2, y2 = rect
            center_x = (x1 + x2) / 2
            center_y = (y1 + y2) / 2
            action.move_to_element_with_offset(captcha_img, center_x, center_y).click().perform()
            print(f"✅ 机器点击矩形中心坐标：({center_x:.1f}, {center_y:.1f})")
            time.sleep(0.1)

        # 5. 验证是否自动通过
        print("✅ 等待验证码自动验证...")
        time.sleep(2)
        try:
            success_elem = wait.until(EC.presence_of_element_located(CAPTCHA_CONFIG["success_locator"]))
            if success_elem:
                is_pass = True
                print("🎉 验证码自动验证通过！")
        except:
            print("验证码验证失败（机器逻辑未通过）")

    except Exception as e:
        print("测试出错：", str(e))
        print("报错详情：", traceback.format_exc())
    finally:
        print("\n===== 测试结果汇总 =====")
        print(f"是否通过验证：{is_pass}")
        print(f"机器识别矩形坐标：{target_rects}")
        time.sleep(3)
        driver.quit()

if __name__ == "__main__":
    test_point_captcha_auto_verify()