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.订单状态流转.penalty_recovery_flow_helpers import (
    resolve_order_for_case,
    resolve_wanyouji_account,
)
from e2e.utils.account_store import account_store


@pytest.mark.s_flow_078
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_078_player_sub_order_revoke_terminal(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-078",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_states=["player_sub_order_in_progress"],
    )
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-078 使用的打手代练中订单；请先执行 S-FLOW-026。")

    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)
    reason = os.getenv("E2E_S_FLOW_CHILD_REVOKE_REASON", f"S-FLOW-078 丸友集撤销代练中子单 {main_order_no or source_order_no}")
    revoke_amount = os.getenv("E2E_S_FLOW_REVOKE_AMOUNT", "1")

    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, before_detail_text, terminal_detail_text = (
        fulfillment_page.revoke_in_progress_child_from_workshop_order_detail(
            source_order_no,
            order_title,
            reason,
            revoke_amount=revoke_amount,
        )
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-078 丸友集撤销代练中子单：{main_order_no or source_order_no}/{target_sub_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-078",
        status="wanyouji_child_revoke_completed",
        current_flow_state="player_sub_order_revoke_approved_terminal",
        task_wanyouji_phone=wanyouji_account.phone,
        task_player_sub_order_no=target_sub_order_no,
        player_revoke_approved_sub_order_no=target_sub_order_no,
        wanyouji_child_revoke_reason=reason,
        wanyouji_child_revoke_amount=revoke_amount,
        wanyouji_child_revoke_before_detail_text=before_detail_text[:1500],
        wanyouji_child_revoke_terminal_detail_text=terminal_detail_text[:1500],
        wanyouji_sub_order_status="撤销完成",
        available_for_cases=["S-FLOW-032", "S-FLOW-033", "S-FLOW-072"],
    )
