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_035
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_035_approve_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_035_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-035 使用的子单售后中订单，请先执行任一子单发起售后用例")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    previous_flow_state = order.get("current_flow_state", "")
    amount = os.getenv("E2E_S_FLOW_AFTERSALE_AMOUNT", order.get("aftersale_amount", "1"))
    approve_remark = f"S-FLOW-035 丸友集同意/处理子单售后 {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-035 台账中未找到丸友集账号：{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-035 丸友集账号登录")
    frame = fulfillment_page.open_workshop_order_list()
    current_wanyouji_text = fulfillment_page.search_workshop_order_list(frame, source_order_no, order_title)
    current_wanyouji_row_text = WanyoujiFulfillmentPage.extract_order_row_text(current_wanyouji_text, source_order_no)
    completed_statuses = ["售后完成", "售后结束", "售后处理完成", "仲裁结束"]
    if any(status in current_wanyouji_row_text for status in completed_statuses):
        wanyouji_approve_text = current_wanyouji_text
    else:
        wanyouji_approve_text = fulfillment_page.handle_upstream_aftersale_from_workshop_list(
            source_order_no,
            order_title,
            action="同意",
            remark=approve_remark,
            amount=amount,
            service_name=customer_service.contact_name,
        )
    wanyouji_approve_row_text = WanyoujiFulfillmentPage.extract_order_row_text(wanyouji_approve_text, source_order_no)
    assert any(status in wanyouji_approve_row_text for status in completed_statuses), (
        f"S-FLOW-035 丸友集同意售后后目标订单状态未进入售后完成/售后结束/售后处理完成；"
        f"source_order_no={source_order_no}; row_text={wanyouji_approve_row_text[:1500]}; "
        f"source_order_no={source_order_no}; text={wanyouji_approve_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-035 丸友集同意/处理子单售后：{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)
    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=["售后结束", "售后完成", "已售后"],
    )
    assert "结果: 售后处理完成" in detail_status_text and "退款金额" in detail_status_text, (
        f"S-FLOW-035 丸掌柜售后结束子单未展示售后处理完成和退款金额；"
        f"main_order_no={main_order_no}; source_order_no={source_order_no}; detail={detail_status_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-035 丸掌柜回读丸友集同意售后后状态：{main_order_no or source_order_no}",
    )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-035",
        status="sub_order_aftersale_approved",
        current_flow_state="wanyouji_sub_order_aftersale_approved",
        aftersale_approved_by=wanyouji_account.phone,
        aftersale_approve_remark=approve_remark,
        sub_order_aftersale_source_state=previous_flow_state,
        wanyouji_abnormal_sub_order_aftersale_approved_text=wanyouji_approve_text[:1500],
        wanyouji_abnormal_sub_order_aftersale_approved_row_text=wanyouji_approve_row_text[:1500],
        abnormal_sub_order_aftersale_approved_detail_text=detail_status_text[:1500],
        available_for_cases=(
            ["S-FLOW-051", "S-FLOW-061", "S-FLOW-062"]
            if previous_flow_state == "wanzhanggui_abnormal_sub_order_aftersale_pending"
            else []
        ),
    )


def resolve_s_flow_035_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-035",
        wanzhanggui_phone=wanzhanggui_phone,
    )


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