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_020
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_020_cancel_aftersale_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_020_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-020 使用的已接单未发打手售后中订单；请先执行 S-FLOW-018")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    cancel_reason = os.getenv(
        "E2E_S_FLOW_AFTERSALE_CANCEL_REASON",
        f"S-FLOW-020 已接单未发打手主单取消售后 {main_order_no or source_order_no}",
    )

    assert order.get("current_flow_state") == "wanzhanggui_aftersale_pending_from_accepted_without_player", (
        f"S-FLOW-020 前置台账状态不满足已接单未发打手售后中；order={order}"
    )
    assert "S-FLOW-020" in order.get("available_for_cases", []), f"该订单未声明可用于 S-FLOW-020；order={order}"

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

    final_text = order_page.cancel_aftersale_for_order(
        source_order_no,
        order_title,
        main_order_no=main_order_no,
        reason=cancel_reason,
        expected_status_after_cancel=["代练中", "服务中"],
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-020 丸掌柜已接单未发打手订单取消主单售后：{main_order_no or 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_aftersale_absent=True,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-020 丸掌柜订单详情取消售后后状态校验：{main_order_no or source_order_no}",
    )

    wanyouji_phone = resolve_wanyouji_phone(order)
    wanyouji_account = store.find(phone=wanyouji_phone)
    assert wanyouji_account is not None, f"台账中未找到 S-FLOW-020 丸友集账号：{wanyouji_phone}"
    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-020 丸友集账号登录")
    wanyouji_text = fulfillment_page.search_workshop_order_list(
        fulfillment_page.open_workshop_order_list(),
        source_order_no,
        order_title,
    )
    wanyouji_row_text = WanyoujiFulfillmentPage.extract_order_row_text(wanyouji_text, source_order_no)
    assert "异常中-待售后" in wanyouji_row_text or "异常中" in wanyouji_row_text, (
        f"S-FLOW-020 取消主单售后后丸友集侧状态不符合实际预期；"
        f"source_order_no={source_order_no}; row_text={wanyouji_row_text[:1500]}"
    )
    assert "立即发单" not in wanyouji_row_text, (
        f"S-FLOW-020 取消主单售后后丸友集侧不应直接进入立即发单；"
        f"source_order_no={source_order_no}; row_text={wanyouji_row_text[:1500]}"
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-020",
        status="wanyouji_abnormal_pending_after_main_aftersale_cancelled",
        current_flow_state="wanyouji_abnormal_pending_after_main_aftersale_cancelled_without_player",
        wanzhanggui_main_status="代练中",
        wanzhanggui_sub_order_status="代练中/异常中",
        wanyouji_parent_status="异常中-待售后",
        wanyouji_visibility="workshop_order_list_visible_but_not_dispatchable",
        aftersale_cancelled_by=wanzhanggui_phone,
        aftersale_cancel_reason=cancel_reason,
        aftersale_cancelled_text=final_text[:1500],
        aftersale_cancelled_detail_status_text=detail_status_text[:1500],
        wanyouji_after_aftersale_cancel_text=wanyouji_text[:1500],
        wanyouji_after_aftersale_cancel_row_text=wanyouji_row_text[:1500],
        available_for_cases=[],
    )


def resolve_s_flow_020_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

    candidate = account_store().find_order_for_flow_case(
        case_id="S-FLOW-020",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanzhanggui_aftersale_pending_from_accepted_without_player",
    )
    return candidate


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