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.tests.订单状态流转.order_flow_member_helpers import ensure_wanyouji_customer_service_member
from e2e.utils.account_store import account_store


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

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    aftersale_amount = os.getenv("E2E_S_FLOW_AFTERSALE_AMOUNT", "1")
    aftersale_reason = f"S-FLOW-034 异常中子单发起售后 {main_order_no or source_order_no}"
    reject_reason = f"S-FLOW-036 丸友集拒绝异常中子单售后 {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="FLOW-034 丸掌柜账号登录")

    before_detail_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,
    )

    aftersale_detail_text = order_page.start_abnormal_sub_order_aftersale(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        reason=aftersale_reason,
        amount=aftersale_amount,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-034 丸掌柜异常中子单发起售后：{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-036 台账中未找到丸友集账号：{wanyouji_phone}"
    customer_service = ensure_wanyouji_customer_service_member(
        page=page,
        settings=settings,
        bug_reporter=bug_reporter,
        parent=wanyouji_account,
    )
    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-036 丸友集账号登录")
    wanyouji_reject_text = fulfillment_page.handle_upstream_aftersale_from_workshop_list(
        source_order_no,
        order_title,
        action="拒绝",
        remark=reject_reason,
        amount=aftersale_amount,
        service_name=customer_service.contact_name,
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-036 丸友集拒绝异常中子单售后：{main_order_no or source_order_no}",
    )

    order_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
    final_detail_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=["售后中"],
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-036 丸掌柜回读丸友集拒绝售后后状态：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-034",
        status="abnormal_sub_order_aftersale_cancelled",
        current_flow_state="wanyouji_abnormal_sub_order_aftersale_rejected",
        aftersale_started_by=wanzhanggui_phone,
        aftersale_reason=aftersale_reason,
        aftersale_amount=aftersale_amount,
        abnormal_sub_order_aftersale_before_detail_text=before_detail_text[:1500],
        abnormal_sub_order_aftersale_started_detail_text=aftersale_detail_text[:1500],
        available_for_cases=["S-FLOW-034"],
    )
    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-036",
        status="abnormal_sub_order_aftersale_rejected_pending",
        current_flow_state="wanyouji_abnormal_sub_order_aftersale_rejected_still_pending",
        aftersale_rejected_by=wanyouji_account.phone,
        aftersale_reject_reason=reject_reason,
        wanyouji_abnormal_sub_order_aftersale_rejected_text=wanyouji_reject_text[:1500],
        abnormal_sub_order_aftersale_rejected_detail_text=final_detail_text[:1500],
        available_for_cases=[],
    )


def resolve_s_flow_034_036_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-034",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanyouji_revoke_rejected_continue_service",
    )
    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") in {
            "wanyouji_revoke_rejected_continue_service",
            "wanzhanggui_abnormal_sub_order_after_revoke_rejected",
        }
        and "S-FLOW-036" 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-036 订单台账缺少 wanyouji_phones；order={order}"
    return phones[0]
