#!/bin/bash

# 一键测试脚本 - 自动编译、启动、测试

PROJECT_DIR=~/Desktop/projects/monisuo
JAR_NAME="monisuo-1.0.jar"
PID_FILE="/tmp/monisuo_test.pid"
LOG_FILE="/tmp/monisuo_test.log"

echo "=========================================="
echo "审批订单一键测试"
echo "=========================================="
echo ""

# 进入项目目录
cd ${PROJECT_DIR}

# 1. 编译项目
echo "步骤1: 编译项目..."
mvn clean package -DskipTests > /dev/null 2>&1

if [ ! -f "target/${JAR_NAME}" ]; then
    echo "❌ 编译失败"
    exit 1
fi
echo "✅ 编译成功"
echo ""

# 2. 停止旧进程
echo "步骤2: 停止旧进程..."
if [ -f "${PID_FILE}" ]; then
    OLD_PID=$(cat ${PID_FILE})
    if ps -p ${OLD_PID} > /dev/null 2>&1; then
        echo "停止进程 ${OLD_PID}..."
        kill -9 ${OLD_PID} 2>/dev/null
        sleep 2
    fi
    rm -f ${PID_FILE}
fi
echo "✅ 清理完成"
echo ""

# 3. 启动服务（后台运行，日志输出到文件）
echo "步骤3: 启动后端服务..."
echo "日志文件: ${LOG_FILE}"
nohup java -jar target/${JAR_NAME} > ${LOG_FILE} 2>&1 &
NEW_PID=$!
echo ${NEW_PID} > ${PID_FILE}
echo "进程ID: ${NEW_PID}"
echo ""

# 4. 等待服务启动
echo "步骤4: 等待服务启动..."
MAX_WAIT=30
WAIT_COUNT=0
while [ ${WAIT_COUNT} -lt ${MAX_WAIT} ]; do
    if curl -s http://localhost:5010/admin/login > /dev/null 2>&1; then
        echo "✅ 服务启动成功"
        break
    fi
    echo -n "."
    sleep 1
    WAIT_COUNT=$((WAIT_COUNT + 1))
done
echo ""

if [ ${WAIT_COUNT} -eq ${MAX_WAIT} ]; then
    echo "❌ 服务启动超时"
    echo "查看日志: tail -50 ${LOG_FILE}"
    exit 1
fi
echo ""

# 5. 运行测试
echo "步骤5: 运行审批测试..."
echo "=========================================="
bash ${PROJECT_DIR}/diagnose_approval.sh
echo "=========================================="
echo ""

# 6. 询问是否查看日志
echo "测试完成！"
echo ""
echo "📋 查看详细日志:"
echo "   tail -100 ${LOG_FILE}"
echo ""
echo "🔍 搜索审批相关日志:"
echo "   grep -A 50 '审批订单开始' ${LOG_FILE}"
echo ""
echo "🛑 停止服务:"
echo "   kill ${NEW_PID}"
echo ""
