#!/usr/bin/env python3
"""
测试文件上传的链式处理功能
"""

import requests
import json
import time
import os
from datetime import datetime

# 禁用代理，避免连接问题
os.environ['NO_PROXY'] = 'localhost,127.0.0.1'
for proxy_var in ['http_proxy', 'https_proxy', 'all_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY']:
    if proxy_var in os.environ:
        del os.environ[proxy_var]

def test_upload_with_chain_processing():
    """测试上传文件并验证链式处理"""
    
    # API端点
    base_url = "http://localhost:8000/api/v1"
    upload_url = f"{base_url}/import/upload"
    
    # 选择测试文件 - 使用新创建的测试文件
    test_file = "/Users/jinjunqian/PycharmProjects/订单处理新版/ordersys/test_new_orders.csv"
    
    print(f"测试文件上传链式处理")
    print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)
    
    # 准备文件
    with open(test_file, 'rb') as f:
        files = {'file': ('test_orders.csv', f, 'text/csv')}
        
        print(f"\n1. 上传文件: {test_file}")
        print("   正在上传...")
        
        # 发送请求
        start_time = time.time()
        response = requests.post(upload_url, files=files)
        elapsed_time = time.time() - start_time
        
    # 检查响应
    if response.status_code == 200:
        result = response.json()
        print(f"   ✓ 上传成功 (耗时: {elapsed_time:.2f}秒)")
        print(f"\n2. 导入结果:")
        print(f"   - 状态: {result.get('status')}")
        print(f"   - 导入行数: {result.get('total_imported')}")
        print(f"   - 失败行数: {result.get('total_failed')}")
        
        # 检查链式处理结果
        if 'chain_processing' in result and result['chain_processing']:
            chain = result['chain_processing']
            print(f"\n3. 链式处理结果:")
            print(f"   - 新增产品: {chain.get('products_created', 0)} 个")
            print(f"   - 更新产品: {chain.get('products_updated', 0)} 个")
            print(f"   - 生成采购订单: {chain.get('procurement_orders_created', 0)} 个")
            
            if chain.get('products_created', 0) > 0 or chain.get('procurement_orders_created', 0) > 0:
                print("\n   ✓ 链式处理成功触发并执行！")
            else:
                print("\n   ⚠ 链式处理已触发，但没有新数据生成（可能数据已存在）")
        else:
            print(f"\n3. 链式处理:")
            print(f"   ⚠ 未触发链式处理（可能没有新数据导入）")
        
        # 显示错误（如果有）
        if result.get('errors'):
            print(f"\n4. 错误信息:")
            for error in result['errors']:
                print(f"   - {error}")
        
        print("\n" + "=" * 60)
        print("测试完成！")
        
        # 返回结果供进一步分析
        return result
        
    else:
        print(f"   ✗ 上传失败")
        print(f"   状态码: {response.status_code}")
        print(f"   错误: {response.text}")
        return None

def check_products_and_procurement():
    """检查产品主表和采购订单的统计"""
    base_url = "http://localhost:8000/api/v1"
    
    print("\n检查系统数据统计:")
    print("-" * 40)
    
    # 检查产品主表统计
    try:
        response = requests.get(f"{base_url}/products-master/stats")
        if response.status_code == 200:
            stats = response.json()
            print(f"产品主表统计:")
            print(f"  - 总产品数: {stats.get('total_products', 0)}")
            print(f"  - 已批准: {stats.get('approved_count', 0)}")
    except Exception as e:
        print(f"获取产品统计失败: {e}")
    
    # 检查采购订单统计
    try:
        response = requests.get(f"{base_url}/procurement/stats")
        if response.status_code == 200:
            stats = response.json()
            print(f"\n采购订单统计:")
            print(f"  - 总订单数: {stats.get('total_orders', 0)}")
    except Exception as e:
        print(f"获取采购订单统计失败: {e}")

if __name__ == "__main__":
    # 执行测试
    result = test_upload_with_chain_processing()
    
    # 如果上传成功，等待几秒后检查统计
    if result and result.get('total_imported', 0) > 0:
        print("\n等待2秒后检查系统数据...")
        time.sleep(2)
        check_products_and_procurement()