#!/usr/bin/env python
"""
测试批量修改品牌功能修复
"""

import asyncio
import aiohttp
import json
from datetime import datetime

API_BASE_URL = "http://localhost:8000/api/v1"

async def test_batch_brand_update():
    """测试批量修改品牌"""
    
    async with aiohttp.ClientSession() as session:
        print("="*60)
        print("批量修改品牌功能测试（修复后）")
        print(f"测试时间: {datetime.now().isoformat()}")
        print("="*60)
        
        # 1. 先获取产品数量
        print("\n1. 检查产品数量:")
        async with session.get(
            f"{API_BASE_URL}/products-master/stats"
        ) as resp:
            if resp.status == 200:
                data = await resp.json()
                total_products = data.get('total_products', 0)
                print(f"  总产品数: {total_products}")
                
                if total_products == 0:
                    print("\n⚠️ 数据库中没有产品数据")
                    print("请先运行数据导入或生成产品主表")
                    return
            else:
                print(f"  获取统计信息失败: {resp.status}")
                return
        
        # 2. 获取几个产品进行测试
        print("\n2. 获取测试产品（前3个）:")
        async with session.get(
            f"{API_BASE_URL}/products-master/products",
            params={"page": 1, "page_size": 3}
        ) as resp:
            if resp.status == 200:
                data = await resp.json()
                products = data.get('data', [])
                
                if not products:
                    print("  没有获取到产品数据")
                    return
                
                print(f"  找到 {len(products)} 个产品:")
                for p in products:
                    print(f"    ID: {p['id']}, 当前品牌: {p.get('品牌', 'N/A')}")
                    print(f"       名称: {p.get('线上宝贝名称', '')[:40]}...")
            else:
                print(f"  获取产品失败: {resp.status}")
                return
        
        # 3. 测试批量修改品牌
        print("\n3. 批量修改品牌为 'TestBrand':")
        
        update_data = {
            "operation_type": "update_brand",  # 修复：使用正确的枚举值
            "updates": [
                {
                    "product_id": p['id'],
                    "品牌": "TestBrand"
                }
                for p in products
            ],
            "operator": "测试脚本",
            "reason": "批量品牌修改功能测试"
        }
        
        print(f"  准备更新 {len(update_data['updates'])} 个产品")
        
        async with session.post(
            f"{API_BASE_URL}/products-master/batch-update",
            json=update_data
        ) as resp:
            if resp.status == 200:
                result = await resp.json()
                print(f"  ✓ 批量更新成功:")
                print(f"    成功: {result.get('updated', 0)} 个")
                print(f"    失败: {result.get('failed', 0)} 个")
                print(f"    消息: {result.get('message', '')}")
            else:
                error_text = await resp.text()
                print(f"  ✗ 批量更新失败: 状态码 {resp.status}")
                print(f"    错误: {error_text}")
                return
        
        # 4. 验证更新结果
        print("\n4. 验证更新结果:")
        
        async with session.get(
            f"{API_BASE_URL}/products-master/products",
            params={"page": 1, "page_size": 10}
        ) as resp:
            if resp.status == 200:
                data = await resp.json()
                updated_products = data.get('data', [])
                
                for original_product in products:
                    updated = next(
                        (p for p in updated_products if p['id'] == original_product['id']),
                        None
                    )
                    if updated:
                        new_brand = updated.get('品牌', 'N/A')
                        status = "✓" if new_brand == "TestBrand" else "✗"
                        print(f"  {status} ID {updated['id']}: 品牌 = '{new_brand}'")
        
        print("\n" + "="*60)
        print("✅ 测试完成！")
        print("="*60)

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