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


@pytest.mark.e2e_settle_player_apply_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_player_settlement_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"))

    if order.get("status") not in {"player_settlement_bill_submitted", "settlement_verified"}:
        player_browser_page = login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
        player_page = WanyoujiFulfillmentPage(player_browser_page, settings.tenant_home_url, bug_reporter)
        player_page.apply_player_settlement_for_order(
            source_order_no,
            order_title,
            expected_amount=expected_amount,
            account_name=os.getenv("E2E_PLAYER_PAYMENT_ACCOUNT_NAME", player_account.contact_name or "E2E打手"),
            account_phone=os.getenv("E2E_PLAYER_PAYMENT_ACCOUNT_PHONE", player_account.phone),
            payment_account=os.getenv("E2E_PLAYER_PAYMENT_ACCOUNT_NO", f"e2e{player_account.phone}@example.com"),
            bank_name=os.getenv("E2E_PLAYER_PAYMENT_BANK_NAME", "E2E测试银行"),
            id_card=os.getenv("E2E_PLAYER_PAYMENT_ID_CARD", "110101199001011234"),
        )
        store.upsert(
            player_account,
            player_payment_account_status="ready",
            player_payment_account_verified_by=player_account.phone,
        )
        store.mark_task_order_status(
            source_order_no=source_order_no,
            status="player_settlement_bill_submitted",
            player_settlement_bill_submitted_by=player_account.phone,
            expected_player_amount=expected_amount,
        )
        bug_reporter.record_if_errors(
            account=player_account.phone,
            location=f"丸友集打手账号-我的收入-一键结算提交账单：{source_order_no}/{order_title}",
        )

    if os.getenv("E2E_SETTLE_PLAYER_APPLY_SKIP_OWNER_SUMMARY", "").lower() in {"1", "true", "yes"}:
        return

    owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    owner_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    owner_page.verify_workshop_employee_settlement_summary_detail(
        source_order_no,
        order_title,
        expected_player_amount=expected_amount,
        player_name=player_account.contact_name or "",
        settlement_batch_no=order.get("player_settlement_batch_no", ""),
    )
    store.mark_task_order_status(
        source_order_no=source_order_no,
        status="settlement_verified",
        player_settlement_bill_verified_by=wanyouji_account.phone,
        expected_player_amount=expected_amount,
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"丸友集主账号-工作室基础应用-财务结算列表-员工结算汇总-详情：{source_order_no}/{order_title}",
    )


def resolve_player_settlement_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()
    explicit_player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip() or os.getenv("E2E_PLAYER_PHONE", "").strip()
    payload = store.load_payload()
    allowed_statuses = {"sub_order_income_verified", "player_settlement_bill_submitted", "settlement_verified"}
    if explicit_order_no:
        allowed_statuses.add("player_settlement_page_opened")
    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)
    ]
    candidates = sorted(candidates, key=lambda item: item.get("updated_at", item.get("created_at", "")), reverse=True)
    assert candidates, "台账中没有可用于 B-SETTLE-PLAYER-APPLY-001 的已生成收入订单，请先执行 A-DELIVERY-002。"

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

    raise AssertionError("未找到已完善打款账户、丸友集主账号且存在收入记录的结算数据，请先执行 B-SETTLE-PLAYER-ACCOUNT-001 和 A-DELIVERY-002。")
