#!/bin/bash

# 订单审批功能测试脚本
# 用于诊断审批后订单状态不更新的问题

BASE_URL="http://localhost:5010"
ADMIN_TOKEN=""

echo "================================"
echo "订单审批功能诊断测试"
echo "================================"
echo ""

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

echo "登录响应: $LOGIN_RESPONSE"
ADMIN_TOKEN=$(echo $LOGIN_RESPONSE | grep -o '"token":"[^"]*' | cut -d'"' -f4)
echo "Token: ${ADMIN_TOKEN:0:20}..."
echo ""

# 2. 获取待审批订单列表
echo "步骤2: 获取待审批订单..."
PENDING_RESPONSE=$(curl -s "$BASE_URL/admin/order/pending" \
  -H "Authorization: Bearer $ADMIN_TOKEN")

echo "待审批订单响应:"
echo "$PENDING_RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$PENDING_RESPONSE"
echo ""

# 提取第一个订单号
ORDER_NO=$(echo $PENDING_RESPONSE | grep -o '"orderNo":"[^"]*' | head -1 | cut -d'"' -f4)
if [ -z "$ORDER_NO" ]; then
    echo "❌ 没有待审批的订单"
    exit 1
fi

echo "选择的订单号: $ORDER_NO"
echo ""

# 3. 查询订单详情（审批前）
echo "步骤3: 查询订单详情（审批前）..."
DETAIL_RESPONSE=$(curl -s "$BASE_URL/admin/order/list?orderNo=$ORDER_NO" \
  -H "Authorization: Bearer $ADMIN_TOKEN")

echo "订单详情（审批前）:"
echo "$DETAIL_RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$DETAIL_RESPONSE"

BEFORE_STATUS=$(echo $DETAIL_RESPONSE | grep -o '"status":[0-9]*' | head -1 | cut -d':' -f2)
echo "审批前状态: $BEFORE_STATUS"
echo ""

# 4. 执行审批（通过）
echo "步骤4: 执行审批（通过）..."
APPROVE_RESPONSE=$(curl -s -X POST "$BASE_URL/admin/order/approve" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -d "{\"orderNo\":\"$ORDER_NO\",\"status\":2,\"adminRemark\":\"测试审批通过\"}")

echo "审批响应:"
echo "$APPROVE_RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$APPROVE_RESPONSE"
echo ""

# 5. 等待2秒，确保事务提交
echo "步骤5: 等待事务提交..."
sleep 2
echo ""

# 6. 再次查询订单详情（审批后）
echo "步骤6: 查询订单详情（审批后）..."
DETAIL_RESPONSE_AFTER=$(curl -s "$BASE_URL/admin/order/list?orderNo=$ORDER_NO" \
  -H "Authorization: Bearer $ADMIN_TOKEN")

echo "订单详情（审批后）:"
echo "$DETAIL_RESPONSE_AFTER" | python3 -m json.tool 2>/dev/null || echo "$DETAIL_RESPONSE_AFTER"

AFTER_STATUS=$(echo $DETAIL_RESPONSE_AFTER | grep -o '"status":[0-9]*' | head -1 | cut -d':' -f2)
echo "审批后状态: $AFTER_STATUS"
echo ""

# 7. 验证状态是否改变
echo "================================"
echo "验证结果:"
echo "================================"
echo "审批前状态: $BEFORE_STATUS"
echo "审批后状态: $AFTER_STATUS"

if [ "$BEFORE_STATUS" != "$AFTER_STATUS" ]; then
    echo "✅ 状态已改变！"
else
    echo "❌ 状态未改变！"
    echo ""
    echo "可能的原因："
    echo "1. 事务回滚了"
    echo "2. 数据库更新失败"
    echo "3. 查询到了缓存数据"
    echo ""
    echo "建议检查："
    echo "1. 查看后端日志，搜索 '[FundService.approve]'"
    echo "2. 直接查询数据库验证："
    echo "   SELECT id, order_no, status, approve_admin_id, approve_time FROM order_fund WHERE order_no='$ORDER_NO';"
fi

echo ""
echo "================================"
echo "测试完成"
echo "================================"
