/**
 * 镜像推送工具类
 * 遵循阿里开发手册、大厂CI/CD标准
 * 
 * @param config 推送配置
 *   - services: 服务列表
 *   - imageRegistry: 镜像仓库地址
 *   - environment: 环境标识
 *   - version: 版本号
 *   - registryHost: 仓库主机
 *   - credentialsId: 凭据ID
 */
def call(Map config = [:]) {
    // 默认配置
    def services = config.services ?: ['api-gateway', 'auth-service', 'user-service',
                                      'map-service', 'order-service', 'merchant-service',
                                      'platform-service', 'product-service', 'rider-service',
                                      'upload-service', 'marketing-service']
    def imageRegistry = config.imageRegistry ?: env.IMAGE_REGISTRY
    def environment = config.environment ?: env.ENVIRONMENT
    def version = config.version ?: env.VERSION
    def registryHost = config.registryHost ?: env.REGISTRY_HOST
    def credentialsId = config.credentialsId ?: 'registry-cred'
    
    def startTime = System.currentTimeMillis()
    echo "📤 推送镜像到私有仓库"
    
    withCredentials([usernamePassword(
        credentialsId: credentialsId,
        usernameVariable: 'REGISTRY_USER',
        passwordVariable: 'REGISTRY_PWD'
    )]) {
        // 登录镜像仓库
        sh "ssh -i /var/lib/jenkins/.ssh/id_rsa -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@localhost \"printf '%s' \\\"\${REGISTRY_PWD}\\\" | podman login ${registryHost} -u \${REGISTRY_USER} --password-stdin\""
        
        // 并行推送镜像（每批4个，避免网络拥堵）
        def batchSize = 4
        def batches = services.collate(batchSize)
        def batchNum = 1
        
        batches.each { batch ->
            echo "📤 并行推送批次 ${batchNum}: ${batch.join(', ')}"
            parallel batch.collectEntries { service ->
                ["push-${service}": {
                    def imageTag = "${imageRegistry}/${service}-${environment}:${version}"
                    pushImage(imageTag)
                }]
            }
            batchNum++
        }
    }
    
    def duration = (System.currentTimeMillis() - startTime) / 1000
    echo "⏱️ 镜像推送总耗时: ${duration}秒"
    echo "✅ 所有镜像推送成功"
}

/**
 * 推送单个镜像（带重试机制）
 */
def pushImage(String imageTag) {
    def pushCommand = "ssh -i /var/lib/jenkins/.ssh/id_rsa -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@localhost \"podman push ${imageTag}\""
    
    // 重试机制（最多3次）
    def success = false
    for (int i = 0; i < 3; i++) {
        def exitCode = sh script: pushCommand, returnStatus: true
        if (exitCode == 0) {
            success = true
            break
        }
        echo "⚠️ ${imageTag} 推送失败，重试..."
        sleep 30
    }
    
    if (!success) {
        error "${imageTag} 推送失败"
    }
    echo "✅ ${imageTag} 推送成功"
}