#!/usr/bin/env python3
"""
测试订单更新逻辑
验证：
1. update模式是否正确更新3个字段（交易状态、卖家备注、退款状态）
2. 采购订单状态是否正确同步
3. 采购订单不会因为状态变化而被删除
"""

import asyncio
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

# 设置正确的数据库路径
os.environ['DATABASE_URL'] = 'sqlite+aiosqlite:///./backend/ordersys.db'

from datetime import datetime
from app.core.database import get_db, AsyncSessionLocal
from app.services.import_service import ImportService
from app.services.procurement_order_sync_service import ProcurementOrderSyncService
from app.models.raw_orders import RawOrder
from app.models.procurement_orders import ProcurementOrder
from sqlalchemy import select, func
import json


async def test_update_logic():
    """测试更新逻辑的主函数"""
    print("=" * 50)
    print("开始测试订单更新逻辑")
    print("=" * 50)
    
    async with AsyncSessionLocal() as db:
        # 1. 检查原始订单和采购订单的初始状态
        print("\n1. 检查初始状态...")
        
        # 获取一些原始订单样本
        raw_orders_query = select(RawOrder).limit(5)
        result = await db.execute(raw_orders_query)
        raw_orders = result.scalars().all()
        
        if not raw_orders:
            print("❌ 没有找到原始订单，请先导入一些订单数据")
            return
        
        print(f"✅ 找到 {len(raw_orders)} 个原始订单样本")
        
        # 显示初始状态
        print("\n原始订单初始状态：")
        for order in raw_orders[:3]:
            print(f"  订单 {order.原始订单编号}:")
            print(f"    - 交易状态: {order.交易状态}")
            print(f"    - 退款状态: {order.退款状态}")
            print(f"    - 卖家备注: {order.卖家备注}")
        
        # 获取对应的采购订单
        procurement_orders_query = select(ProcurementOrder).limit(5)
        result = await db.execute(procurement_orders_query)
        procurement_orders = result.scalars().all()
        
        if procurement_orders:
            print(f"\n✅ 找到 {len(procurement_orders)} 个采购订单")
            print("\n采购订单初始状态：")
            for p_order in procurement_orders[:3]:
                print(f"  采购订单 {p_order.id} (原始订单: {p_order.原始订单编号}):")
                print(f"    - 交易状态: {p_order.交易状态}")
                print(f"    - 退款状态: {p_order.退款状态}")
                print(f"    - 卖家备注: {p_order.卖家备注}")
        
        # 2. 模拟更新一个订单的状态
        print("\n" + "=" * 50)
        print("2. 模拟更新订单状态...")
        
        if raw_orders:
            test_order = raw_orders[0]
            print(f"\n选择测试订单: {test_order.原始订单编号}")
            
            # 创建更新数据
            update_data = {
                '原始订单编号': test_order.原始订单编号,
                '线上宝贝名称': test_order.线上宝贝名称,
                '线上销售属性': test_order.线上销售属性,
                '数量': test_order.数量,
                '付款时间': test_order.付款时间,
                '交易状态': '已取消',  # 模拟取消
                '退款状态': '退款成功',  # 模拟退款
                '卖家备注': '测试更新备注 - ' + datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
            
            # 使用ImportService的更新方法
            import_service = ImportService()
            updated = await import_service._update_existing_order(db, update_data)
            
            if updated:
                print("✅ 成功更新订单")
                
                # 重新查询订单验证更新
                updated_order = await db.get(RawOrder, test_order.id)
                print(f"\n更新后的订单状态:")
                print(f"  - 交易状态: {test_order.交易状态} -> {updated_order.交易状态}")
                print(f"  - 退款状态: {test_order.退款状态} -> {updated_order.退款状态}")
                print(f"  - 卖家备注: {updated_order.卖家备注}")
            else:
                print("❌ 更新订单失败")
        
        # 3. 测试采购订单状态同步
        print("\n" + "=" * 50)
        print("3. 测试采购订单状态同步...")
        
        sync_service = ProcurementOrderSyncService()
        sync_result = await sync_service.sync_order_status(db)
        
        print(f"\n同步结果:")
        print(f"  - 总订单数: {sync_result.get('total_orders', 0)}")
        print(f"  - 同步成功: {sync_result.get('synced_orders', 0)}")
        print(f"  - 同步失败: {sync_result.get('failed_orders', 0)}")
        
        if sync_result.get('errors'):
            print(f"  - 错误: {sync_result['errors'][:3]}")  # 只显示前3个错误
        
        # 4. 验证采购订单是否保留
        print("\n" + "=" * 50)
        print("4. 验证采购订单是否保留...")
        
        # 查询所有状态为"已取消"或"退款成功"的采购订单
        cancelled_procurement_query = select(ProcurementOrder).where(
            (ProcurementOrder.交易状态 == '已取消') | 
            (ProcurementOrder.退款状态 == '退款成功')
        )
        result = await db.execute(cancelled_procurement_query)
        cancelled_procurements = result.scalars().all()
        
        if cancelled_procurements:
            print(f"\n✅ 找到 {len(cancelled_procurements)} 个已取消/退款的采购订单（已保留）")
            for cp in cancelled_procurements[:3]:
                print(f"  - 采购订单 {cp.id}: 交易状态={cp.交易状态}, 退款状态={cp.退款状态}")
        else:
            print("\n⚠️ 没有找到已取消/退款的采购订单")
        
        # 5. 获取同步统计信息
        print("\n" + "=" * 50)
        print("5. 获取同步统计信息...")
        
        stats = await sync_service.get_sync_statistics(db)
        print(f"\n同步统计:")
        print(f"  - 总采购订单数: {stats.get('total_orders', 0)}")
        print(f"  - 交易状态不一致: {stats.get('trade_status_mismatch', 0)}")
        print(f"  - 退款状态不一致: {stats.get('refund_status_mismatch', 0)}")
        print(f"  - 卖家备注不一致: {stats.get('seller_note_mismatch', 0)}")
        
        print("\n" + "=" * 50)
        print("测试完成！")
        print("=" * 50)


if __name__ == "__main__":
    asyncio.run(test_update_logic())