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_order_page import WanzhangguiOrderPage


租户首页 = "https://test-lianlianyun.lianlianwz.com/home"
丸掌柜账号 = "19147509308"
丸掌柜密码 = "test123456"
来源单号 = "E2EORDER0605115628"
订单标题 = "E2E手工录单0605115628"
输出目录 = Path("runtime/probes/wanzhanggui_revoke_order")


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(
        """({ sourceOrderNo, orderTitle }) => {
            const rows = Array.from(document.querySelectorAll('tr, .ant-table-row, [class*="table"] [class*="row"]'))
              .map((row, index) => ({ row, index, text: (row.innerText || row.textContent || '').trim(), html: row.outerHTML, r: row.getBoundingClientRect() }))
              .filter(item => item.r.width > 0 && item.r.height > 0)
              .filter(item => item.text.includes(sourceOrderNo) || item.text.includes(orderTitle));
            const buttons = rows.flatMap(item =>
              Array.from(item.row.querySelectorAll('button, a, span, div')).map((el, index) => {
                const r = el.getBoundingClientRect();
                return {
                  rowIndex: item.index,
                  index,
                  text: (el.innerText || el.textContent || '').trim(),
                  tag: el.tagName,
                  className: String(el.className || ''),
                  rect: { x: r.x, y: r.y, width: r.width, height: r.height },
                };
              }).filter(btn => btn.rect.width > 0 && btn.rect.height > 0 && btn.text)
            );
            const dialogs = Array.from(document.querySelectorAll('.ant-modal, .ant-popover, .ant-popconfirm'))
              .map((el, index) => {
                const r = el.getBoundingClientRect();
                return {
                  index,
                  text: (el.innerText || el.textContent || '').trim(),
                  html: el.outerHTML,
                  rect: { x: r.x, y: r.y, width: r.width, height: r.height },
                };
              }).filter(item => item.rect.width > 0 && item.rect.height > 0);
            return {
              url: location.href,
              bodyText: document.body.innerText,
              rows: rows.map(item => ({ index: item.index, text: item.text, html: item.html })),
              buttons,
              dialogs,
            };
        }""",
        {"sourceOrderNo": 来源单号, "orderTitle": 订单标题},
    )
    (输出目录 / 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=120)
        context = browser.new_context(viewport={"width": 1920, "height": 1080})
        page = context.new_page()
        order_page = WanzhangguiOrderPage(page, 租户首页)
        order_page.login_main_account(丸掌柜账号, 丸掌柜密码)
        frame = order_page.open_order_management()
        order_page.search_order_if_possible(frame, 来源单号)
        page.wait_for_timeout(1500)
        保存现场(page, frame, "after-search")
        order_page.click_order_row_action(frame, 来源单号, 订单标题, ["撤销"])
        page.wait_for_timeout(1500)
        保存现场(page, frame, "after-click-revoke")
        print(f"[probe] 已保存订单行现场：{输出目录}")
        page.wait_for_timeout(10000)
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
