from __future__ import annotations

from playwright.sync_api import Page

from e2e.pages.base_page import BasePage


class AdminPage(BasePage):
    def __init__(self, page: Page, admin_url: str):
        super().__init__(page)
        self.admin_url = admin_url

    def login(self, username: str, password: str) -> None:
        login_url = self.admin_url.replace("/pages/home/index", "/pages/login/index")
        self.goto(login_url)
        self.page.wait_for_load_state("domcontentloaded")
        self.page.wait_for_timeout(1500)
        self.fill_first_visible(
            [
                "input[placeholder*='请输入账号']",
                "input[placeholder*='账号']",
                "input[placeholder*='用户名']",
                "input[name='username']",
                "input[type='text']",
            ],
            username,
            timeout=10000,
        )
        self.fill_first_visible(
            [
                "input[placeholder*='请输入密码']",
                "input[placeholder*='密码']",
                "input[name='password']",
                "input[type='password']",
            ],
            password,
            timeout=10000,
        )
        self.click_first_visible(
            [
                "taro-button-core:has-text('登录')",
                "button:has-text('登录')",
                "button:has-text('登 录')",
                "button[type='submit']",
            ]
        )

    def approve_enterprise_certification(self, enterprise_name: str) -> None:
        self.maybe_click_text(["商户管理", "企业管理", "租户管理", "认证管理"], timeout=3000)
        self.maybe_click_text(["商户认证", "企业认证", "认证审核", "待审核"], timeout=3000)

        search_input = self.page.locator(
            "input[placeholder*='用户名称'], input[placeholder*='用户'], input[placeholder*='企业'], input[placeholder*='商户'], input[placeholder*='名称'], input[placeholder*='关键字']"
        ).first
        if search_input.count():
            search_input.fill(enterprise_name)
            self.maybe_click_text(["查询", "搜索"], timeout=1000)

        row = self.page.locator(".ant-table-row", has_text=enterprise_name).first
        row.wait_for(state="visible", timeout=10000)

        audit_button = row.get_by_text("审核", exact=True).first
        if audit_button.count():
            audit_button.click()
        else:
            row.get_by_text("查看", exact=True).first.click()
            self.maybe_click_text(["审核"], timeout=1500)

        self.page.locator(".ant-modal .ant-select-selector").click()
        self.page.get_by_text("通过", exact=True).click()
        self.click_first_visible([".ant-modal button:has-text('提 交')", ".ant-modal button:has-text('提交')"], timeout=5000)
        self.maybe_click_text(["确定", "确认"], timeout=3000)
