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 E2EAccount, account_store


@pytest.mark.s_flow_006
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_006_dispatch_after_cancel_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)
    strategy_type = os.getenv("E2E_ORDER_STRATEGY_TYPE", "单平台指定")
    assert strategy_type in {"单平台指定", "多工作室同时分发", "多平台分发"}, (
        "E2E_ORDER_STRATEGY_TYPE 仅支持：单平台指定、多工作室同时分发、多平台分发，"
        f"当前值：{strategy_type}"
    )

    store = account_store()
    order = resolve_s_flow_006_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-006 使用的取消售后后待推单订单；请先走 FLOW-003 前置或显式指定订单")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    strategy_name = latest_strategy_name_for_type(wanzhanggui_phone, strategy_type)
    required_count = 1 if strategy_type == "单平台指定" else 2
    wanyouji_accounts = find_accounts_with_dispatch_strategy_name(
        wanzhanggui_phone,
        strategy_type,
        strategy_name,
        required_count,
    )
    if len(wanyouji_accounts) < required_count:
        pytest.skip(
            f"S-FLOW-006 至少需要 {required_count} 个已配置 {strategy_type}/{strategy_name} 的丸友集账号，"
            f"当前仅找到 {len(wanyouji_accounts)} 个"
        )

    current_flow_state = order.get("current_flow_state")
    status = order.get("status")
    assert current_flow_state in {
        "wanzhanggui_pending_accept_without_sub_order",
        "wanzhanggui_sub_order_cancelled_after_aftersale_cancelled",
    }, (
        "S-FLOW-006 前置台账状态不满足取消售后后可继续发单："
        f"order={order}"
    )
    assert status in {"without_dispatch", "sub_order_cancelled"}, (
        f"S-FLOW-006 前置业务状态不满足未推单/旧子单已取消；order={order}"
    )
    assert order.get("aftersale_cancelled_text") or order.get("aftersale_cancelled_detail_status_text"), (
        f"S-FLOW-006 需要取消售后后的订单作为前置；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-006 丸掌柜账号登录")

    if current_flow_state == "wanzhanggui_sub_order_cancelled_after_aftersale_cancelled":
        before_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_parts=["待接单", "已推单"],
            expected_sub_order_list_status="取消订单",
            expected_aftersale_absent=True,
        )
    else:
        before_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_aftersale_absent=True,
        )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-006 丸掌柜推单前订单详情状态校验：{main_order_no or source_order_no}",
    )

    dispatched_text = order_page.dispatch_pending_main_order_to_wanyouji(
        main_order_no=main_order_no,
        source_order_no=source_order_no,
        order_title=order_title,
        strategy_name=strategy_name,
        strategy_type=strategy_type,
        dispatch_price=os.getenv("E2E_S_FLOW_DISPATCH_PRICE", "70"),
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-006 丸掌柜-取消售后后推单到丸友集：{main_order_no or source_order_no}/{strategy_name}",
    )

    expected_sub_order_list_status: str | list[str] = "已发布"
    if current_flow_state == "wanzhanggui_sub_order_cancelled_after_aftersale_cancelled":
        expected_sub_order_list_status = ["已发布", "取消订单"]
    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_parts=["待接单", "已推单"],
        expected_sub_order_list_status=expected_sub_order_list_status,
        expected_aftersale_absent=True,
    )
    if current_flow_state == "wanzhanggui_sub_order_cancelled_after_aftersale_cancelled":
        order_page.assert_latest_sub_order_published_with_cancelled_history(detail_status_text)
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-006 丸掌柜推单后订单详情状态校验：{main_order_no or source_order_no}",
    )

    expected_scope = "私单" if strategy_type == "单平台指定" else "公池单/私单"
    wanyouji_hall_status_texts: list[str] = []
    for wanyouji_account in wanyouji_accounts[:required_count]:
        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-006 丸友集账号登录")
        hall_status_text = fulfillment_page.verify_order_reached_hall(
            source_order_no,
            order_title,
            expected_scope,
            main_order_no=main_order_no,
            expected_status="待接单",
        )
        wanyouji_hall_status_texts.append(hall_status_text[:1500])
        bug_reporter.record_if_errors(
            account=wanyouji_account.phone,
            location=f"S-FLOW-006 丸友集抢单大厅可见订单：{source_order_no}/{order_title}",
        )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-006",
        status="dispatched",
        current_flow_state="wanyouji_pending_accept_rejectable",
        strategy_name=strategy_name,
        strategy_type=strategy_type,
        wanyouji_phones=[account.phone for account in wanyouji_accounts[:required_count]],
        wanzhanggui_main_status="待接单",
        wanzhanggui_sub_order_status="待接单-已推单",
        wanzhanggui_sub_order_list_status=(
            "latest_published_with_cancelled_history"
            if current_flow_state == "wanzhanggui_sub_order_cancelled_after_aftersale_cancelled"
            else "已发布"
        ),
        wanyouji_visibility="hall_visible",
        dispatch_after_cancel_aftersale_by=wanzhanggui_phone,
        dispatch_after_cancel_aftersale_before_detail_text=before_detail_status_text[:1500],
        dispatch_after_cancel_aftersale_text=dispatched_text[:1500],
        dispatch_after_cancel_aftersale_detail_status_text=detail_status_text[:1500],
        dispatch_after_cancel_aftersale_wanyouji_hall_status_texts=wanyouji_hall_status_texts,
        available_for_cases=["S-FLOW-011", "S-FLOW-014"],
    )


def resolve_s_flow_006_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
        if explicit_source_order_no:
            return {
                "wanzhanggui_phone": wanzhanggui_phone,
                "main_order_no": explicit_main_order_no,
                "source_order_no": explicit_source_order_no,
                "order_title": os.getenv("E2E_S_FLOW_ORDER_TITLE", explicit_source_order_no),
                "status": "without_dispatch",
                "current_flow_state": "wanzhanggui_pending_accept_without_sub_order",
                "aftersale_cancelled_text": "explicit",
            }
        return None

    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if (not wanzhanggui_phone or item.get("wanzhanggui_phone") == wanzhanggui_phone)
        and item.get("status") in {"without_dispatch", "sub_order_cancelled"}
        and item.get("current_flow_state")
        in {"wanzhanggui_pending_accept_without_sub_order", "wanzhanggui_sub_order_cancelled_after_aftersale_cancelled"}
        and (item.get("aftersale_cancelled_text") or item.get("aftersale_cancelled_detail_status_text"))
        and "S-FLOW-006" not in item.get("consumed_by_cases", [])
    ]
    if candidates:
        return sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)[0]
    return None


def find_accounts_with_dispatch_strategy_name(
    wanzhanggui_phone: str,
    strategy_type: str,
    strategy_name: str,
    count: int,
) -> list[E2EAccount]:
    matched: list[E2EAccount] = []
    accounts = sorted(account_store().load(), key=lambda account: account.updated_at, reverse=True)
    for account in accounts:
        if account.certification_status != "approved" or account.wanyouji_status != "opened":
            continue
        has_strategy = any(
            item.get("wanzhanggui_phone") == wanzhanggui_phone
            and item.get("strategy_type") == strategy_type
            and item.get("strategy_name") == strategy_name
            and item.get("status") == "created"
            for item in account.dispatch_strategies
        )
        if not has_strategy:
            continue
        matched.append(account)
        if len(matched) >= count:
            return matched
    return matched


def latest_strategy_name_for_type(wanzhanggui_phone: str, strategy_type: str) -> str:
    candidates: list[tuple[str, str]] = []
    for account in account_store().load():
        for item in account.dispatch_strategies:
            if (
                item.get("wanzhanggui_phone") == wanzhanggui_phone
                and item.get("strategy_type") == strategy_type
                and item.get("status") == "created"
            ):
                candidates.append((item.get("created_at", account.updated_at), item["strategy_name"]))
    if not candidates:
        raise AssertionError(f"台账中未找到 {strategy_type} 的策略名称")
    return sorted(candidates, key=lambda item: item[0], reverse=True)[0][1]
