from __future__ import annotations

import sys
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from playwright.sync_api import sync_playwright

from e2e.pages.wanzhanggui_push_page import WanzhangguiPushPage


租户首页 = "https://test-lianlianyun.lianlianwz.com/home"
丸掌柜账号 = "19147509308"
丸掌柜密码 = "test123456"
输出目录 = Path("runtime/probes/wanzhanggui_dispatch_auto_select")


def 保存现场(page, frame, name: str) -> None:
    输出目录.mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    page.screenshot(path=输出目录 / f"{timestamp}-{name}.png", full_page=True)
    payload = frame.evaluate(
        """() => {
            const selector = document.querySelectorAll('.ant-modal .ant-select-selector')[1];
            const selected = selector
              ? Array.from(selector.querySelectorAll('.ant-select-selection-item-content'))
                  .map(el => (el.innerText || el.textContent || '').trim())
                  .filter(Boolean)
              : [];
            const options = Array.from(document.querySelectorAll(
                '.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option'
              )).map((option, index) => {
                const content = option.querySelector('.ant-select-item-option-content') || option;
                const r = option.getBoundingClientRect();
                return {
                  index,
                  text: (content.innerText || content.textContent || '').trim(),
                  ariaSelected: option.getAttribute('aria-selected'),
                  className: option.className,
                  rect: { x: r.x, y: r.y, width: r.width, height: r.height },
                };
              });
            return {
              bodyText: document.body.innerText,
              selected,
              options,
            };
        }"""
    )
    (输出目录 / f"{timestamp}-{name}.txt").write_text(str(payload), encoding="utf-8")


def main() -> None:
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=250)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        push_page = WanzhangguiPushPage(page, 租户首页)

        push_page.login_main_account(丸掌柜账号, 丸掌柜密码)
        frame = push_page.open_dispatch_strategy()
        strategy_name = f"E2E探测策略{datetime.now().strftime('%m%d%H%M%S')}"

        push_page.click_frame_button_by_js(frame, "新增策略")
        page.wait_for_timeout(1200)
        frame.locator(".ant-modal input[placeholder='例如: 默认推单策略']").first.fill(strategy_name)
        push_page.click_modal_radio(frame, "多工作室同时分发")
        push_page.select_modal_option(frame, 0, "丸友集")
        page.wait_for_timeout(1200)

        selector = frame.locator(".ant-modal .ant-select-selector").nth(1)
        selector.click(force=True)
        page.wait_for_timeout(800)
        保存现场(page, frame, "01-opened")

        options = frame.locator(
            ".ant-select-dropdown:not(.ant-select-dropdown-hidden) "
            ".ant-select-item-option:not(.ant-select-item-option-disabled)"
        )
        for index in range(min(2, options.count())):
            option = options.nth(index)
            text = option.locator(".ant-select-item-option-content").inner_text(timeout=5000).strip()
            box = option.bounding_box(timeout=5000)
            print(f"[probe] 点击第 {index + 1} 行：{text} box={box}")
            option.click(force=True, timeout=5000)
            page.wait_for_timeout(1200)
            保存现场(page, frame, f"0{index + 2}-after-click-{index + 1}")

        page.wait_for_timeout(5000)
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
