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_083
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_083_cancel_abnormal_sub_order_aftersale(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_083_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-083 使用的异常中子单售后中订单，请先执行 S-FLOW-034。")

    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 = f"S-FLOW-083 丸掌柜取消异常中子单售后 {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-083 丸掌柜账号登录")

    final_detail_text = order_page.cancel_abnormal_sub_order_aftersale(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        reason=cancel_reason,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-083 丸掌柜取消异常中子单售后：{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-083 台账中未找到丸友集账号：{wanyouji_phone}"
    fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    frame = fulfillment_page.open_workshop_order_list()
    wanyouji_text = fulfillment_page.search_workshop_order_list(frame, source_order_no, order_title)
    wanyouji_row_text = WanyoujiFulfillmentPage.extract_order_row_text(wanyouji_text, source_order_no)
    assert source_order_no in wanyouji_text or order_title in wanyouji_text, (
        f"S-FLOW-083 取消异常中子单售后后丸友集订单列表未找到订单；"
        f"source_order_no={source_order_no}; text={wanyouji_text[:1500]}"
    )
    assert "售后中" not in wanyouji_row_text, (
        f"S-FLOW-083 取消异常中子单售后后丸友集目标订单仍显示售后中；"
        f"source_order_no={source_order_no}; row_text={wanyouji_row_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-083 丸友集取消异常中子单售后后回查：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-083",
        status="abnormal_sub_order_aftersale_cancelled",
        current_flow_state="wanzhanggui_abnormal_sub_order_aftersale_cancelled",
        expected_result=(
            "丸掌柜侧异常中子单售后取消成功；目标子单不再显示售后中，恢复为异常中或页面对应可继续处理状态；"
            "取消原因可追溯；丸友集侧目标订单不再停留售后中；后续可重新接 S-FLOW-034 或按异常中后续链路处理。"
        ),
        wanzhanggui_expected_result="订单详情子单列表目标子单不再售后中，显示异常中/发单方取消撤销等可继续处理状态，售后信息消失或记录为已取消。",
        wanyouji_expected_result="订单列表目标订单不再显示售后中，来源单号与主单号仍匹配同一订单。",
        aftersale_cancelled_by=wanzhanggui_phone,
        aftersale_cancel_reason=cancel_reason,
        abnormal_sub_order_aftersale_cancelled_detail_text=final_detail_text[:1500],
        wanyouji_abnormal_sub_order_aftersale_cancelled_text=wanyouji_text[:1500],
        wanyouji_abnormal_sub_order_aftersale_cancelled_row_text=wanyouji_row_text[:1500],
        wanzhanggui_sub_order_list_status="异常中",
        available_for_cases=["S-FLOW-034"],
    )


def resolve_s_flow_083_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-083",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanzhanggui_abnormal_sub_order_aftersale_pending",
    )
    if candidate:
        return candidate

    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if (not wanzhanggui_phone or item.get("wanzhanggui_phone") == wanzhanggui_phone)
        and item.get("current_flow_state") == "wanzhanggui_abnormal_sub_order_aftersale_pending"
        and "S-FLOW-083" not in item.get("consumed_by_cases", [])
    ]
    return sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)[0] if candidates else None


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