"""管理端 — 承运结算 — 打款 Page Object。

覆盖步骤:
    7. 货主打款 (do_shipper_payment)
    8. 平台打款给司机 (do_platform_payment)

Usage:
    settlement_page = SettlementPage(page)
    settlement_page.do_shipper_payment(order_no)
    settlement_page.do_platform_payment(order_no)
"""

from playwright.sync_api import Page

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


class SettlementPage(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.shipper_pay_btn = page.get_by_role("button", name="货主打款")         # ⚠️
        self.platform_pay_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.status_text = page.locator(".settlement-status")                     # ⚠️ 结算状态文本

    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 do_shipper_payment(self, order_no: str) -> None:
        """货主打款流程: 搜索 → 货主打款 → 确认。

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

        self.click_when_ready(self.shipper_pay_btn)
        self.page.wait_for_timeout(500)

        # 确认打款弹窗
        self._confirm_if_present()

        # 等待成功提示
        self.wait_visible(self.success_toast, timeout_ms=10_000)

    def do_platform_payment(self, order_no: str) -> None:
        """平台打款给司机流程: 搜索 → 平台打款 → 确认。

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

        self.click_when_ready(self.platform_pay_btn)
        self.page.wait_for_timeout(500)

        # 确认打款弹窗
        self._confirm_if_present()

        # 等待成功提示
        self.wait_visible(self.success_toast, timeout_ms=10_000)

    def _confirm_if_present(self) -> None:
        """如果有确认弹窗则点击确定。"""
        # ⚠️ 确认按钮可能以不同形式存在
        try:
            if self.confirm_btn.is_visible():
                self.click_when_ready(self.confirm_btn)
                self.page.wait_for_timeout(500)
        except Exception:
            pass
