pipeline {
    agent any
    parameters {
        choice(name: 'ENV', choices: ['prod'], description: '部署环境')
    }
    environment {
        // 阿里云 Docker 仓库的地址和用户名
        DOCKER_REGISTRY = "registry.cn-shanghai.aliyuncs.com"
        DOCKER_NAMESPACE = "advich-group"
        DOCKER_REPO = "weichi-crm-web"
        DOCKER_IMAGE = "${DOCKER_REGISTRY}/${DOCKER_NAMESPACE}/${DOCKER_REPO}:latest"
    }
    stages {
        stage('拉取Git代码') {
            steps {
                checkout scmGit(branches: [[name: '${branch}']], extensions: [], userRemoteConfigs: [[credentialsId: 'fb3553e7-6ea6-4f34-92a0-6ba34a71c5b5', url: 'https://git.dev.advichcloud.com/wangfan/weichi-crm-web.git']])
            }
        }
        stage('编译打包代码') {
            steps {
                nodejs('node8') {
                    bat "npm install"
                    bat "npm run build"
                }
            }
        }
        stage('Build and Push Docker Image') {
            steps {
                script {
                    // 使用刚才创建的凭证
                    withCredentials([usernamePassword(credentialsId: '41a5dc65-0283-4d56-ace5-36bc08350b08', usernameVariable: 'REGISTRY_USERNAME', passwordVariable: 'REGISTRY_PASSWORD')]) {
                        // 构建Docker镜像
                        bat "docker build -t ${DOCKER_IMAGE} ."
                        // 登录阿里云Docker Registry
                        bat "docker login -u ${REGISTRY_USERNAME} -p ${REGISTRY_PASSWORD} ${DOCKER_REGISTRY}"
                        // 推送镜像到阿里云Docker Registry
                        bat "docker push ${DOCKER_IMAGE}"
                    }
                }
            }
        }
        stage('Deploy to Server') {
            when {
                expression { return params.ENV == 'prod' }
            }
            steps {
                sshPublisher(publishers: [sshPublisherDesc(configName:'CRM（阿里云）', transfers: [sshTransfer(cleanRemote: false, excludes: '',
                execCommand: '''
                docker login -u wangfan@1934160439855919 -p Initial0 registry.cn-shanghai.aliyuncs.com
                docker pull registry.cn-shanghai.aliyuncs.com/advich-group/weichi-crm-web:latest
                docker rm -f weichi-crm-web || true
                docker run -d --name weichi-crm-web -p 80:80 registry.cn-shanghai.aliyuncs.com/advich-group/weichi-crm-web:latest''',execTimeout: 120000, flatten: false, makeEmptyDirs: false,
                noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '',
                remoteDirectorySDF: false, removePrefix: '', sourceFiles: '')],
                usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose:
                false)])
            }
        }
    }
}

