#!/usr/bin/env python3
"""
测试手动重新匹配采购订单功能
"""
import os
import requests
import json

# 禁用代理
os.environ['NO_PROXY'] = 'localhost,127.0.0.1'
os.environ.pop('http_proxy', None)
os.environ.pop('https_proxy', None)
os.environ.pop('all_proxy', None)


def test_rematch_procurement():
    """测试重新匹配采购订单API"""

    url = "http://localhost:8000/api/v1/new-shipping/rematch-procurement"

    # 首先查询当前状态
    print("=" * 60)
    print("查询当前待发货订单状态...")

    # 获取待发货订单列表查看匹配状态
    list_url = "http://localhost:8000/api/v1/new-shipping/pending-orders"
    list_response = requests.post(list_url, json={"limit": 100})

    if list_response.status_code == 200:
        orders = list_response.json()['orders']
        unmatched_count = sum(1 for order in orders if order.get('procurement_order_id') is None)
        matched_count = sum(1 for order in orders if order.get('procurement_order_id') is not None)

        print(f"当前订单状态:")
        print(f"  总订单数: {len(orders)}")
        print(f"  已匹配: {matched_count}")
        print(f"  未匹配: {unmatched_count}")

        # 显示几个未匹配的订单示例
        unmatched_examples = [o for o in orders if o.get('procurement_order_id') is None][:3]
        if unmatched_examples:
            print("\n未匹配订单示例:")
            for order in unmatched_examples:
                print(f"  - 子订单编号: {order.get('子订单编号')}")
                print(f"    主订单编号: {order.get('主订单编号')}")
                print(f"    商品标题: {order.get('商品标题')[:30]}...")
                print(f"    match_status: {order.get('match_status')}")

    print("\n" + "=" * 60)
    print("执行重新匹配...")

    # 执行重新匹配
    data = {
        'shop_name': None,  # 不限定店铺
        'force_all': False  # 只匹配未匹配的订单
    }

    try:
        response = requests.post(url, data=data, timeout=30)

        if response.status_code == 200:
            result = response.json()
            print("\n✅ 重新匹配成功！")
            print(f"消息: {result['message']}")

            stats = result['statistics']
            print("\n匹配统计:")
            print(f"  处理订单总数: {stats['total_processed']}")

            # 新的分层匹配统计
            if 'level1_matched' in stats:
                print(f"  第1层匹配（单SKU）: {stats['level1_matched']}")
            if 'level2_matched' in stats:
                print(f"  第2层匹配（多SKU不同商品）: {stats['level2_matched']}")
            if 'level3_matched' in stats:
                print(f"  第3层匹配（多SKU相同商品）: {stats['level3_matched']}")

            # 兼容旧字段
            if 'single_sku_matched' in stats:
                print(f"  单SKU订单匹配成功: {stats['single_sku_matched']}")
            if 'multi_sku_matched' in stats:
                print(f"  多SKU订单匹配成功: {stats['multi_sku_matched']}")

            print(f"  匹配失败: {stats['failed']}")
            print(f"  已匹配（跳过）: {stats['already_matched']}")
            print(f"  匹配率: {stats['match_rate']}")

            # 再次查询验证结果
            print("\n" + "=" * 60)
            print("验证匹配结果...")

            verify_response = requests.post(list_url, json={"limit": 100})
            if verify_response.status_code == 200:
                orders_after = verify_response.json()['orders']
                unmatched_after = sum(1 for o in orders_after if o.get('procurement_order_id') is None)
                matched_after = sum(1 for o in orders_after if o.get('procurement_order_id') is not None)

                print(f"\n匹配后订单状态:")
                print(f"  总订单数: {len(orders_after)}")
                print(f"  已匹配: {matched_after} (增加 {matched_after - matched_count})")
                print(f"  未匹配: {unmatched_after} (减少 {unmatched_count - unmatched_after})")

                # 显示成功匹配的示例
                newly_matched = [o for o in orders_after
                               if o.get('procurement_order_id') is not None
                               and o.get('子订单编号') in [x.get('子订单编号') for x in unmatched_examples]]

                if newly_matched:
                    print("\n新匹配成功的订单示例:")
                    for order in newly_matched[:3]:
                        print(f"  - 子订单编号: {order.get('子订单编号')}")
                        print(f"    procurement_order_id: {order.get('procurement_order_id')}")
                        print(f"    match_status: {order.get('match_status')}")

                        # 显示采购信息
                        if order.get('procurement_info'):
                            info = order['procurement_info']
                            print(f"    采购信息:")
                            print(f"      品牌: {info.get('品牌')}")
                            print(f"      颜色: {info.get('颜色')}")
                            print(f"      尺码: {info.get('尺码')}")
                            print(f"      货号: {info.get('货号')}")
        else:
            print(f"❌ 重新匹配失败，状态码: {response.status_code}")
            print(f"错误信息: {response.text}")

    except requests.exceptions.RequestException as e:
        print(f"❌ 网络请求错误: {e}")
    except Exception as e:
        print(f"❌ 未知错误: {e}")


if __name__ == "__main__":
    test_rematch_procurement()