#!/bin/bash

# 完整的审批功能测试报告生成器

echo "=========================================="
echo "Monisuo 审批功能诊断报告"
echo "生成时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo "=========================================="
echo ""

BASE_URL="http://localhost:5010"

# 1. 管理员登录
echo "[1] 管理员登录"
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/admin/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin123"}')

TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.data.token')

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
  echo "✗ 管理员登录失败"
  exit 1
fi

echo "✓ 管理员登录成功"
echo ""

# 2. 查询所有充值订单（状态=2）
echo "[2] 查询所有状态=2的充值订单"
ORDERS_RESPONSE=$(curl -s -X GET "$BASE_URL/admin/order/list?type=1&status=2&pageNum=1&pageSize=20" \
  -H "Authorization: Bearer $TOKEN")

echo "$ORDERS_RESPONSE" | jq -r '.data.list[] | "订单号: \(.orderNo), 金额: \(.amount), 状态: \(.status), 审批时间: \(.approveTime // "无"), 确认时间: \(.confirmTime // "无")"'

TOTAL=$(echo "$ORDERS_RESPONSE" | jq -r '.data.total')
echo ""
echo "待确认订单总数（API返回）: $TOTAL"
echo ""

# 3. 查询用户5的账户信息
echo "[3] 查询用户5的账户信息"
USER_DETAIL=$(curl -s -X GET "$BASE_URL/admin/user/detail?userId=5" \
  -H "Authorization: Bearer $TOKEN")

BALANCE=$(echo "$USER_DETAIL" | jq -r '.data.fund.balance')
FROZEN=$(echo "$USER_DETAIL" | jq -r '.data.fund.frozen')
TOTAL_DEPOSIT=$(echo "$USER_DETAIL" | jq -r '.data.fund.totalDeposit')
TOTAL_WITHDRAW=$(echo "$USER_DETAIL" | jq -r '.data.fund.totalWithdraw')

echo "余额: $BALANCE USDT"
echo "冻结: $FROZEN USDT"
echo "累计充值: $TOTAL_DEPOSIT USDT"
echo "累计提现: $TOTAL_WITHDRAW USDT"
echo ""

# 4. 分析问题
echo "[4] 问题分析"
echo "--------------------"

# 获取所有状态=2的订单
ORDER_COUNT=$(echo "$ORDERS_RESPONSE" | jq -r '.data.list | length')

if [ "$ORDER_COUNT" -gt 0 ]; then
  echo "⚠️  发现 $ORDER_COUNT 个状态=2的充值订单，但部分可能已被审批"
  echo ""
  
  # 检查每个订单
  echo "$ORDERS_RESPONSE" | jq -r '.data.list[] | select(.approveTime != null) | .orderNo' | while read ORDER_NO; do
    echo "  订单 $ORDER_NO - 已审批但状态仍为2"
  done
  
  echo ""
  echo "【诊断结论】"
  echo "1. 订单状态没有正确更新到数据库"
  echo "2. 可能原因："
  echo "   - MyBatis-Plus updateById 方法执行失败"
  echo "   - 事务回滚"
  echo "   - 数据库连接问题"
  echo ""
  echo "【建议修复】"
  echo "1. 检查数据库连接和权限"
  echo "2. 检查 MyBatis-Plus 配置"
  echo "3. 查看应用日志，确认 updateById 是否执行成功"
  echo "4. 添加数据库字段更新日志"
else
  echo "✓ 没有发现异常订单"
fi

echo ""
echo "=========================================="
echo "诊断完成"
echo "=========================================="
