from __future__ import annotations

import os

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.tests.订单状态流转.penalty_recovery_flow_helpers import (
    resolve_order_for_case,
    resolve_player_account,
    resolve_wanyouji_account,
)
from e2e.utils.account_store import account_store
from e2e.utils.dual_browser import assert_distinct_account_contexts


@pytest.mark.s_flow_081
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_081_wanyouji_complete_player_settlement(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    settlement_method = os.getenv("E2E_WANYOUJI_SETTLEMENT_METHOD", "线下支付").strip()
    assert settlement_method in {"线下支付", "线上打款"}, (
        "E2E_WANYOUJI_SETTLEMENT_METHOD 仅支持：线下支付、线上打款；"
        f"当前值：{settlement_method}"
    )

    store = account_store()
    order = resolve_order_for_case(
        case_id="S-FLOW-081",
        wanzhanggui_phone=wanzhanggui_phone,
        current_flow_states=["player_settlement_bill_submitted"],
    )
    if not order:
        pytest.skip("台账中未找到可供 S-FLOW-081 使用的打手结算账单；请先执行 S-FLOW-080。")

    source_order_no = order["source_order_no"]
    main_order_no = order.get("main_order_no", "")
    order_title = order.get("order_title", source_order_no)
    expected_amount = os.getenv("E2E_DELIVERY_EXPECTED_PLAYER_AMOUNT", order.get("expected_player_amount", "70"))
    wanyouji_account = resolve_wanyouji_account(order)
    player_account = resolve_player_account(order, wanyouji_account)

    owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
    owner_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
    config_result = {}
    if settlement_method == "线上打款":
        config_result = owner_page.ensure_wanyouji_online_payment_config_ready()
    completion_result = owner_page.complete_wanyouji_player_settlement_bill(
        source_order_no=source_order_no,
        order_title=order_title,
        settlement_method=settlement_method,
    )
    assert not completion_result.get("expected_rejected"), (
        f"S-FLOW-081 线上打款被平台预期拒绝，未完成结算；source_order_no={source_order_no}; "
        f"result={completion_result}"
    )

    completed_order_text = owner_page.verify_workshop_order_completed_after_player_settlement(
        source_order_no,
        order_title,
    )
    bug_reporter.record_if_errors(
        account=wanyouji_account.phone,
        location=f"S-FLOW-081 丸友集完成打手结算账单：{main_order_no or source_order_no}/{settlement_method}",
    )

    player_browser_page = login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
    assert_distinct_account_contexts(owner_page.page, wanyouji_account.phone, player_browser_page, player_account.phone)
    player_page = WanyoujiFulfillmentPage(player_browser_page, settings.tenant_home_url, bug_reporter)
    expected_total_amount = os.getenv(
        "E2E_PLAYER_SETTLEMENT_EXPECTED_TOTAL_AMOUNT",
        str(
            completion_result.get("settlement_total_amount")
            or order.get("wanyouji_player_settlement_total_amount")
            or expected_amount
        ),
    )
    player_income_completed_text = player_page.verify_player_income_settlement_completed(
        source_order_no,
        order_title,
        expected_amount=expected_amount,
        expected_total_amount=expected_total_amount,
    )
    bug_reporter.record_if_errors(
        account=player_account.phone,
        location=f"S-FLOW-081 打手我的收入已结算校验：{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-081",
        status="player_settlement_completed",
        current_flow_state="player_sub_order_settled_completed_ready_for_next_dispatch",
        task_player_phone=player_account.phone,
        task_wanyouji_phone=wanyouji_account.phone,
        wanyouji_online_payment_config_status="ready" if settlement_method == "线上打款" else order.get("wanyouji_online_payment_config_status", ""),
        wanyouji_online_payment_config_verified_by=wanyouji_account.phone,
        wanyouji_online_payment_app=str(config_result.get("selected_app", "")),
        wanyouji_online_payment_channel=str(config_result.get("selected_channel", "")),
        wanyouji_player_settlement_method=settlement_method,
        wanyouji_player_settlement_completed_by=wanyouji_account.phone,
        wanyouji_player_settlement_result="completed",
        wanyouji_player_settlement_total_amount=str(completion_result.get("settlement_total_amount") or expected_total_amount),
        wanyouji_order_list_completed_verified_by=wanyouji_account.phone,
        wanyouji_order_list_completed_text=completed_order_text[:1500],
        player_income_settlement_completed_verified_by=player_account.phone,
        player_income_settlement_completed_text=player_income_completed_text[:1500],
        wanyouji_sub_order_status="已完成",
        player_order_status="已完成",
        player_income_settlement_status="已结算",
        available_for_cases=["S-FLOW-044", "S-FLOW-045", "S-FLOW-054"],
    )
