from __future__ import annotations

import os
from typing import Any

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import (
    login_player_sub_account_by_sms,
    resolve_task_order_and_accounts,
)
from e2e.utils.account_store import E2EAccount, account_store


@pytest.mark.e2e_delivery_001
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_打手确认上号上传首图并提交验收后主账号查看(page: Page, settings, bug_reporter) -> None:
    store = account_store()
    order, wanyouji_account, player_account = resolve_delivery_order_and_accounts()
    source_order_no = order["source_order_no"]
    order_title = order["order_title"]

    login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
    player_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    player_page.submit_player_delivery_for_acceptance(source_order_no, order_title)
    store.mark_task_order_status(
        source_order_no=source_order_no,
        status="delivery_submitted",
        task_player_phone=player_account.phone,
    )
    bug_reporter.record_if_errors(
        account=player_account.phone,
        location=f"丸友集-打手应用-我的订单-确认上号-上传首图-提交验收：{source_order_no}/{order_title}",
    )

    owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    owner_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    frame = owner_page.open_workshop_order_list()
    text = owner_page.search_workshop_order_list(frame, source_order_no, order_title)
    assert source_order_no in text or order_title in text, (
        f"丸友集主账号订单列表未找到打手提交验收后的订单；source_order_no={source_order_no}; "
        f"order_title={order_title}; text={text[:1500]}"
    )
    assert "待验收" in text or "申请上游验收" in text, (
        f"丸友集主账号订单列表未看到待验收/申请上游验收状态；source_order_no={source_order_no}; "
        f"text={text[:1500]}"
    )
    store.mark_task_order_status(
        source_order_no=source_order_no,
        status="delivery_submitted",
        delivery_checked_by_wanyouji_owner=wanyouji_account.phone,
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"丸友集主账号-工作室履约应用-订单列表-查看待验收订单：{source_order_no}/{order_title}",
    )


def resolve_delivery_order_and_accounts() -> tuple[dict[str, Any], E2EAccount, E2EAccount]:
    explicit_order_no = os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "").strip()
    if explicit_order_no:
        os.environ["E2E_TASK_SOURCE_ORDER_NO"] = explicit_order_no
        return resolve_task_order_and_accounts(os.getenv("E2E_TASK_WANZHANGGUI_PHONE", "19147509308"))

    store = account_store()
    payload = store.load_payload()
    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if item.get("status") == "task_player_accepted"
        and item.get("task_player_phone")
        and (item.get("task_wanyouji_phone") or item.get("wanyouji_phones"))
    ]
    candidates = sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)
    assert candidates, "台账中没有可用于 E2E-DELIVERY-001 的已接单订单，请先执行 E2E-TASK-001。"
    order = candidates[0]
    os.environ["E2E_TASK_SOURCE_ORDER_NO"] = order["source_order_no"]
    return resolve_task_order_and_accounts(os.getenv("E2E_TASK_WANZHANGGUI_PHONE", "19147509308"))
