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.e2e_order_002
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_丸掌柜撤销派单并在丸友集验证订单不可见(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", "19147509308")
    wanzhanggui_password = os.getenv("E2E_ORDER_WANZHANGGUI_PASSWORD", "test123456")
    strategy_type = os.getenv("E2E_ORDER_STRATEGY_TYPE", "")
    if strategy_type:
        assert strategy_type in {"单平台指定", "多工作室同时分发", "多平台分发"}, (
            "E2E_ORDER_STRATEGY_TYPE 仅支持：单平台指定、多工作室同时分发、多平台分发，"
            f"当前值：{strategy_type}"
        )

    store = account_store()
    order = store.find_latest_dispatched_order(
        wanzhanggui_phone=wanzhanggui_phone,
        strategy_type=strategy_type,
    )
    if order is None:
        pytest.skip("台账中未找到已派单且未撤销的订单，请先执行 E2E-ORDER-001 创建并验证订单。")

    source_order_no = order["source_order_no"]
    order_title = order["order_title"]
    actual_strategy_type = order["strategy_type"]
    expected_scope = "私单" if actual_strategy_type == "单平台指定" else "公池单/私单"
    accounts_to_verify = find_accounts_by_phones(order.get("wanyouji_phones", []))
    assert accounts_to_verify, f"台账订单缺少丸友集验证账号：{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="丸掌柜账号-主账号登录")
    order_page.revoke_dispatched_order(source_order_no, order_title)
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"丸掌柜-商家管理-订单管理-撤销派单：{source_order_no}/{order_title}",
    )

    for wanyouji_account in accounts_to_verify:
        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="丸友集账号-主账号登录")
        fulfillment_page.verify_order_not_in_hall(source_order_no, order_title, expected_scope)
        bug_reporter.record_if_errors(
            account=wanyouji_account.phone,
            location=(
                "丸友集-工作室履约应用-抢单大厅-"
                f"验证撤销后{expected_scope}不可见：{source_order_no}/{order_title}"
            ),
        )

    store.mark_order_revoked(wanzhanggui_phone=wanzhanggui_phone, source_order_no=source_order_no)


def find_accounts_by_phones(phones: list[str]) -> list[E2EAccount]:
    by_phone = {account.phone: account for account in account_store().load()}
    return [by_phone[phone] for phone in phones if phone in by_phone]
