#!/bin/bash

# ====================================
# 项目创建功能测试脚本
# 功能：测试创建项目时集成流水分析平台
# 作者：Claude Code
# 日期：2026-03-04
# ====================================

# 配置
BASE_URL="http://localhost:8080"
USERNAME="admin"
PASSWORD="admin123"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        log_error "$1 未安装，请先安装 $1"
        exit 1
    fi
}

# 检查后端服务是否运行
check_backend_service() {
    log_info "检查后端服务状态..."
    if curl -s --connect-timeout 5 "$BASE_URL/actuator/health" > /dev/null 2>&1; then
        log_info "✓ 后端服务运行正常"
        return 0
    else
        log_error "✗ 后端服务未运行，请先启动后端服务"
        log_info "启动命令: cd ruoyi-admin && mvn spring-boot:run"
        return 1
    fi
}

# 获取访问令牌
get_token() {
    log_info "获取访问令牌..."
    TOKEN_RESPONSE=$(curl -s -X POST "$BASE_URL/login/test?username=$USERNAME&password=$PASSWORD")

    # 检查响应是否为空
    if [ -z "$TOKEN_RESPONSE" ]; then
        log_error "获取令牌失败：响应为空"
        return 1
    fi

    # 提取 token（假设返回格式为 {"code":200,"msg":"操作成功","data":"token"}）
    TOKEN=$(echo "$TOKEN_RESPONSE" | grep -o '"token":"[^"]*"' | sed 's/"token":"//;s/"//')

    if [ -z "$TOKEN" ]; then
        log_error "获取令牌失败：无法从响应中提取 token"
        log_info "响应内容: $TOKEN_RESPONSE"
        return 1
    fi

    log_info "✓ 成功获取令牌"
    return 0
}

# 测试场景1：创建项目成功
test_create_project_success() {
    log_info "=========================================="
    log_info "测试场景1：创建项目成功"
    log_info "=========================================="

    # 准备测试数据
    PROJECT_NAME="集成测试项目_$(date +%Y%m%d_%H%M%S)"
    REQUEST_DATA=$(cat <<EOF
{
  "projectName": "$PROJECT_NAME",
  "description": "测试集成流水分析平台",
  "configType": "default"
}
EOF
)

    log_info "请求数据: $REQUEST_DATA"

    # 发送请求
    RESPONSE=$(curl -s -X POST "$BASE_URL/ccdi/project" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d "$REQUEST_DATA")

    log_info "响应内容: $RESPONSE"

    # 验证响应
    CODE=$(echo "$RESPONSE" | grep -o '"code":[0-9]*' | sed 's/"code"://')
    MSG=$(echo "$RESPONSE" | grep -o '"msg":"[^"]*"' | sed 's/"msg":"//;s/"//')

    if [ "$CODE" == "200" ]; then
        log_info "✓ 项目创建成功"

        # 验证 lsfxProjectId 是否存在
        LSFX_PROJECT_ID=$(echo "$RESPONSE" | grep -o '"lsfxProjectId":[0-9]*' | sed 's/"lsfxProjectId"://')
        if [ -n "$LSFX_PROJECT_ID" ]; then
            log_info "✓ 流水分析平台项目ID: $LSFX_PROJECT_ID"
        else
            log_error "✗ 流水分析平台项目ID为空"
            return 1
        fi

        # 验证数据库
        log_info "验证数据库..."
        DB_CHECK=$(mysql -h 116.62.17.81 -u root -pKfcx@1234 ccdi -N -B -e \
            "SELECT COUNT(*) FROM ccdi_project WHERE project_name='$PROJECT_NAME' AND lsfx_project_id IS NOT NULL;" 2>/dev/null)

        if [ "$DB_CHECK" == "1" ]; then
            log_info "✓ 数据库验证通过：lsfx_project_id 已正确保存"
        else
            log_error "✗ 数据库验证失败：lsfx_project_id 未保存"
            return 1
        fi

        return 0
    else
        log_error "✗ 项目创建失败: $MSG"
        return 1
    fi
}

# 测试场景2：创建项目失败（项目名称为空）
test_create_project_empty_name() {
    log_info "=========================================="
    log_info "测试场景2：创建项目失败（项目名称为空）"
    log_info "=========================================="

    REQUEST_DATA=$(cat <<EOF
{
  "projectName": "",
  "description": "测试异常场景",
  "configType": "default"
}
EOF
)

    log_info "请求数据: $REQUEST_DATA"

    RESPONSE=$(curl -s -X POST "$BASE_URL/ccdi/project" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d "$REQUEST_DATA")

    log_info "响应内容: $RESPONSE"

    CODE=$(echo "$RESPONSE" | grep -o '"code":[0-9]*' | sed 's/"code"://')

    if [ "$CODE" != "200" ]; then
        log_info "✓ 正确拒绝了空项目名称"
        return 0
    else
        log_error "✗ 未正确验证项目名称"
        return 1
    fi
}

# 测试场景3：流水分析平台不可用
test_lsfx_unavailable() {
    log_info "=========================================="
    log_info "测试场景3：流水分析平台不可用"
    log_info "=========================================="
    log_warning "注意：此测试需要停止 Mock Server"
    log_info "请手动停止 lsfx-mock-server 并重新运行此测试"
    log_info "提示：在 lsfx-mock-server 目录按 Ctrl+C 停止"

    # 询问用户是否继续
    read -p "是否已停止 Mock Server？(y/n): " confirm
    if [ "$confirm" != "y" ]; then
        log_info "跳过此测试"
        return 0
    fi

    REQUEST_DATA=$(cat <<EOF
{
  "projectName": "异常测试项目_$(date +%Y%m%d_%H%M%S)",
  "description": "测试流水分析平台不可用",
  "configType": "default"
}
EOF
)

    log_info "请求数据: $REQUEST_DATA"

    RESPONSE=$(curl -s -X POST "$BASE_URL/ccdi/project" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d "$REQUEST_DATA")

    log_info "响应内容: $RESPONSE"

    CODE=$(echo "$RESPONSE" | grep -o '"code":[0-9]*' | sed 's/"code"://')
    MSG=$(echo "$RESPONSE" | grep -o '"msg":"[^"]*"' | sed 's/"msg":"//;s/"//')

    if [ "$CODE" == "500" ]; then
        log_info "✓ 正确处理了流水分析平台不可用的情况"
        log_info "错误信息: $MSG"

        # 验证数据库没有脏数据
        PROJECT_NAME=$(echo "$REQUEST_DATA" | grep -o '"projectName":"[^"]*"' | sed 's/"projectName":"//;s/"//')
        DB_CHECK=$(mysql -h 116.62.17.81 -u root -pKfcx@1234 ccdi -N -B -e \
            "SELECT COUNT(*) FROM ccdi_project WHERE project_name='$PROJECT_NAME';" 2>/dev/null)

        if [ "$DB_CHECK" == "0" ]; then
            log_info "✓ 事务已回滚，数据库无脏数据"
        else
            log_error "✗ 事务未回滚，存在脏数据"
            return 1
        fi

        return 0
    else
        log_error "✗ 未正确处理异常情况"
        return 1
    fi
}

# 测试场景4：查询项目列表
test_query_project_list() {
    log_info "=========================================="
    log_info "测试场景4：查询项目列表"
    log_info "=========================================="

    RESPONSE=$(curl -s -X GET "$BASE_URL/ccdi/project/list?pageNum=1&pageSize=10" \
        -H "Authorization: Bearer $TOKEN")

    log_info "响应内容（前500字符）: ${RESPONSE:0:500}"

    CODE=$(echo "$RESPONSE" | grep -o '"code":[0-9]*' | sed 's/"code"://')

    if [ "$CODE" == "200" ]; then
        log_info "✓ 查询项目列表成功"

        # 检查是否包含 lsfxProjectId
        if echo "$RESPONSE" | grep -q "lsfxProjectId"; then
            log_info "✓ 项目列表包含 lsfxProjectId 字段"
        else
            log_warning "! 项目列表可能缺少 lsfxProjectId 字段"
        fi

        return 0
    else
        log_error "✗ 查询项目列表失败"
        return 1
    fi
}

# 主测试流程
main() {
    log_info "=========================================="
    log_info "开始执行项目创建功能测试"
    log_info "=========================================="

    # 检查依赖
    check_command curl
    check_command mysql

    # 检查后端服务
    check_backend_service || exit 1

    # 获取令牌
    get_token || exit 1

    # 执行测试
    PASS_COUNT=0
    FAIL_COUNT=0

    if test_create_project_success; then
        ((PASS_COUNT++))
    else
        ((FAIL_COUNT++))
    fi

    if test_create_project_empty_name; then
        ((PASS_COUNT++))
    else
        ((FAIL_COUNT++))
    fi

    if test_query_project_list; then
        ((PASS_COUNT++))
    else
        ((FAIL_COUNT++))
    fi

    # 可选测试
    log_info "=========================================="
    log_info "可选测试：流水分析平台不可用场景"
    log_info "=========================================="
    read -p "是否执行流水分析平台不可用测试？(y/n): " run_unavailable_test
    if [ "$run_unavailable_test" == "y" ]; then
        if test_lsfx_unavailable; then
            ((PASS_COUNT++))
        else
            ((FAIL_COUNT++))
        fi
    fi

    # 输出测试结果
    log_info "=========================================="
    log_info "测试结果汇总"
    log_info "=========================================="
    log_info "通过: $PASS_COUNT"
    log_info "失败: $FAIL_COUNT"
    log_info "总计: $((PASS_COUNT + FAIL_COUNT))"

    if [ $FAIL_COUNT -eq 0 ]; then
        log_info "✓ 所有测试通过！"
        exit 0
    else
        log_error "✗ 存在失败的测试"
        exit 1
    fi
}

# 执行主函数
main
