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

# 配置
$BaseUrl = "http://localhost:8080"
$Username = "admin"
$Password = "admin123"
$Token = $null

# 计数器
$PassCount = 0
$FailCount = 0

# 日志函数
function Write-LogInfo {
    param([string]$Message)
    Write-Host "[INFO] " -ForegroundColor Green -NoNewline
    Write-Host $Message
}

function Write-LogError {
    param([string]$Message)
    Write-Host "[ERROR] " -ForegroundColor Red -NoNewline
    Write-Host $Message
}

function Write-LogWarning {
    param([string]$Message)
    Write-Host "[WARNING] " -ForegroundColor Yellow -NoNewline
    Write-Host $Message
}

# 检查后端服务
function Test-BackendService {
    Write-LogInfo "检查后端服务状态..."
    try {
        $response = Invoke-WebRequest -Uri "$BaseUrl/actuator/health" -TimeoutSec 5 -ErrorAction Stop
        Write-LogInfo "✓ 后端服务运行正常"
        return $true
    } catch {
        Write-LogError "✗ 后端服务未运行，请先启动后端服务"
        Write-LogInfo "启动命令: cd ruoyi-admin; mvn spring-boot:run"
        return $false
    }
}

# 获取访问令牌
function Get-AccessToken {
    Write-LogInfo "获取访问令牌..."
    try {
        $response = Invoke-RestMethod -Uri "$BaseUrl/login/test?username=$Username&password=$Password" -Method POST

        if ($response.code -eq 200 -and $response.token) {
            $script:Token = $response.token
            Write-LogInfo "✓ 成功获取令牌"
            return $true
        } else {
            Write-LogError "获取令牌失败：响应格式不正确"
            Write-LogInfo "响应内容: $($response | ConvertTo-Json)"
            return $false
        }
    } catch {
        Write-LogError "获取令牌失败: $($_.Exception.Message)"
        return $false
    }
}

# 测试场景1：创建项目成功
function Test-CreateProjectSuccess {
    Write-LogInfo "=========================================="
    Write-LogInfo "测试场景1：创建项目成功"
    Write-LogInfo "=========================================="

    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    $projectName = "集成测试项目_$timestamp"

    $requestData = @{
        projectName = $projectName
        description = "测试集成流水分析平台"
        configType = "default"
    } | ConvertTo-Json

    Write-LogInfo "请求数据: $requestData"

    try {
        $headers = @{
            "Content-Type" = "application/json"
            "Authorization" = "Bearer $Token"
        }

        $response = Invoke-RestMethod -Uri "$BaseUrl/ccdi/project" -Method POST -Headers $headers -Body $requestData

        Write-LogInfo "响应内容: $($response | ConvertTo-Json -Depth 5)"

        if ($response.code -eq 200) {
            Write-LogInfo "✓ 项目创建成功"

            if ($response.data.lsfxProjectId) {
                Write-LogInfo "✓ 流水分析平台项目ID: $($response.data.lsfxProjectId)"
                $script:PassCount++
                return $true
            } else {
                Write-LogError "✗ 流水分析平台项目ID为空"
                $script:FailCount++
                return $false
            }
        } else {
            Write-LogError "✗ 项目创建失败: $($response.msg)"
            $script:FailCount++
            return $false
        }
    } catch {
        Write-LogError "请求失败: $($_.Exception.Message)"
        $script:FailCount++
        return $false
    }
}

# 测试场景2：创建项目失败（项目名称为空）
function Test-CreateProjectEmptyName {
    Write-LogInfo "=========================================="
    Write-LogInfo "测试场景2：创建项目失败（项目名称为空）"
    Write-LogInfo "=========================================="

    $requestData = @{
        projectName = ""
        description = "测试异常场景"
        configType = "default"
    } | ConvertTo-Json

    Write-LogInfo "请求数据: $requestData"

    try {
        $headers = @{
            "Content-Type" = "application/json"
            "Authorization" = "Bearer $Token"
        }

        $response = Invoke-RestMethod -Uri "$BaseUrl/ccdi/project" -Method POST -Headers $headers -Body $requestData

        if ($response.code -ne 200) {
            Write-LogInfo "✓ 正确拒绝了空项目名称"
            $script:PassCount++
            return $true
        } else {
            Write-LogError "✗ 未正确验证项目名称"
            $script:FailCount++
            return $false
        }
    } catch {
        Write-LogInfo "✓ 正确拒绝了空项目名称（请求失败）"
        $script:PassCount++
        return $true
    }
}

# 测试场景3：查询项目列表
function Test-QueryProjectList {
    Write-LogInfo "=========================================="
    Write-LogInfo "测试场景3：查询项目列表"
    Write-LogInfo "=========================================="

    try {
        $headers = @{
            "Authorization" = "Bearer $Token"
        }

        $response = Invoke-RestMethod -Uri "$BaseUrl/ccdi/project/list?pageNum=1&pageSize=10" -Method GET -Headers $headers

        Write-LogInfo "响应内容（前500字符）: $($response | ConvertTo-Json -Depth 3 | Select-Object -First 500)"

        if ($response.code -eq 200) {
            Write-LogInfo "✓ 查询项目列表成功"

            if ($response.rows -and $response.rows[0].lsfxProjectId) {
                Write-LogInfo "✓ 项目列表包含 lsfxProjectId 字段"
            } else {
                Write-LogWarning "! 项目列表可能缺少 lsfxProjectId 字段"
            }
            $script:PassCount++
            return $true
        } else {
            Write-LogError "✗ 查询项目列表失败"
            $script:FailCount++
            return $false
        }
    } catch {
        Write-LogError "请求失败: $($_.Exception.Message)"
        $script:FailCount++
        return $false
    }
}

# 测试场景4：流水分析平台不可用
function Test-LsfxUnavailable {
    Write-LogInfo "=========================================="
    Write-LogInfo "测试场景4：流水分析平台不可用"
    Write-LogInfo "=========================================="
    Write-LogWarning "注意：此测试需要停止 Mock Server"
    Write-LogInfo "请手动停止 lsfx-mock-server 并重新运行此测试"

    $confirm = Read-Host "是否已停止 Mock Server？(y/n)"
    if ($confirm -ne "y") {
        Write-LogInfo "跳过此测试"
        return
    }

    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    $projectName = "异常测试项目_$timestamp"

    $requestData = @{
        projectName = $projectName
        description = "测试流水分析平台不可用"
        configType = "default"
    } | ConvertTo-Json

    Write-LogInfo "请求数据: $requestData"

    try {
        $headers = @{
            "Content-Type" = "application/json"
            "Authorization" = "Bearer $Token"
        }

        $response = Invoke-RestMethod -Uri "$BaseUrl/ccdi/project" -Method POST -Headers $headers -Body $requestData

        if ($response.code -eq 500) {
            Write-LogInfo "✓ 正确处理了流水分析平台不可用的情况"
            Write-LogInfo "错误信息: $($response.msg)"

            # 注意：PowerShell版本无法直接验证数据库，需要MySQL工具
            Write-LogWarning "请手动验证数据库无脏数据"

            $script:PassCount++
            return $true
        } else {
            Write-LogError "✗ 未正确处理异常情况"
            $script:FailCount++
            return $false
        }
    } catch {
        Write-LogError "请求失败: $($_.Exception.Message)"
        $script:FailCount++
        return $false
    }
}

# 主函数
function Main {
    Write-LogInfo "=========================================="
    Write-LogInfo "开始执行项目创建功能测试"
    Write-LogInfo "=========================================="

    # 检查后端服务
    if (-not (Test-BackendService)) {
        exit 1
    }

    # 获取令牌
    if (-not (Get-AccessToken)) {
        exit 1
    }

    # 执行测试
    Test-CreateProjectSuccess
    Test-CreateProjectEmptyName
    Test-QueryProjectList

    # 可选测试
    Write-LogInfo "=========================================="
    Write-LogInfo "可选测试：流水分析平台不可用场景"
    Write-LogInfo "=========================================="
    $runUnavailableTest = Read-Host "是否执行流水分析平台不可用测试？(y/n)"
    if ($runUnavailableTest -eq "y") {
        Test-LsfxUnavailable
    }

    # 输出测试结果
    Write-LogInfo "=========================================="
    Write-LogInfo "测试结果汇总"
    Write-LogInfo "=========================================="
    Write-LogInfo "通过: $PassCount"
    Write-LogError "失败: $FailCount"
    Write-LogInfo "总计: $($PassCount + $FailCount)"

    if ($FailCount -eq 0) {
        Write-LogInfo "✓ 所有测试通过！"
        exit 0
    } else {
        Write-LogError "✗ 存在失败的测试"
        exit 1
    }
}

# 执行主函数
Main
