#!/bin/bash

# 审批订单完整诊断脚本
# 检查所有可能的问题点

BASE_URL="http://localhost:5010"

echo "=========================================="
echo "审批订单完整诊断"
echo "=========================================="
echo ""

# 检查后端服务是否运行
echo "1. 检查后端服务..."
if curl -s --connect-timeout 2 "${BASE_URL}/actuator/health" > /dev/null 2>&1; then
    echo "✅ 后端服务正在运行"
else
    echo "⚠️  后端服务可能未运行或健康检查端点不可用"
    echo "   尝试连接: ${BASE_URL}"
fi
echo ""

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

if echo "${LOGIN_RESPONSE}" | grep -q '"token"'; then
    echo "✅ 登录成功"
    TOKEN=$(echo ${LOGIN_RESPONSE} | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
else
    echo "❌ 登录失败"
    echo "响应: ${LOGIN_RESPONSE}"
    exit 1
fi
echo ""

# 查询待审批订单
echo "3. 查询待审批订单..."
PENDING=$(curl -s -X GET "${BASE_URL}/admin/order/pending?pageNum=1&pageSize=10" \
  -H "Authorization: Bearer ${TOKEN}")

echo "响应预览: "
echo "${PENDING}" | python3 -m json.tool 2>/dev/null | head -30
echo ""

ORDER_COUNT=$(echo ${PENDING} | grep -o '"orderNo"' | wc -l | tr -d ' ')
echo "找到 ${ORDER_COUNT} 个待审批订单"
echo ""

if [ "$ORDER_COUNT" -eq 0 ]; then
    echo "⚠️  没有待审批订单，创建测试订单步骤："
    echo "   1. 用户登录小程序"
    echo "   2. 创建充值订单"
    echo "   3. 用户确认打款"
    echo "   4. 重新运行此脚本"
    exit 0
fi

# 选择第一个订单
ORDER_NO=$(echo ${PENDING} | grep -o '"orderNo":"[^"]*"' | head -1 | cut -d'"' -f4)
ORDER_TYPE=$(echo ${PENDING} | grep -A 10 "\"orderNo\":\"${ORDER_NO}\"" | grep -o '"type":[0-9]*' | head -1 | cut -d':' -f2)
ORDER_STATUS=$(echo ${PENDING} | grep -A 10 "\"orderNo\":\"${ORDER_NO}\"" | grep -o '"status":[0-9]*' | head -1 | cut -d':' -f2)
USER_ID=$(echo ${PENDING} | grep -A 10 "\"orderNo\":\"${ORDER_NO}\"" | grep -o '"userId":[0-9]*' | head -1 | cut -d':' -f2)
AMOUNT=$(echo ${PENDING} | grep -A 10 "\"orderNo\":\"${ORDER_NO}\"" | grep -o '"amount":[0-9.]*' | head -1 | cut -d':' -f2)

echo "选择测试订单:"
echo "  订单号: ${ORDER_NO}"
echo "  类型: ${ORDER_TYPE} (1=充值, 2=提现)"
echo "  当前状态: ${ORDER_STATUS}"
echo "  用户ID: ${USER_ID}"
echo "  金额: ${AMOUNT}"
echo ""

# 验证订单状态是否可审批
echo "4. 验证订单状态..."
if [ "$ORDER_TYPE" = "1" ]; then
    if [ "$ORDER_STATUS" = "2" ]; then
        echo "✅ 充值订单状态正确（待确认）"
    else
        echo "❌ 充值订单状态不正确（需要状态2，实际${ORDER_STATUS}）"
        exit 1
    fi
else
    if [ "$ORDER_STATUS" = "1" ]; then
        echo "✅ 提现订单状态正确（待审批）"
    else
        echo "❌ 提现订单状态不正确（需要状态1，实际${ORDER_STATUS}）"
        exit 1
    fi
fi
echo ""

# 查询用户资金账户（审批前）
echo "5. 查询用户资金账户（审批前）..."
USER_DETAIL=$(curl -s -X GET "${BASE_URL}/admin/user/detail?userId=${USER_ID}" \
  -H "Authorization: Bearer ${TOKEN}")

BALANCE_BEFORE=$(echo ${USER_DETAIL} | grep -o '"balance":[0-9.]*' | head -1 | cut -d':' -f2)
FROZEN_BEFORE=$(echo ${USER_DETAIL} | grep -o '"frozen":[0-9.]*' | head -1 | cut -d':' -f2)

echo "审批前资金账户:"
echo "  余额: ${BALANCE_BEFORE}"
echo "  冻结: ${FROZEN_BEFORE}"
echo ""

# 执行审批
echo "=========================================="
echo "6. 执行审批操作（通过）"
echo "=========================================="
echo "重要：请观察后端控制台日志输出！"
echo ""

APPROVE_RESPONSE=$(curl -s -X POST "${BASE_URL}/admin/order/approve" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${TOKEN}" \
  -d "{
    \"orderNo\": \"${ORDER_NO}\",
    \"status\": 2,
    \"adminRemark\": \"诊断测试审批\"
  }")

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

if echo "${APPROVE_RESPONSE}" | grep -q '"code":"0"'; then
    echo "✅ 审批接口返回成功"
else
    echo "❌ 审批接口返回失败"
    exit 1
fi
echo ""

# 等待并验证
echo "7. 等待2秒后验证结果..."
sleep 2
echo ""

# 查询订单状态（审批后）
echo "8. 查询订单状态（审批后）..."
ORDER_LIST=$(curl -s -X GET "${BASE_URL}/admin/order/list?pageNum=1&pageSize=10" \
  -H "Authorization: Bearer ${TOKEN}")

NEW_STATUS=$(echo ${ORDER_LIST} | grep -A 20 "\"orderNo\":\"${ORDER_NO}\"" | grep -o '"status":[0-9]*' | head -1 | cut -d':' -f2)

echo "订单新状态: ${NEW_STATUS}"
if [ "$ORDER_TYPE" = "1" ]; then
    EXPECTED_STATUS="3"
    STATUS_TEXT="已完成"
else
    EXPECTED_STATUS="2"
    STATUS_TEXT="已完成"
fi

if [ "$NEW_STATUS" = "$EXPECTED_STATUS" ]; then
    echo "✅✅✅ 订单状态更新成功！状态 = ${NEW_STATUS} (${STATUS_TEXT})"
else
    echo "❌ 订单状态更新失败！期望 ${EXPECTED_STATUS}，实际 ${NEW_STATUS}"
fi
echo ""

# 查询用户资金账户（审批后）
echo "9. 查询用户资金账户（审批后）..."
USER_DETAIL_AFTER=$(curl -s -X GET "${BASE_URL}/admin/user/detail?userId=${USER_ID}" \
  -H "Authorization: Bearer ${TOKEN}")

BALANCE_AFTER=$(echo ${USER_DETAIL_AFTER} | grep -o '"balance":[0-9.]*' | head -1 | cut -d':' -f2)
FROZEN_AFTER=$(echo ${USER_DETAIL_AFTER} | grep -o '"frozen":[0-9.]*' | head -1 | cut -d':' -f2)

echo "审批后资金账户:"
echo "  余额: ${BALANCE_AFTER}"
echo "  冻结: ${FROZEN_AFTER}"
echo ""

# 验证余额变化
if [ "$ORDER_TYPE" = "1" ]; then
    # 充值：余额应该增加
    echo "验证充值订单余额变化:"
    echo "  审批前余额: ${BALANCE_BEFORE}"
    echo "  审批后余额: ${BALANCE_AFTER}"
    echo "  充值金额: ${AMOUNT}"
    
    # 使用 awk 进行浮点数计算
    BALANCE_DIFF=$(awk "BEGIN {print ${BALANCE_AFTER} - ${BALANCE_BEFORE}}")
    echo "  余额变化: ${BALANCE_DIFF}"
    
    if [ "$(awk "BEGIN {print (${BALANCE_DIFF} == ${AMOUNT})}")" = "1" ]; then
        echo "✅✅✅ 余额增加正确！"
    else
        echo "⚠️  余额变化与充值金额不匹配"
    fi
else
    # 提现：冻结应该减少
    echo "验证提现订单冻结变化:"
    echo "  审批前冻结: ${FROZEN_BEFORE}"
    echo "  审批后冻结: ${FROZEN_AFTER}"
    echo "  提现金额: ${AMOUNT}"
    
    FROZEN_DIFF=$(awk "BEGIN {print ${FROZEN_BEFORE} - ${FROZEN_AFTER}}")
    echo "  冻结变化: ${FROZEN_DIFF}"
    
    if [ "$(awk "BEGIN {print (${FROZEN_DIFF} == ${AMOUNT})}")" = "1" ]; then
        echo "✅✅✅ 冻结减少正确！"
    else
        echo "⚠️  冻结变化与提现金额不匹配"
    fi
fi
echo ""

echo "=========================================="
echo "诊断完成"
echo "=========================================="
echo ""
echo "📋 检查清单:"
echo "  1. 后端控制台是否有详细日志输出？"
echo "  2. 订单状态是否正确更新？"
echo "  3. 用户资金账户是否正确变化？"
echo "  4. 是否有任何错误或异常？"
echo ""
echo "如果所有检查都通过，说明审批功能正常工作！"
echo "如果有任何失败，请查看后端控制台日志以获取详细信息。"
