#!/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_notes_columns():
    """测试备注字段是否在API响应中"""

    url = "http://localhost:8000/api/v1/new-shipping/pending-orders"
    headers = {"Content-Type": "application/json"}
    data = {"limit": 10}

    try:
        response = requests.post(url, json=data, headers=headers, timeout=10)

        if response.status_code == 200:
            result = response.json()
            print(f"✅ API请求成功")
            print(f"总订单数: {result.get('total', 0)}")

            if result.get('orders'):
                print("\n备注字段展示:")
                print("=" * 80)

                has_seller_notes = False
                has_buyer_notes = False

                for i, order in enumerate(result['orders'][:5], 1):
                    print(f"\n订单 {i}:")
                    print(f"  子订单编号: {order.get('子订单编号')}")
                    print(f"  商品标题: {order.get('商品标题')[:30]}...")

                    # 检查卖家备注
                    seller_note = order.get('商家备注')
                    if seller_note and seller_note.strip():
                        print(f"  ✅ 卖家备注: {seller_note}")
                        has_seller_notes = True
                    else:
                        print(f"  ⚪ 卖家备注: (无)")

                    # 检查买家备注
                    buyer_note = order.get('主订单买家留言')
                    if buyer_note and buyer_note.strip():
                        print(f"  ✅ 买家备注: {buyer_note}")
                        has_buyer_notes = True
                    else:
                        print(f"  ⚪ 买家备注: (无)")

                # 统计结果
                print("\n" + "=" * 80)
                print("字段存在性检查:")

                # 检查字段是否存在于响应中
                first_order = result['orders'][0]
                if '商家备注' in first_order:
                    print("  ✅ API响应包含 '商家备注' 字段")
                else:
                    print("  ❌ API响应缺少 '商家备注' 字段")

                if '主订单买家留言' in first_order:
                    print("  ✅ API响应包含 '主订单买家留言' 字段")
                else:
                    print("  ❌ API响应缺少 '主订单买家留言' 字段")

                print("\n数据统计:")
                if has_seller_notes:
                    print("  ✅ 存在包含卖家备注的订单")
                else:
                    print("  ⚪ 暂无卖家备注数据（可能所有订单都没有备注）")

                if has_buyer_notes:
                    print("  ✅ 存在包含买家备注的订单")
                else:
                    print("  ⚪ 暂无买家备注数据（可能所有订单都没有留言）")

                # 详细统计
                seller_count = sum(1 for o in result['orders'] if o.get('商家备注') and o.get('商家备注').strip())
                buyer_count = sum(1 for o in result['orders'] if o.get('主订单买家留言') and o.get('主订单买家留言').strip())

                print(f"\n在前 {len(result['orders'])} 个订单中:")
                print(f"  - {seller_count} 个订单有卖家备注")
                print(f"  - {buyer_count} 个订单有买家备注")

            else:
                print("⚠️ 没有返回订单数据")

        else:
            print(f"❌ API请求失败，状态码: {response.status_code}")
            print(f"响应内容: {response.text}")

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


if __name__ == "__main__":
    test_notes_columns()