"""App 登录功能测试用例。

覆盖正常登录、异常登录。
按 ui_automation_best_practices.md §6.4 的范本结构编写。

标记:
    pytest -m app          # 仅执行 App 用例
    pytest -m p0           # 仅执行 P0 冒烟
    pytest -m smoke        # 仅执行冒烟
"""

import pytest
from appium.webdriver.common.appiumby import AppiumBy

pytestmark = [pytest.mark.app]


# ═══════════════════════════════════════════════════════════════════
# P0 — 冒烟测试
# ═══════════════════════════════════════════════════════════════════

class TestAppLoginSuccess:
    """App 正常登录流程。"""

    @pytest.mark.p0
    @pytest.mark.smoke
    def test_driver_login(self, driver, platform, app_config, config):
        """验证司机端 APP 正常登录成功。"""
        from tests.app.pages.driver_home_page import DriverHomePage

        account = config["accounts"]["driver"]

        # ⚠️ 以下定位需根据实际 APP UI 调整
        # 1. 输入手机号
        phone_input = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_phone_input")
        phone_input.send_keys(account["phone"])

        # 2. 输入密码
        password_input = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_password_input")
        password_input.send_keys(account["password"])

        # 3. 点击登录
        driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_submit_btn").click()

        # 4. 验证首页展示
        home = DriverHomePage(driver, platform=platform)
        assert home.is_displayed(), "登录后应展示司机端首页"


# ═══════════════════════════════════════════════════════════════════
# P1 — 异常与校验
# ═══════════════════════════════════════════════════════════════════

class TestAppLoginValidation:
    """App 登录异常校验。"""

    @pytest.mark.p1
    @pytest.mark.parametrize("phone,password,expected_toast", [
        pytest.param("", "88888888", "请输入手机号", id="empty_phone"),
        pytest.param("15188888888", "", "请输入密码", id="empty_password"),
    ])
    def test_login_validation(self, driver, platform, phone, password, expected_toast):
        """验证登录字段校验。"""
        if phone:
            phone_input = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_phone_input")
            phone_input.send_keys(phone)
        if password:
            password_input = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_password_input")
            password_input.send_keys(password)

        driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_submit_btn").click()

        # Toast 提示验证（⚠️ Toast 定位方式因设备/平台而异，可能需要调整）
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC

        try:
            wait = WebDriverWait(driver, timeout=5)
            toast_xpath = f"//*[contains(@text,'{expected_toast}')]"
            wait.until(EC.visibility_of_element_located((AppiumBy.XPATH, toast_xpath)))
        except Exception:
            # Toast 可能已自动消失，这里不做硬断言，以实际调试为准
            pass
