"""跨端 E2E 测试 — 货运全流程。

业务流程 (8 步):
    1. Web 管理端: 发布货源
    2. 司机安卓 APP: 接单
    3. 司机安卓 APP: 装货
    4. 司机安卓 APP: 卸货
    5. Web 管理端: 核算运单
    6. Web 管理端: 核算审核
    7. Web 管理端: 货主打款
    8. Web 管理端: 平台打款给司机

运行:
    pytest tests/cross_end/ -m cross_end -v -s

前置条件:
    - Appium server: appium (http://localhost:4723)
    - Android 模拟器已启动，司机 APP 已安装并登录过一次 (noReset)
    - 管理端 auth 态: python tests/web/admin/save_auth.py --role super_admin
"""

import pytest

from tests.cross_end.pages.admin.freight_source_page import FreightSourcePage
from tests.cross_end.pages.admin.waybill_management_page import WaybillManagementPage
from tests.cross_end.pages.admin.settlement_page import SettlementPage
from tests.cross_end.pages.app.driver_home_page import DriverHomePage
from tests.cross_end.pages.app.driver_order_list_page import DriverOrderListPage
from tests.cross_end.pages.app.driver_transport_page import DriverTransportPage
from tests.utils.data_helper import generate_order_no

pytestmark = [pytest.mark.cross_end, pytest.mark.p0, pytest.mark.smoke]


class TestFreightFullFlow:
    """货运全流程跨端 E2E — 管理端发布货源 → 司机 APP 接单装货卸货 → 管理端核算打款。"""

    def test_full_freight_flow(
        self,
        admin_page,
        app_driver,
        ensure_admin_login,
        ensure_driver_login,
        cross_end_context,
        logger,
    ):
        """验证从发布货源到平台打款的完整跨端流程。"""
        logger.info("=" * 60)
        logger.info("跨端 E2E: 货运全流程开始")
        logger.info("=" * 60)

        # ── 登录 ──
        ensure_admin_login("super_admin")
        ensure_driver_login(app_driver)

        # 生成唯一订单号 (用于货源描述，实际订单号由系统生成)
        from tests.web.admin.pages.components.navbar import NavBar
        navbar = NavBar(admin_page)
        test_order_prefix = generate_order_no()

        # ════════════════════════════════════════════════════════
        # Step 1: Web 管理端 — 发布货源
        # ════════════════════════════════════════════════════════
        logger.info("Step 1/8: Web管理端 — 发布货源")

        # ⚠️ 菜单名称需要根据实际管理端调整
        navbar.go_to_submenu("运输管理", "货源管理")
        admin_page.wait_for_timeout(1000)

        freight_page = FreightSourcePage(admin_page)
        freight_page.fill_freight_form(
            goods_name=f"测试货物_{test_order_prefix}",
            weight=10,
            # ⚠️ 地址格式根据实际系统调整
            load_addr="云南省昆明市五华区",
            unload_addr="云南省昆明市官渡区",
        )
        freight_page.submit()
        freight_page.confirm_publish()

        # 截图留档
        freight_page.screenshot("step1_freight_published")

        # 获取系统生成的订单号
        published_order_no = freight_page.get_published_order_no()
        cross_end_context["order_no"] = published_order_no
        logger.info(f"  -> 发布成功, 订单号: {published_order_no}")

        # ════════════════════════════════════════════════════════
        # Step 2: 司机安卓 APP — 接单
        # ════════════════════════════════════════════════════════
        logger.info("Step 2/8: 司机安卓APP — 接单")

        driver_home = DriverHomePage(app_driver)
        driver_home.go_to_order_list()

        order_list_page = DriverOrderListPage(app_driver)
        order_list_page.search_and_accept_order(published_order_no)

        if not order_list_page.verify_order_accepted():
            order_list_page.screenshot("step2_order_accept_failed")
            raise AssertionError(f"司机端接单失败: {published_order_no}")

        order_list_page.screenshot("step2_order_accepted")
        logger.info(f"  -> 接单成功: {published_order_no}")

        # ════════════════════════════════════════════════════════
        # Step 3: 司机安卓 APP — 装货
        # ════════════════════════════════════════════════════════
        logger.info("Step 3/8: 司机安卓APP — 装货")

        transport_page = DriverTransportPage(app_driver)
        transport_page.load_goods(published_order_no)
        cross_end_context["load_confirm"] = True

        transport_page.screenshot("step3_loaded")
        logger.info("  -> 装货完成")

        # ════════════════════════════════════════════════════════
        # Step 4: 司机安卓 APP — 卸货
        # ════════════════════════════════════════════════════════
        logger.info("Step 4/8: 司机安卓APP — 卸货")

        transport_page.unload_goods(published_order_no)
        cross_end_context["unload_confirm"] = True

        transport_page.screenshot("step4_unloaded")
        logger.info("  -> 卸货完成")

        # ════════════════════════════════════════════════════════
        # Step 5: Web 管理端 — 核算运单
        # ════════════════════════════════════════════════════════
        logger.info("Step 5/8: Web管理端 — 核算运单")

        # ⚠️ 菜单名称需要根据实际管理端调整
        # 运单核算可能在 "运输管理 > 运单管理" 或 "承运结算" 下
        navbar.go_to_submenu("运输管理", "承运结算")
        admin_page.wait_for_timeout(1000)

        waybill_page = WaybillManagementPage(admin_page)
        waybill_page.do_accounting(published_order_no)
        cross_end_context["accounting_done"] = True

        waybill_page.screenshot("step5_accounting_done")
        logger.info(f"  -> 核算完成: {published_order_no}")

        # ════════════════════════════════════════════════════════
        # Step 6: Web 管理端 — 核算审核
        # ════════════════════════════════════════════════════════
        logger.info("Step 6/8: Web管理端 — 核算审核")

        waybill_page.do_review(published_order_no)
        cross_end_context["review_done"] = True

        waybill_page.screenshot("step6_review_done")
        logger.info(f"  -> 审核完成: {published_order_no}")

        # ════════════════════════════════════════════════════════
        # Step 7: Web 管理端 — 货主打款
        # ════════════════════════════════════════════════════════
        logger.info("Step 7/8: Web管理端 — 货主打款")

        # ⚠️ 打款页面可能与运单核算在同一菜单下或不同菜单
        settlement_page = SettlementPage(admin_page)
        settlement_page.do_shipper_payment(published_order_no)

        settlement_page.screenshot("step7_shipper_paid")
        logger.info(f"  -> 货主打款完成: {published_order_no}")

        # ════════════════════════════════════════════════════════
        # Step 8: Web 管理端 — 平台打款给司机
        # ════════════════════════════════════════════════════════
        logger.info("Step 8/8: Web管理端 — 平台打款给司机")

        settlement_page.do_platform_payment(published_order_no)

        settlement_page.screenshot("step8_platform_paid")
        logger.info(f"  -> 平台打款完成: {published_order_no}")

        # ════════════════════════════════════════════════════════
        # 最终验证
        # ════════════════════════════════════════════════════════
        logger.info("=" * 60)
        logger.info("跨端 E2E: 货运全流程完成!")
        logger.info(f"  订单号:       {cross_end_context['order_no']}")
        logger.info(f"  装货确认:     {cross_end_context['load_confirm']}")
        logger.info(f"  卸货确认:     {cross_end_context['unload_confirm']}")
        logger.info(f"  核算完成:     {cross_end_context['accounting_done']}")
        logger.info(f"  审核完成:     {cross_end_context['review_done']}")
        logger.info("=" * 60)

        # 断言: 所有步骤必须完成
        assert cross_end_context["order_no"], "订单号不能为空"
        assert cross_end_context["load_confirm"], "装货未确认"
        assert cross_end_context["unload_confirm"], "卸货未确认"
        assert cross_end_context["accounting_done"], "核算未完成"
        assert cross_end_context["review_done"], "审核未完成"
