from __future__ import annotations

import os

import pytest
from playwright.sync_api import Page

from e2e.tests.履约验收.test_e2e_delivery_001_player_submit_acceptance import (
    test_打手确认上号上传首图并提交验收后主账号查看 as run_delivery_001,
)
from e2e.tests.履约验收.test_e2e_delivery_002_upstream_acceptance_settlement import (
    test_丸友集验收打手子单并校验打手收入 as run_delivery_002,
)
from e2e.tests.订单状态流转.order_flow_member_helpers import ensure_wanyouji_player_member
from e2e.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import (
    test_丸掌柜外部派单由丸友集接单并发到打手抢单大厅 as run_task_001,
)
from e2e.tests.结算.test_e2e_settle_player_account_001_payment_account import (
    test_打手完善打款账户信息 as run_settle_player_account_001,
)
from e2e.tests.结算.test_e2e_settle_player_apply_001_create_bill import (
    test_打手在我的收入中点击一键结算并提交账单 as run_settle_player_apply_001,
)
from e2e.utils.account_store import account_store


WORKSHOP_PHONE = "19041265882"
WANZHANGGUI_PHONE = "19159770995"
PLAYER_PHONE = "19012864298"


@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_auth_simplification_player_to_settlement(page: Page, settings, bug_reporter, monkeypatch) -> None:
    store = account_store()
    workshop = store.find_main(WORKSHOP_PHONE)
    assert workshop and workshop.wanyouji_status == "opened", "授权简化工作室未处于丸友集已开通状态"

    monkeypatch.setenv("E2E_PLAYER_PHONE", PLAYER_PHONE)
    player = ensure_wanyouji_player_member(page=page, settings=settings, bug_reporter=bug_reporter, parent=workshop)
    latest_order = next(
        (
            order
            for order in reversed(store.load_payload().get("dispatched_orders", []))
            if order.get("wanzhanggui_phone") == WANZHANGGUI_PHONE
            and WORKSHOP_PHONE in order.get("wanyouji_phones", [])
            and order.get("status") == "dispatched"
        ),
        None,
    )
    assert latest_order, "未找到授权简化策略最近分发且尚未被打手处理的订单"

    monkeypatch.setenv("E2E_TASK_WANZHANGGUI_PHONE", WANZHANGGUI_PHONE)
    monkeypatch.setenv("E2E_TASK_WANYOUJI_PHONE", WORKSHOP_PHONE)
    monkeypatch.setenv("E2E_TASK_PLAYER_PHONE", player.phone)
    monkeypatch.setenv("E2E_TASK_SOURCE_ORDER_NO", latest_order["source_order_no"])
    monkeypatch.setenv("E2E_TASK_ASSIGNMENT_METHOD", "抢单大厅")
    monkeypatch.setenv("E2E_DELIVERY_SOURCE_ORDER_NO", latest_order["source_order_no"])
    monkeypatch.setenv("E2E_REUSE_TENANT_LOGIN", "1")
    monkeypatch.setenv("E2E_REUSE_PLAYER_LOGIN", "1")
    monkeypatch.setenv("E2E_SETTLE_PLAYER_APPLY_SKIP_OWNER_SUMMARY", "1")
    monkeypatch.setenv("E2E_PLAYER_SETTLEMENT_FAST_SEARCH", "1")

    run_task_001(page, settings, bug_reporter)
    run_delivery_001(page, settings, bug_reporter)
    run_delivery_002(page, settings, bug_reporter)
    run_settle_player_account_001(page, settings, bug_reporter)
    run_settle_player_apply_001(page, settings, bug_reporter)
