from __future__ import annotations

import os

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import (
    find_player_account,
    login_player_sub_account_by_sms,
)
from e2e.tests.订单状态流转.order_flow_member_helpers import ensure_wanyouji_player_member
from e2e.tests.订单状态流转.penalty_recovery_flow_helpers import resolve_order_for_case, resolve_wanyouji_account
from e2e.utils.account_store import account_store
from e2e.utils.dual_browser import assert_distinct_account_contexts


@pytest.mark.s_flow_044
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_044_continue_dispatch_after_completed_child(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    assignment_method = os.getenv("E2E_TASK_ASSIGNMENT_METHOD", "抢单大厅").strip()
    assert assignment_method in {"抢单大厅", "指派打手", "智能派单"}, (
        "E2E_TASK_ASSIGNMENT_METHOD 仅支持：抢单大厅、指派打手、智能派单；"
        f"当前值：{assignment_method}"
    )

    store = account_store()
    order = resolve_order_for_case(
        case_id="S-FLOW-044",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_states=["player_sub_order_settled_completed_ready_for_next_dispatch"],
    )
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-044 使用的已完成且已结算子单订单；请先执行 S-FLOW-080 和 S-FLOW-081。")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    wanyouji_account = resolve_wanyouji_account(order)
    player_hall_text = ""

    fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    if os.getenv("E2E_S_FLOW_044_VERIFY_ONLY", "").lower() in {"1", "true", "yes"}:
        frame = fulfillment_page.open_workshop_order_list()
        before_text = fulfillment_page.search_workshop_order_list(frame, source_order_no, order_title)
        clicked = (
            fulfillment_page.click_workshop_order_list_action(frame, source_order_no, "操作")
            or fulfillment_page.click_row_action_allow_revoke(frame, source_order_no, order_title, ["操作", "操 作"])
        )
        assert clicked, (
            f"S-FLOW-044 恢复校验时订单列表行未找到【操作】入口；source_order_no={source_order_no}; "
            f"text={before_text[:1500]}"
        )
        detail_text = fulfillment_page.wait_for_continue_dispatch_cancelled_child_detail(
            frame,
            source_order_no,
            order_title,
        )
        after_text = before_text
    else:
        before_text, detail_text, after_text = fulfillment_page.continue_dispatch_cancelled_child_from_workshop_order_list(
            source_order_no,
            order_title,
            assignment_method=assignment_method,
            allowed_terminal_statuses=["已完成", "完成"],
        )
    assert "已完成" in detail_text or "完成" in detail_text, (
        f"S-FLOW-044 续发前子单列表未看到已完成子单；source_order_no={source_order_no}; detail={detail_text[:1500]}"
    )
    assert any(status in after_text for status in ["待接单", "已发单", "代练中", "抢单大厅"]), (
        f"S-FLOW-044 已完成子单后续发未看到下一子单待接单/已发单状态；source_order_no={source_order_no}; "
        f"text={after_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-044 丸友集前一子单完成后续发下一子单：{main_order_no or source_order_no}/{assignment_method}",
    )

    if assignment_method == "抢单大厅":
        player_account = find_player_account(wanyouji_account, os.getenv("E2E_TASK_PLAYER_PHONE", "").strip())
        if player_account is None:
            player_account = ensure_wanyouji_player_member(
                page=page,
                settings=settings,
                bug_reporter=bug_reporter,
                parent=wanyouji_account,
            )
        player_browser_page = login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
        assert_distinct_account_contexts(
            fulfillment_page.page,
            wanyouji_account.phone,
            player_browser_page,
            player_account.phone,
        )
        player_page = WanyoujiFulfillmentPage(player_browser_page, settings.tenant_home_url, bug_reporter)
        player_hall_text = player_page.verify_order_in_player_hall(source_order_no, order_title)
        bug_reporter.record_if_errors(
            account=player_account.phone,
            location=f"S-FLOW-044 打手抢单大厅可见完成子单后的续发订单：{main_order_no or source_order_no}",
        )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-044",
        status="task_dispatched_to_player_hall",
        current_flow_state="wanyouji_dispatched_to_player_hall",
        task_wanyouji_phone=wanyouji_account.phone,
        task_assignment_method=assignment_method,
        wanyouji_order_list_before_continue_dispatch_completed_child_text=before_text[:1500],
        wanyouji_continue_dispatch_completed_child_detail_text=detail_text[:1500],
        wanyouji_order_list_after_continue_dispatch_completed_child_text=after_text[:1500],
        player_hall_after_continue_dispatch_completed_child_text=player_hall_text[:1500],
        available_for_cases=["S-FLOW-026", "S-FLOW-075"],
    )
