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.utils.account_store import E2EAccount, account_store


@pytest.mark.e2e_settle_wyj_emp_bill_init_001
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_丸友集在员工结算汇总账单待发起中生成打手账单(page: Page, settings, bug_reporter) -> None:
    store = account_store()
    order, player_account, wanyouji_account = resolve_employee_pending_bill_order_and_account()
    source_order_no = order["source_order_no"]
    order_title = order["order_title"]
    expected_amount = os.getenv("E2E_DELIVERY_EXPECTED_PLAYER_AMOUNT", order.get("expected_player_amount", "70"))

    owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    owner_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    try:
        owner_page.initiate_employee_settlement_bill_from_pending(
            source_order_no=source_order_no,
            order_title=order_title,
            expected_player_amount=expected_amount,
            player_name=player_account.contact_name or "",
        )
    except AssertionError as exc:
        message = str(exc)
        if "暂无可生成的打手账单" in message or "未找到目标行" in message or "暂无可结算订单" in message:
            pytest.skip(
                "丸友集员工结算汇总-账单待发起暂无目标打手账单；"
                "请先完成打手子单验收并确认打手收入已生成，再执行B-SETTLE-WYJ-EMP-BILL-INIT-001。"
            )
        raise

    store.mark_task_order_status(
        source_order_no=source_order_no,
        status="player_settlement_bill_submitted",
        employee_bill_initiated_by=wanyouji_account.phone,
        employee_bill_initiated_from="员工结算汇总-账单待发起",
        expected_player_amount=expected_amount,
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=(
            "B-SETTLE-WYJ-EMP-BILL-INIT-001 丸友集主账号-工作室基础应用-"
            f"财务结算列表-员工结算汇总-账单待发起：{source_order_no}/{order_title}"
        ),
    )


def resolve_employee_pending_bill_order_and_account() -> tuple[dict[str, Any], E2EAccount, E2EAccount]:
    store = account_store()
    explicit_order_no = os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "").strip()
    explicit_wanyouji_phone = os.getenv("E2E_TASK_WANYOUJI_PHONE", "").strip() or os.getenv("E2E_SETTLE_WANYOUJI_PHONE", "").strip()
    explicit_player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip() or os.getenv("E2E_PLAYER_PHONE", "").strip()
    allowed_statuses = {
        "sub_order_income_verified",
        "player_settlement_page_opened",
        "settlement_verified",
        "delivery_accepted",
        "upstream_completed",
    }
    payload = store.load_payload()
    candidates = [
        item
        for item in payload.get("dispatched_orders", [])
        if item.get("status") in allowed_statuses
        and item.get("task_player_phone")
        and (item.get("task_wanyouji_phone") or item.get("wanyouji_phones"))
        and (not explicit_order_no or item.get("source_order_no") == explicit_order_no)
        and (not explicit_player_phone or item.get("task_player_phone") == explicit_player_phone)
        and (not explicit_wanyouji_phone or item.get("task_wanyouji_phone") == explicit_wanyouji_phone or explicit_wanyouji_phone in (item.get("wanyouji_phones") or []))
    ]
    candidates = sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)
    assert candidates, (
        "台账中没有可用于 B-SETTLE-WYJ-EMP-BILL-INIT-001 的已生成收入订单；"
        "请先执行到打手完成子单并由丸友集验收通过。"
    )

    accounts = {account.phone: account for account in store.load()}
    for order in candidates:
        player = accounts.get(order.get("task_player_phone", ""))
        wanyouji_phone = explicit_wanyouji_phone or order.get("task_wanyouji_phone") or (order.get("wanyouji_phones") or [""])[0]
        wanyouji = accounts.get(wanyouji_phone)
        if player and wanyouji:
            return order, player, wanyouji

    raise AssertionError("台账中未找到目标订单对应的打手账号或丸友集主账号。")
