from __future__ import annotations

import os
import random
from datetime import datetime

import pytest
from playwright.sync_api import Page

from e2e.pages.wanzhanggui_order_page import ManualOrderData, WanyoujiFulfillmentPage, WanzhangguiOrderPage
from e2e.tests.订单状态流转.上游发单.test_s_flow_006_dispatch_after_cancel_aftersale import (
    find_accounts_with_dispatch_strategy_name,
    latest_strategy_name_for_type,
)
from e2e.utils.account_store import account_store


@pytest.mark.s_flow_007
@pytest.mark.e2e_ledger
@pytest.mark.e2e_chain
def test_s_flow_007_create_order_with_dispatch(page: Page, settings, bug_reporter) -> None:
    wanzhanggui_phone = os.getenv("E2E_ORDER_WANZHANGGUI_PHONE", settings.wanzhanggui_tenant_phone)
    wanzhanggui_password = os.getenv("E2E_ORDER_WANZHANGGUI_PASSWORD", settings.wanzhanggui_tenant_password)
    strategy_type = os.getenv("E2E_ORDER_STRATEGY_TYPE", "单平台指定")
    assert strategy_type in {"单平台指定", "多工作室同时分发", "多平台分发"}, (
        "E2E_ORDER_STRATEGY_TYPE 仅支持：单平台指定、多工作室同时分发、多平台分发；"
        f"当前值：{strategy_type}"
    )

    strategy_name = latest_strategy_name_for_type(wanzhanggui_phone, strategy_type)
    required_count = 1 if strategy_type == "单平台指定" else 2
    wanyouji_accounts = find_accounts_with_dispatch_strategy_name(
        wanzhanggui_phone,
        strategy_type,
        strategy_name,
        required_count,
    )
    if len(wanyouji_accounts) < required_count:
        pytest.skip(
            f"S-FLOW-007 至少需要 {required_count} 个已配置 {strategy_type}/{strategy_name} 的丸友集账号；"
            f"当前仅找到 {len(wanyouji_accounts)} 个"
        )

    order = resolve_s_flow_007_order(strategy_name, strategy_type)
    order_page = WanzhangguiOrderPage(page, settings.tenant_home_url, bug_reporter)
    order_page.login_main_account(wanzhanggui_phone, wanzhanggui_password)
    bug_reporter.record_if_errors(account=wanzhanggui_phone, location="S-FLOW-007 丸掌柜账号登录")

    if should_create_order(order):
        order_page.create_manual_order(order)
        main_order_no = order_page.find_main_order_no_from_order_list(
            source_order_no=order.source_order_no,
            order_title=order.order_title,
        )
        assert main_order_no.startswith("BO"), (
            f"S-FLOW-007 创建已推单主单后未提取到 BO 主单号；"
            f"source_order_no={order.source_order_no}; order_title={order.order_title}"
        )
    else:
        main_order_no = order.main_order_no

    detail_status_text = order_page.assert_order_detail_statuses(
        main_order_no=main_order_no,
        source_order_no=order.source_order_no,
        order_title=order.order_title,
        expected_main_status="待接单",
        expected_sub_status_parts=["待接单", "已推单"],
        expected_sub_order_list_status="已发布",
        expected_aftersale_absent=True,
    )
    bug_reporter.record_if_errors(
        account=wanzhanggui_phone,
        location=f"S-FLOW-007 丸掌柜创建主单已推单状态校验：{main_order_no or order.source_order_no}",
    )

    expected_scope = "私单" if strategy_type == "单平台指定" else "公池单/私单"
    wanyouji_hall_status_texts: list[str] = []
    for wanyouji_account in wanyouji_accounts[:required_count]:
        fulfillment_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
        fulfillment_page.login_main_account(wanyouji_account.phone, wanyouji_account.password)
        bug_reporter.record_if_errors(account=wanyouji_account.phone, location="S-FLOW-007 丸友集账号登录")
        hall_status_text = fulfillment_page.verify_order_reached_hall(
            order.source_order_no,
            order.order_title,
            expected_scope,
            main_order_no=main_order_no,
            expected_status="待接单",
        )
        wanyouji_hall_status_texts.append(hall_status_text[:1500])
        bug_reporter.record_if_errors(
            account=wanyouji_account.phone,
            location=f"S-FLOW-007 丸友集抢单大厅可见且待接单：{main_order_no or order.source_order_no}",
        )

    account_store().mark_order_without_dispatch(
        wanzhanggui_phone=wanzhanggui_phone,
        main_order_no=main_order_no,
        source_order_no=order.source_order_no,
        order_title=order.order_title,
        wanyouji_phones=[account.phone for account in wanyouji_accounts[:required_count]],
    )
    account_store().mark_order_consumed_by_flow_case(
        source_order_no=order.source_order_no,
        case_id="S-FLOW-007",
        status="dispatched",
        current_flow_state="wanyouji_pending_accept_rejectable",
        strategy_name=strategy_name,
        strategy_type=strategy_type,
        wanyouji_phones=[account.phone for account in wanyouji_accounts[:required_count]],
        wanzhanggui_main_status="待接单",
        wanzhanggui_sub_order_status="待接单-已推单",
        wanzhanggui_sub_order_list_status="已发布",
        wanyouji_visibility="hall_visible",
        wanyouji_hall_status="待接单",
        created_with_dispatch_by=wanzhanggui_phone,
        created_with_dispatch_detail_status_text=detail_status_text[:1500],
        created_with_dispatch_wanyouji_hall_status_texts=wanyouji_hall_status_texts,
        available_for_cases=["S-FLOW-008", "S-FLOW-011", "S-FLOW-014"],
    )


def resolve_s_flow_007_order(strategy_name: str, strategy_type: str) -> ManualOrderData:
    explicit_main_order_no = os.getenv("E2E_S_FLOW_MAIN_ORDER_NO", "").strip()
    explicit_source_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "").strip()
    explicit_order_title = os.getenv("E2E_S_FLOW_ORDER_TITLE", "").strip()
    if explicit_main_order_no or explicit_source_order_no:
        return ManualOrderData(
            source_order_no=explicit_source_order_no,
            order_title=explicit_order_title or explicit_source_order_no or explicit_main_order_no,
            strategy_name=strategy_name,
            strategy_type=strategy_type,
            main_order_no=explicit_main_order_no,
            receive_price=manual_order_receive_price(),
            dispatch_price=os.getenv("E2E_S_FLOW_DISPATCH_PRICE", "70"),
        )

    timestamp = datetime.now().strftime("%m%d%H%M%S")
    return ManualOrderData(
        source_order_no=f"E2EORDER{timestamp}",
        order_title=f"E2E手工录单已推单{timestamp}",
        strategy_name=strategy_name,
        strategy_type=strategy_type,
        receive_price=manual_order_receive_price(),
        dispatch_price=os.getenv("E2E_S_FLOW_DISPATCH_PRICE", "70"),
        role_name=f"SFlow角色{timestamp[-4:]}",
    )


def should_create_order(order: ManualOrderData) -> bool:
    if order.main_order_no:
        return False
    mode = os.getenv("E2E_S_FLOW_CREATE_MODE", "create").strip().lower()
    return mode not in {"reuse", "existing"}


def manual_order_receive_price() -> str:
    explicit = os.getenv("E2E_MANUAL_ORDER_RECEIVE_PRICE", "").strip()
    if explicit:
        value = int(explicit)
        assert 50 <= value <= 300, f"E2E_MANUAL_ORDER_RECEIVE_PRICE must be between 50 and 300, got {value}"
        return str(value)
    return str(random.randint(50, 300))
