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.订单状态流转.上游发单.test_s_flow_006_dispatch_after_cancel_aftersale import (
    find_accounts_with_dispatch_strategy_name,
    latest_strategy_name_for_type,
)
from e2e.utils.account_store import account_store


@pytest.mark.s_flow_061
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_061_continue_dispatch_after_aftersale_end(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_061_order(wanzhanggui_phone)
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-061 使用的售后结束订单；请先执行 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)
    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-061 至少需要 {required_count} 个已配置 {strategy_type}/{strategy_name} 的丸友集账号，"
            f"当前仅找到 {len(wanyouji_accounts)} 个"
        )

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

    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="售后结束",
    )
    assert "继续发单" in before_detail_status_text, (
        f"S-FLOW-061 前置订单详情未展示继续发单入口；main_order_no={main_order_no}; "
        f"source_order_no={source_order_no}; detail={before_detail_status_text[:1500]}"
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-061 丸掌柜继续发单前售后结束状态校验：{main_order_no or source_order_no}",
    )

    if "已发布" in before_detail_status_text and "售后结束" in before_detail_status_text:
        dispatched_text = before_detail_status_text
    else:
        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-061 丸掌柜售后结束后继续发单：{main_order_no or source_order_no}/{strategy_name}",
        )

    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=["已发布", "售后结束"],
    )
    assert_latest_sub_order_published_with_previous_aftersale_end(order_page, detail_status_text)
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-061 丸掌柜继续发单后子单列表状态校验：{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-061 丸友集账号登录")
        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-061 丸友集抢单大厅可见售后结束后新推送订单：{main_order_no or source_order_no}/{order_title}",
        )

    store.mark_order_consumed_by_flow_case(
        source_order_no=source_order_no,
        case_id="S-FLOW-061",
        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_sub_order_list_status="latest_published_with_aftersale_end_history",
        wanyouji_visibility="hall_visible",
        wanyouji_hall_status="待接单",
        continue_dispatch_after_aftersale_end_by=wanzhanggui_phone,
        continue_dispatch_after_aftersale_end_before_detail_text=before_detail_status_text[:1500],
        continue_dispatch_after_aftersale_end_text=dispatched_text[:1500],
        continue_dispatch_after_aftersale_end_detail_status_text=detail_status_text[:1500],
        continue_dispatch_after_aftersale_end_wanyouji_hall_status_texts=wanyouji_hall_status_texts,
        available_for_cases=["S-FLOW-014", "S-FLOW-015", "S-FLOW-034"],
    )


def resolve_s_flow_061_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-061",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_state="wanyouji_abnormal_sub_order_aftersale_approved",
    )
    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") == "wanyouji_abnormal_sub_order_aftersale_approved"
        and "S-FLOW-061" in item.get("available_for_cases", [])
        and "S-FLOW-061" 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 assert_latest_sub_order_published_with_previous_aftersale_end(
    order_page: WanzhangguiOrderPage,
    detail_text: str,
) -> None:
    sub_order_list_text = order_page.detail_section_text(detail_text, "子单列表")
    assert sub_order_list_text, f"订单详情缺少子单列表区域；detail={detail_text[:1500]}"
    assert "已发布" in sub_order_list_text, (
        f"子单列表未看到最新已发布子单；sub_order_list={sub_order_list_text[:1500]}"
    )
    assert "售后结束" in sub_order_list_text, (
        f"子单列表未保留售后结束历史子单；sub_order_list={sub_order_list_text[:1500]}"
    )

    rows = order_page.extract_sub_order_rows(sub_order_list_text)
    assert rows, f"子单列表未解析到有效子单行；sub_order_list={sub_order_list_text[:1500]}"
    status_rows = [row for row in rows if "已发布" in row or "售后结束" in row]
    assert status_rows, f"子单列表未解析到有效状态行；sub_order_list={sub_order_list_text[:1500]}"

    sortable_rows = []
    for row in status_rows:
        sub_order_no = row.split("\t", 1)[0].strip()
        sortable_rows.append((sub_order_no, row))
    sorted_rows = sorted(sortable_rows, key=lambda item: item[0], reverse=True)
    latest_row = sorted_rows[0][1]
    previous_rows = [row for _, row in sorted_rows[1:]]

    assert "已发布" in latest_row, (
        "丸掌柜侧预期最新子单状态为已发布，但实际不一致；"
        f"latest_row={latest_row}; rows={[row for _, row in sorted_rows[:8]]}"
    )
    assert any("售后结束" in row for row in previous_rows), (
        "丸掌柜侧预期前一个历史子单状态为售后结束，但实际未找到；"
        f"latest_row={latest_row}; previous_rows={previous_rows[:8]}"
    )
