pipeline {
    agent { label '构建机1' }

    environment {
        IMAGE_PREFIX = "im"
        IMAGE_TAG = "${BUILD_NUMBER}"

        DOCKER_BUILDKIT = "1"

        // 如果你有 Harbor，可以改成：
        // REGISTRY = "harbor.xxx.com/im"
        REGISTRY = "reg.nxsir.cn/im"
    }

    stages {
        stage('拉取代码') {
            steps {
                checkout scm
            }
        }

        stage('检测变更') {
            steps {
                script {
                    def diffCmd = '''
                        if git rev-parse HEAD~1 >/dev/null 2>&1; then
                            git diff --name-only HEAD~1 HEAD
                        else
                            git ls-files
                        fi
                    '''

                    env.CHANGED_FILES = sh(
                        script: diffCmd,
                        returnStdout: true
                    ).trim()

                    echo "变更文件："
                    echo env.CHANGED_FILES
                }
            }
        }

        stage('构建镜像') {
            steps {
                script {
                    def services = [
                        [
                            name: 'connector-service',
                            dockerfile: 'ConnectorService/Dockerfile',
                            image: 'connector-service',
                            paths: [
                                'ConnectorService/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Protocols/'
                            ]
                        ],
                        [
                            name: 'user-service',
                            dockerfile: 'User.WebApi/Dockerfile',
                            image: 'user-service',
                            paths: [
                                'User.WebApi/',
                                'User.Domain/',
                                'User.Infrastructure/',
                                'DomainCommons/',
                                'Infrastructure/',
                                'IM.ASPNETCore/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Jwt/',
                                'IM.Protocols/'
                            ]
                        ],
                        [
                            name: 'contact-service',
                            dockerfile: 'ContactService.WebApi/Dockerfile',
                            image: 'contact-service',
                            paths: [
                                'ContactService.WebApi/',
                                'ContactService.Domain/',
                                'ContactService.Infrastructure/',
                                'DomainCommons/',
                                'Infrastructure/',
                                'IM.ASPNETCore/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Jwt/',
                                'IM.Protocols/'
                            ]
                        ],
                        [
                            name: 'group-service',
                            dockerfile: 'GroupService.WebApi/Dockerfile',
                            image: 'group-service',
                            paths: [
                                'GroupService.WebApi/',
                                'GroupService.Domain/',
                                'GroupService.Infrastructure/',
                                'DomainCommons/',
                                'Infrastructure/',
                                'IM.ASPNETCore/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Jwt/',
                                'IM.Protocols/'
                            ]
                        ],
                        [
                            name: 'message-service',
                            dockerfile: 'MessageService.WebApi/Dockerfile',
                            image: 'message-service',
                            paths: [
                                'MessageService.WebApi/',
                                'MessageService.Domain/',
                                'MessageService.Infrastructure/',
                                'DomainCommons/',
                                'Infrastructure/',
                                'IM.ASPNETCore/',
                                'IM.Commons/',
                                'IM.InitCommon/',
                                'IM.Jwt/',
                                'IM.Protocols/'
                            ]
                        ]
                    ]

                    def changedFiles = env.CHANGED_FILES.split("\\n") as List

                    services.each { svc ->
                        def needBuild = changedFiles.any { file ->
                            svc.paths.any { path ->
                                file.startsWith(path)
                            }
                        }

                        if (needBuild) {
                            def imageName = "${IMAGE_PREFIX}-${svc.image}:${IMAGE_TAG}"
                            def latestName = "${IMAGE_PREFIX}-${svc.image}:latest"

                            echo "开始构建镜像：${imageName}"

                            sh """
                                docker build \
                                  -t ${imageName} \
                                  -t ${latestName} \
                                  -f ${svc.dockerfile} .
                            """

                            if (env.REGISTRY?.trim()) {
                                sh """
                                    docker tag ${imageName} ${REGISTRY}/${svc.image}:${IMAGE_TAG}
                                    docker tag ${latestName} ${REGISTRY}/${svc.image}:latest

                                    docker push ${REGISTRY}/${svc.image}:${IMAGE_TAG}
                                    docker push ${REGISTRY}/${svc.image}:latest
                                """
                            }
                        } else {
                            echo "跳过构建：${svc.name}，没有相关代码变更"
                        }
                    }
                }
            }
        }
    }

    post {
        success {
            echo "流水线执行成功"
        }

        failure {
            echo "流水线执行失败"
        }
    }
}