#!/bin/bash

BASE_URL="http://localhost:5010"

echo "================================"
echo "测试Flutter资产页面API调用"
echo "================================"

# 1. 用户登录
echo -e "\n步骤1: 用户登录..."
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/api/user/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"abcd","password":"abcd123"}')

TOKEN=$(echo $LOGIN_RESPONSE | python3 -c "
import sys, json
data = json.load(sys.stdin)
if data.get('success'):
    print(data['data']['token'])
" 2>/dev/null)

if [ -z "$TOKEN" ]; then
    echo "❌ 登录失败"
    exit 1
fi

echo "✅ 登录成功"

# 2. 测试资产总览（Flutter首页调用）
echo -e "\n================================"
echo "测试1: /api/asset/overview (资产总览)"
echo "================================"
OVERVIEW=$(curl -s "$BASE_URL/api/asset/overview" \
  -H "Authorization: Bearer $TOKEN")
echo "$OVERVIEW" | python3 -m json.tool

# 3. 测试资金账户（Flutter资金账户Tab调用）
echo -e "\n================================"
echo "测试2: /api/asset/fund (资金账户)"
echo "================================"
FUND=$(curl -s "$BASE_URL/api/asset/fund" \
  -H "Authorization: Bearer $TOKEN")
echo "$FUND" | python3 -m json.tool

# 4. 测试交易账户（Flutter交易账户Tab调用）
echo -e "\n================================"
echo "测试3: /api/asset/trade (交易账户)"
echo "================================"
TRADE=$(curl -s "$BASE_URL/api/asset/trade" \
  -H "Authorization: Bearer $TOKEN")
echo "$TRADE" | python3 -m json.tool

# 5. 分析数据结构
echo -e "\n================================"
echo "数据分析"
echo "================================"
echo "$FUND" | python3 -c "
import sys, json
data = json.load(sys.stdin)
if data.get('success') and data.get('data'):
    fund = data['data'].get('fund', {})
    print('资金账户数据:')
    print(f'  - balance: {fund.get(\"balance\")}')
    print(f'  - frozen: {fund.get(\"frozen\")}')
    print(f'  - total_deposit: {fund.get(\"totalDeposit\")}')
    print(f'  - total_withdraw: {fund.get(\"totalWithdraw\")}')
    
    if fund.get('balance') == 0:
        print('\n⚠️  余额为0，但数据库中应该有15500')
    else:
        print(f'\n✅ 余额正确: {fund.get(\"balance\")}')
"

echo "$TRADE" | python3 -c "
import sys, json
data = json.load(sys.stdin)
if data.get('success') and data.get('data'):
    positions = data['data'].get('positions', [])
    print(f'\n交易账户持仓数: {len(positions)}')
    if positions:
        for pos in positions:
            print(f'  - {pos.get(\"coinCode\")}: {pos.get(\"quantity\")} (价值: {pos.get(\"value\")} USDT)')
    else:
        print('  暂无持仓')
"

echo -e "\n================================"
echo "测试完成"
echo "================================"
