from __future__ import annotations

from pathlib import Path

from playwright.sync_api import sync_playwright


def main() -> None:
    reports = Path("reports")
    reports.mkdir(exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto("https://test-saas-adminui.lianlianwz.com/pages/login/index", wait_until="domcontentloaded")
        page.wait_for_timeout(1500)
        page.locator("input[type='text']").first.fill("wangss")
        page.locator("input[type='password']").first.fill("123456")
        page.get_by_text("登录", exact=False).first.click()
        page.wait_for_load_state("domcontentloaded")
        page.wait_for_timeout(5000)
        print("ADMIN_URL", page.url)
        print(page.locator("body").inner_text(timeout=10000)[:10000])
        page.get_by_text("应用管理", exact=True).first.click()
        page.wait_for_timeout(1500)
        print("AFTER_APP_MENU")
        print(page.locator("body").inner_text(timeout=10000)[:12000])
        for text in ["应用开通", "应用审核", "商户应用", "应用申请", "开通审核", "产品授权"]:
            loc = page.get_by_text(text, exact=False).first
            try:
                box = loc.bounding_box(timeout=500)
                print("CANDIDATE", text, box)
            except Exception:
                pass
        page.get_by_text("应用申请列表", exact=True).click()
        page.wait_for_load_state("domcontentloaded")
        page.wait_for_timeout(4000)
        print("AFTER_APPLICATION_LIST")
        print(page.locator("body").inner_text(timeout=10000)[:12000])
        elements = page.evaluate(
            """() => Array.from(document.querySelectorAll('input,textarea,button,taro-button-core,taro-view-core,a,.ant-menu-item,.ant-menu-submenu-title,.ant-table-row,.ant-select-selector,[class*=menu],[class*=nav]'))
                .map((e, i) => {
                    const r = e.getBoundingClientRect();
                    return {
                        i,
                        tag: e.tagName,
                        id: e.id,
                        href: e.getAttribute('href'),
                        placeholder: e.getAttribute('placeholder'),
                        text: (e.innerText || e.textContent || '').trim(),
                        cls: String(e.className),
                        x: Math.round(r.x),
                        y: Math.round(r.y),
                        w: Math.round(r.width),
                        h: Math.round(r.height),
                        visible: !!(r.width && r.height)
                    };
                })
                .filter(x => x.visible && x.text)
                .slice(0, 500)"""
        )
        for item in elements:
            print(item)
        page.screenshot(path=str(reports / "admin-app-approval-probe.png"), full_page=True)
        browser.close()


if __name__ == "__main__":
    main()
