from __future__ import annotations

from playwright.sync_api import Page

from e2e.pages.admin_page import AdminPage


class AdminApplicationPage(AdminPage):
    def open_application_request_list(self) -> None:
        self.maybe_click_text(["产品管理"], timeout=3000)
        self.click_exact_text("产品申请列表", timeout=5000)
        self.page.wait_for_load_state("domcontentloaded")
        self.page.wait_for_timeout(2000)

    def approve_product_application(
        self,
        enterprise_name: str,
        product_name: str,
        merchant_id: str = "",
        product_id: str = "",
    ) -> None:
        self.open_application_request_list()
        if merchant_id or product_id:
            self.search_product_application(merchant_id=merchant_id, product_id=product_id)
        elif enterprise_name:
            self.search_product_application(keyword=enterprise_name)

        row = self.find_application_row(enterprise_name, product_name, merchant_id=merchant_id, product_id=product_id)
        if row is None:
            row = self.find_application_row("", product_name, merchant_id=merchant_id, product_id=product_id)
        if row is None and product_id:
            row = self.find_application_row("", "", merchant_id=merchant_id, product_id=product_id)

        if row is None:
            approved_row = self.find_application_row(
                enterprise_name,
                product_name,
                merchant_id=merchant_id,
                product_id=product_id,
                accepted_statuses=["审核通过", "已通过", "已开通"],
            )
            if approved_row is not None:
                return
            raise AssertionError(f"主站产品申请列表未找到 {enterprise_name} 的 {product_name} 待审核申请")

        for action in ("审核", "同意", "通过", "查看"):
            action_button = row.get_by_text(action, exact=True).first
            if action_button.count():
                action_button.click()
                break
        else:
            raise AssertionError(f"主站产品申请列表中 {product_name} 申请行未找到审批入口")

        self.page.wait_for_timeout(1000)
        self.submit_product_application_audit()
        self.page.wait_for_timeout(2000)

    def submit_product_application_audit(self) -> None:
        remark = self.page.locator(".ant-modal textarea[placeholder='请输入审核备注']").first
        if remark.count():
            remark.fill("E2E自动化审核通过")

        self.click_first_visible(
            [
                ".ant-modal button:has-text('提 交')",
                ".ant-modal button:has-text('提交')",
                "button:has-text('提 交')",
                "button:has-text('提交')",
            ],
            timeout=5000,
        )
        self.maybe_click_text(["确定", "确认"], timeout=3000)

    def search_product_application(self, merchant_id: str = "", product_id: str = "", keyword: str = "") -> None:
        if merchant_id:
            self.fill_first_visible(["input[placeholder='请输入商户ID']"], merchant_id, timeout=3000)
        if product_id:
            self.fill_first_visible(["input[placeholder='请输入产品ID']"], product_id, timeout=3000)
        if keyword:
            try:
                self.fill_first_visible(
                    [
                        "input[placeholder*='商户名称']",
                        "input[placeholder*='企业名称']",
                        "input[placeholder*='用户名称']",
                        "input[placeholder*='名称']",
                    ],
                    keyword,
                    timeout=2000,
                )
            except AssertionError:
                pass
        self.click_exact_text("查询", timeout=3000)
        self.page.wait_for_timeout(2000)

    def filter_application_status(self, statuses: list[str]) -> None:
        selector = self.page.locator(".ant-select-selector").filter(has_text="申请状态").first
        if not selector.count():
            selector = self.page.locator(".ant-select-selector").first
        if not selector.count():
            return

        for status in statuses:
            try:
                selector.click(timeout=1000)
                self.page.get_by_text(status, exact=True).first.click(timeout=1000)
                self.page.wait_for_timeout(1000)
                return
            except Exception:
                continue

    def find_application_row(
        self,
        enterprise_name: str,
        product_name: str,
        merchant_id: str = "",
        product_id: str = "",
        accepted_statuses: list[str] | None = None,
    ):
        accepted_statuses = accepted_statuses or ["待审核", "审核中", "申请中", "待通过", "待审批", "审核中"]
        rows = self.page.locator(".ant-table-row")
        for index in range(rows.count()):
            row = rows.nth(index)
            text = row.inner_text(timeout=1000)
            columns = [item.strip() for item in text.split("\t")]
            if merchant_id and merchant_id not in columns:
                continue
            if product_id and product_id not in columns:
                continue
            if product_name and not product_id and product_name not in text:
                continue
            if enterprise_name and enterprise_name not in text:
                continue
            if not any(status in text for status in accepted_statuses):
                continue
            return row
        return None
