from __future__ import annotations

import os

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage, WanzhangguiOrderPage
from e2e.utils.account_store import account_store


@pytest.mark.s_flow_017
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_017_reject_revoke_after_accept_without_player(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    wanzhanggui_password = os.getenv("E2E_ORDER_WANZHANGGUI_PASSWORD", settings.wanzhanggui_tenant_password)

    store = account_store()
    order = resolve_s_flow_017_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-017 使用的丸友集撤销中订单；请先执行 S-FLOW-015")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    reject_remark = os.getenv(
        "E2E_S_FLOW_REVOKE_REJECT_REMARK",
        f"S-FLOW-017 丸掌柜拒绝撤销 {main_order_no or source_order_no}",
    )

    order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, bug_reporter)
    order_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
    bug_reporter.record_if_errors(account=wanzhanggui_phone, location="S-FLOW-017 丸掌柜账号登录")

    reject_text = order_page.reject_workshop_revoke_request(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        remark=reject_remark,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-017 丸掌柜拒绝丸友集撤销：{main_order_no or source_order_no}",
    )

    order_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
    detail_status_text = order_page.assert_order_detail_statuses(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        expected_main_status="代练中",
        expected_sub_status="代练中",
        expected_sub_order_list_status=["异常中", "发单方取消撤销"],
        expected_latest_sub_order_list_status="异常中",
        expected_aftersale_absent=True,
    )
    assert "撤销中" not in detail_status_text.split("子单列表", 1)[-1].split("留言", 1)[0], (
        f"S-FLOW-017 拒绝撤销后子单列表不应残留撤销中；main_order_no={main_order_no}; "
        f"source_order_no={source_order_no}; detail={detail_status_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-017 丸掌柜详情拒绝撤销后状态校验：{main_order_no or source_order_no}",
    )

    wanyouji_text = ""
    wanyouji_phone = resolve_wanyouji_phone(order)
    wanyouji_account = store.find(phone=wanyouji_phone)
    if wanyouji_account is not None:
        fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
        fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
        bug_reporter.record_if_errors(account=wanyouji_account.phone, location="S-FLOW-017 丸友集账号登录")
        try:
            frame = fulfillment_page.open_workshop_order_list()
            wanyouji_text = fulfillment_page.search_workshop_order_list(frame, source_order_no, order_title)
            assert "撤销中" not in wanyouji_text, (
                f"S-FLOW-017 丸友集订单列表拒绝撤销后不应残留撤销中；source_order_no={source_order_no}; "
                f"text={wanyouji_text[:1500]}"
            )
        except Exception as exc:
            wanyouji_text = f"S-FLOW-017 丸友集回读非阻断失败：{exc}; page={fulfillment_page.page.locator('body').inner_text(timeout=5000)[:1200]}"

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-017",
        status="wanyouji_revoke_rejected",
        current_flow_state="wanyouji_revoke_rejected_continue_service",
        wanzhanggui_revoke_rejected_by=wanzhanggui_phone,
        wanzhanggui_revoke_reject_remark=reject_remark,
        wanzhanggui_revoke_reject_text=reject_text[:1500],
        wanzhanggui_revoke_rejected_detail_status_text=detail_status_text[:1500],
        wanyouji_after_revoke_rejected_text=wanyouji_text[:1500],
        wanzhanggui_sub_order_list_status="异常中",
        wanzhanggui_sub_order_status_desc="发单方取消撤销",
        wanyouji_visibility="workshop_order_list_visible",
        available_for_cases=["S-FLOW-018", "S-FLOW-021"],
    )


def resolve_s_flow_017_order(wanzhanggui_phone: str) -> dict | None:
    explicit_main_order_no = os.getenv("E2E_S_FLOW_MAIN_ORDER_NO", "").strip()
    explicit_source_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "").strip()
    payload = account_store().load_payload()
    if explicit_main_order_no or explicit_source_order_no:
        for item in payload.get("dispatched_orders", []):
            if wanzhanggui_phone and item.get("wanzhanggui_phone") != wanzhanggui_phone:
                continue
            if explicit_main_order_no and item.get("main_order_no") != explicit_main_order_no:
                continue
            if explicit_source_order_no and item.get("source_order_no") != explicit_source_order_no:
                continue
            return item
        return None

    return account_store().find_order_for_flow_case(
        case_id="S-FLOW-017",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanyouji_revoke_pending_without_player_dispatch",
    )


def resolve_wanyouji_phone(order: dict) -> str:
    explicit = os.getenv("E2E_ORDER_WANYOUJI_PHONE", "").strip()
    if explicit:
        return explicit
    phones = order.get("wanyouji_phones") or []
    assert phones, f"S-FLOW-017 订单台账缺少 wanyouji_phones；order={order}"
    return phones[0]
