"""管理端 — 运输管理 — 运单核算 Page Object。

覆盖步骤:
    5. 核算运单 (do_accounting)
    6. 核算审核 (do_review)

Usage:
    waybill_page = WaybillManagementPage(page)
    waybill_page.do_accounting(order_no)
    waybill_page.do_review(order_no)
"""

from playwright.sync_api import Page

from tests.web.admin.pages.base_page import BasePage


class WaybillManagementPage(BasePage):
    """管理端 - 运输管理 - 运单管理/核算。"""

    def __init__(self, page: Page):
        super().__init__(page)
        # ⚠️ 以下定位器需要根据实际 DOM 调整

        # ── 搜索区 ──
        self.search_order_input = page.get_by_placeholder("请输入订单号")            # ⚠️
        self.search_btn = page.get_by_role("button", name="查询")                  # ⚠️

        # ── 操作按钮 ──
        self.accounting_btn = page.get_by_role("button", name="核算")              # ⚠️ 核算运单
        self.review_btn = page.get_by_role("button", name="审核")                  # ⚠️ 核算审核
        self.confirm_btn = page.get_by_role("button", name="确定")                 # ⚠️ 确认弹窗

        # ── 结果元素 ──
        self.success_toast = page.locator(".el-message--success")                  # ⚠️
        self.table_first_row = page.locator(".el-table__body tr:first-child")     # ⚠️ 列表第一行

    def search_order(self, order_no: str) -> None:
        """搜索运单。"""
        self.fill_field(self.search_order_input, order_no)
        self.click_when_ready(self.search_btn)
        self.page.wait_for_timeout(1000)

    def click_accounting(self) -> None:
        """点击核算按钮。"""
        self.click_when_ready(self.accounting_btn)
        self.page.wait_for_timeout(500)

    def click_review(self) -> None:
        """点击审核按钮（核算审核）。"""
        self.click_when_ready(self.review_btn)
        self.page.wait_for_timeout(500)

    def confirm_action(self) -> None:
        """确认操作弹窗。"""
        # ⚠️ 可能没有确认弹窗，try 一下
        try:
            if self.confirm_btn.is_visible():
                self.click_when_ready(self.confirm_btn)
                self.page.wait_for_timeout(500)
        except Exception:
            pass

    def do_accounting(self, order_no: str) -> None:
        """完整的核算运单流程: 搜索 → 核算 → 确认。

        Args:
            order_no: 订单号
        """
        self.search_order(order_no)
        self.page.wait_for_timeout(500)
        self.click_accounting()
        self.confirm_action()

        # 等待核算完成
        self.has_success_toast()

    def do_review(self, order_no: str) -> None:
        """完整的核算审核流程: 搜索 → 审核 → 确认。

        Args:
            order_no: 订单号
        """
        self.search_order(order_no)
        self.page.wait_for_timeout(500)
        self.click_review()
        self.confirm_action()

        # 等待审核完成
        self.has_success_toast()

    def has_success_toast(self) -> bool:
        """检查操作是否成功（有成功 toast）。"""
        try:
            self.wait_visible(self.success_toast, timeout_ms=5_000)
            return True
        except Exception:
            return False
