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 login_player_sub_account_by_sms
from e2e.tests.订单状态流转.penalty_recovery_flow_helpers import (
    resolve_order_for_case,
    resolve_player_account,
    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_039
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_039_wanyouji_approve_player_cancel(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    store = account_store()
    order = resolve_order_for_case(
        case_id="S-FLOW-039",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_states=["player_cancel_pending_at_wanyouji"],
    )
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-039 使用的打手取消中订单；请先执行 S-FLOW-037。")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    remark = os.getenv("E2E_S_FLOW_PLAYER_CANCEL_APPROVE_REMARK", f"S-FLOW-039 丸友集同意打手取消 {main_order_no or source_order_no}")
    wanyouji_account = resolve_wanyouji_account(order)
    player_account = resolve_player_account(order, wanyouji_account)

    fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    target_sub_order_no = (
        os.getenv("E2E_PLAYER_CANCEL_TARGET_SUB_ORDER_NO", "").strip()
        or order.get("player_cancel_target_sub_order_no", "")
        or order.get("task_player_sub_order_no", "")
        or order.get("assigned_player_sub_order_no", "")
    )
    before_detail_text = ""
    if not target_sub_order_no:
        target_sub_order_no, before_detail_text = fulfillment_page.find_workshop_sub_order_no_by_status(
            source_order_no,
            order_title,
            ["取消中"],
        )
    approve_text = fulfillment_page.approve_player_cancel_order_from_workshop_order(
        source_order_no,
        order_title,
        remark,
        sub_order_no=target_sub_order_no,
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-039 丸友集同意打手取消订单：{main_order_no or source_order_no}",
    )
    terminal_sub_order_no, terminal_detail_text = fulfillment_page.assert_player_cancel_target_sub_order_terminal(
        source_order_no,
        order_title,
        target_sub_order_no,
    )
    assert not target_sub_order_no or terminal_sub_order_no == target_sub_order_no, (
        f"S-FLOW-039 丸友集同意取消后终态子单不是本次取消目标；source_order_no={source_order_no}; "
        f"target={target_sub_order_no}; actual={terminal_sub_order_no}; detail={terminal_detail_text[:1500]}"
    )

    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_text = ""
    assigned_pending_cancel = bool(order.get("assigned_player_sub_order_no")) and (
        target_sub_order_no == order.get("assigned_player_sub_order_no")
    )
    if assigned_pending_cancel:
        assigned_texts: list[str] = []
        for assigned_frame in player_page.open_player_assigned_order_hall():
            assigned_text = player_page.search_player_assigned_orders(assigned_frame, target_sub_order_no)
            assigned_texts.append(assigned_text[:1500])
            if target_sub_order_no not in assigned_text:
                player_text = assigned_text
                break
            player_row_text = player_page.extract_frame_order_row_text(assigned_frame, target_sub_order_no, order_title)
            player_text = assigned_text
            if any(key in player_row_text for key in ["已取消", "取消订单", "取消完成", "取消"]) and "取消中" not in player_row_text:
                break
        assert target_sub_order_no not in player_text or (
            any(key in player_text for key in ["已取消", "取消订单", "取消完成", "取消"]) and "取消中" not in player_text
        ), (
            f"S-FLOW-039 丸友集同意取消后，打手抢单大厅-指派单仍显示未终态取消订单；"
            f"target_sub_order_no={target_sub_order_no}; texts={assigned_texts}"
        )
    else:
        player_frame = player_page.open_player_my_orders(source_order_no)
        player_text = player_page.search_player_my_orders(player_frame, source_order_no, order_title)
        player_row_text = player_page.extract_frame_order_row_text(player_frame, source_order_no, order_title)
        assert any(key in player_row_text for key in ["已取消", "取消订单", "取消完成", "取消"]) and "取消中" not in player_row_text, (
            f"S-FLOW-039 丸友集同意取消后打手侧未看到已取消终态；source_order_no={source_order_no}; "
            f"text={player_text[:1500]}"
        )
    bug_reporter.record_if_errors(
        account=player_account.phone,
        location=f"S-FLOW-039 打手侧同意取消后状态校验：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-039",
        status="player_cancel_approved",
        current_flow_state="wanyouji_previous_child_cancelled_wait_continue_dispatch",
        task_player_phone=player_account.phone,
        task_wanyouji_phone=wanyouji_account.phone,
        task_player_sub_order_no=terminal_sub_order_no,
        player_cancel_approved_sub_order_no=terminal_sub_order_no,
        player_cancel_approved_by=wanyouji_account.phone,
        player_cancel_approve_remark=remark,
        wanyouji_player_cancel_before_detail_text=before_detail_text[:1500],
        wanyouji_player_cancel_approve_text=approve_text[:1500],
        wanyouji_player_cancel_approve_detail_text=terminal_detail_text[:1500],
        player_after_cancel_approved_text=player_text[:1500],
        wanyouji_sub_order_status="已取消",
        available_for_cases=["S-FLOW-032", "S-FLOW-072"],
    )
