"""
测试团队管理API
"""
import asyncio
import sys
from pathlib import Path

# 添加项目路径
sys.path.append(str(Path(__file__).resolve().parent))

import httpx


async def test_team_api():
    """测试团队管理API"""
    base_url = "http://localhost:8000"
    
    print("=" * 60)
    print("测试团队管理API")
    print("=" * 60)
    
    # 1. 登录获取token
    print("\n【1. 登录admin用户】")
    login_data = {
        "username": "admin",
        "password": "admin123"
    }
    
    async with httpx.AsyncClient() as client:
        try:
            response = await client.post(
                f"{base_url}/api/v1/auth/login",
                json=login_data,
                timeout=10.0
            )
            print(f"登录状态: {response.status_code}")
            result = response.json()
            print(f"响应内容: {result}")
            
            if response.status_code == 200:
                # 尝试不同的数据结构
                token = None
                if "access_token" in result:
                    token = result["access_token"]
                elif result.get("data"):
                    if "access_token" in result["data"]:
                        token = result["data"]["access_token"]
                    elif "token" in result["data"] and "access_token" in result["data"]["token"]:
                        token = result["data"]["token"]["access_token"]
                
                if token:
                    print(f"登录成功，获取token: {token[:30]}...")
                else:
                    print(f"无法获取token，响应结构: {list(result.keys())}")
                    return
            else:
                print(f"登录失败: HTTP {response.status_code}")
                return
        except Exception as e:
            print(f"登录失败: {e}")
            return
        
        # 2. 测试团队统计API
        print("\n【2. 获取团队统计】")
        headers = {"Authorization": f"Bearer {token}"}
        try:
            response = await client.get(
                f"{base_url}/api/v1/team/management/statistics",
                headers=headers,
                timeout=10.0
            )
            print(f"状态: {response.status_code}")
            result = response.json()
            print(f"结果: {result}")
        except Exception as e:
            print(f"获取统计失败: {e}")
        
        # 3. 测试团队成员列表API
        print("\n【3. 获取团队成员列表】")
        try:
            response = await client.get(
                f"{base_url}/api/v1/team/management/members",
                headers=headers,
                params={"page": 1, "size": 20},
                timeout=10.0
            )
            print(f"状态: {response.status_code}")
            result = response.json()
            print(f"返回code: {result.get('code')}")
            print(f"返回message: {result.get('message')}")
            
            if result.get("data"):
                data = result["data"]
                print(f"总记录数: {data.get('total')}")
                print(f"当前页: {data.get('page')}")
                print(f"每页大小: {data.get('page_size')}")
                print(f"总页数: {data.get('pages')}")
                print(f"返回记录数: {len(data.get('items', []))}")
                
                if data.get('items'):
                    print("\n前3个成员:")
                    for member in data['items'][:3]:
                        print(f"  - ID:{member['id']}, 姓名:{member['name']}, 岗位:{member['position']}, 状态:{member['status']}")
            else:
                print("无数据返回")
        except Exception as e:
            print(f"获取成员列表失败: {e}")
    
    print("\n" + "=" * 60)


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

