pipeline {
    agent any
    
    options {
        // 保留最近10次构建
        buildDiscarder(logRotator(numToKeepStr: '10'))
        // 超时时间60分钟
        timeout(time: 60, unit: 'MINUTES')
    }
    
    environment {
        // Python路径
        PYTHONPATH = "${WORKSPACE}"
        // Allure结果目录
        ALLURE_RESULTS = "${WORKSPACE}/zhyy/test_case/reports/allure-results"
        // Allure报告目录
        ALLURE_REPORT = "${WORKSPACE}/zhyy/test_case/reports/allure-report"
    }
    
    stages {
        stage('Checkout') {
            steps {
                echo '检出代码...'
                checkout scm
            }
        }
        
        stage('环境准备') {
            steps {
                echo '准备测试环境...'
                script {
                    // 确保Python环境
                    sh '''
                        python --version
                        pip --version
                    '''
                }
            }
        }
        
        stage('运行测试') {
            steps {
                echo '执行测试用例...'
                script {
                    // 根据参数选择运行方式
                    def runType = params.RUN_TYPE ?: 'all'
                    def testCommand = ''
                    
                    switch(runType) {
                        case 'all':
                            testCommand = 'python zhyy/test_case/run_tests.py --all --no-report'
                            break
                        case 'feature':
                            def feature = params.FEATURE_NAME ?: ''
                            testCommand = "python zhyy/test_case/run_tests.py --feature \"${feature}\" --no-report"
                            break
                        case 'story':
                            def story = params.STORY_NAME ?: ''
                            testCommand = "python zhyy/test_case/run_tests.py --story \"${story}\" --no-report"
                            break
                        case 'dir':
                            def dir = params.DIR_PATH ?: ''
                            testCommand = "python zhyy/test_case/run_tests.py --dir \"${dir}\" --no-report"
                            break
                        case 'file':
                            def file = params.FILE_PATH ?: ''
                            testCommand = "python zhyy/test_case/run_tests.py --file \"${file}\" --no-report"
                            break
                        case 'keyword':
                            def keyword = params.KEYWORD ?: ''
                            testCommand = "python zhyy/test_case/run_tests.py --keyword \"${keyword}\" --no-report"
                            break
                        case 'marker':
                            def marker = params.MARKER ?: ''
                            testCommand = "python zhyy/test_case/run_tests.py --marker \"${marker}\" --no-report"
                            break
                        default:
                            testCommand = 'python zhyy/test_case/run_tests.py --all --no-report'
                    }
                    
                    sh """
                        cd ${WORKSPACE}
                        ${testCommand}
                    """
                }
            }
            post {
                always {
                    // 无论成功失败都收集测试结果
                    echo '收集测试结果...'
                }
            }
        }
        
        stage('生成Allure报告') {
            steps {
                echo '生成Allure报告...'
                script {
                    sh """
                        cd ${WORKSPACE}
                        allure generate ${ALLURE_RESULTS} -o ${ALLURE_REPORT} --clean || echo "Allure报告生成失败，但继续执行"
                    """
                }
            }
        }
    }
    
    post {
        always {
            // 发布Allure报告
            allure([
                includeProperties: false,
                jdk: '',
                properties: [],
                reportBuildPolicy: 'ALWAYS',
                results: [[path: 'zhyy/test_case/reports/allure-results']]
            ])
            
            // 清理工作空间（可选）
            // cleanWs()
        }
        success {
            echo '✓ 测试执行成功'
            // 可以在这里添加成功通知，如发送邮件、钉钉等
        }
        failure {
            echo '✗ 测试执行失败'
            // 可以在这里添加失败通知
        }
        unstable {
            echo '⚠ 测试执行不稳定'
        }
    }
}

// 参数化构建
properties([
    parameters([
        choice(
            name: 'RUN_TYPE',
            choices: ['all', 'feature', 'story', 'dir', 'file', 'keyword', 'marker'],
            description: '选择运行方式'
        ),
        string(
            name: 'FEATURE_NAME',
            defaultValue: '',
            description: 'Feature标签名称（当RUN_TYPE=feature时使用）'
        ),
        string(
            name: 'STORY_NAME',
            defaultValue: '',
            description: 'Story标签名称（当RUN_TYPE=story时使用）'
        ),
        string(
            name: 'DIR_PATH',
            defaultValue: '接口/SZPurchase',
            description: '测试目录路径（当RUN_TYPE=dir时使用，相对于TestCase目录）'
        ),
        string(
            name: 'FILE_PATH',
            defaultValue: '接口/SZPurchase/PurchaseOrderManage.py',
            description: '测试文件路径（当RUN_TYPE=file时使用，相对于TestCase目录）'
        ),
        string(
            name: 'KEYWORD',
            defaultValue: 'purchase',
            description: '关键字（当RUN_TYPE=keyword时使用）'
        ),
        string(
            name: 'MARKER',
            defaultValue: 'smoke',
            description: 'Pytest标记（当RUN_TYPE=marker时使用）'
        )
    ])
])
