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


KNOWN_REVOKE_BUG_MESSAGE = "非接单方发起撤销状态，暂不支持"
KNOWN_REVOKE_BUG_ID = "BUG-S-FLOW-016-wanyouji-revoke-cannot-be-approved"


@pytest.mark.s_flow_016
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_016_approve_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_016_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-016 使用的丸友集撤销中订单；请先执行 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)
    approve_remark = os.getenv(
        "E2E_S_FLOW_REVOKE_APPROVE_REMARK",
        f"S-FLOW-016 丸掌柜同意撤销 {main_order_no or source_order_no}",
    )
    approve_amount = os.getenv("E2E_S_FLOW_REVOKE_APPROVE_AMOUNT", "1")
    assert approve_amount.isdigit(), f"E2E_S_FLOW_REVOKE_APPROVE_AMOUNT 必须为整数数字；当前值：{approve_amount}"

    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-016 丸掌柜账号登录")

    approve_text = order_page.approve_workshop_revoke_request(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        remark=approve_remark,
        approve_amount=approve_amount,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-016 丸掌柜同意丸友集撤销：{main_order_no or source_order_no}",
    )
    assert KNOWN_REVOKE_BUG_MESSAGE not in approve_text, (
        f"{KNOWN_REVOKE_BUG_ID}: 接单方丸友集发起撤销后，丸掌柜处理撤销失败。"
        f"平台提示：{KNOWN_REVOKE_BUG_MESSAGE}；main_order_no={main_order_no}; "
        f"source_order_no={source_order_no}"
    )

    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,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-016 丸掌柜详情同意撤销后状态校验：{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-016 丸友集账号登录")
        frame = fulfillment_page.open_workshop_order_list()
        wanyouji_text = fulfillment_page.search_workshop_order_list(frame, source_order_no, order_title)

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-016",
        status="sub_order_revoke_ended",
        current_flow_state="wanzhanggui_sub_order_revoke_ended",
        wanzhanggui_revoke_approved_by=wanzhanggui_phone,
        wanzhanggui_revoke_approve_remark=approve_remark,
        wanzhanggui_revoke_approve_amount=approve_amount,
        wanzhanggui_revoke_approve_text=approve_text[:1500],
        wanzhanggui_revoke_approved_detail_status_text=detail_status_text[:1500],
        wanyouji_after_revoke_approved_text=wanyouji_text[:1500],
        wanzhanggui_sub_order_list_status="撤销结束",
        wanyouji_visibility="cancelled_or_revoke_completed",
        available_for_cases=["S-FLOW-068", "S-FLOW-069"],
    )


def resolve_s_flow_016_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-016",
        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-016 订单台账缺少 wanyouji_phones；order={order}"
    return phones[0]
