pipeline {
    agent any
    tools{
        nodejs 'NodeJS20'
    }
    stages {
        stage('清理工作空间') { 
            steps { deleteDir() }
        }
        stage('拉取代码') {
            steps {
                git url:'http://118.25.129.153:3000/zhihui/suanfa.git', branch:'main'
            }
        }
        stage('设置NPM镜像'){
            steps{
                sh '''
                    npm config set registry https://mirrors.cloud.tencent.com/npm/
                    echo "当前 npm 镜像源："
                    npm config get registry
                '''
            }
        }
        stage('安装依赖'){
            steps{
                sh 'npm install'
            }
        }
        stage('执行依赖'){
            steps{
                sh 'npm run build'
            }
        }
        stage('保存成果'){
            steps{
                archiveArtifacts artifacts: 'dist/**/*', allowEmptyArchive: true
                echo '📦 构建产物已保存'
            } 
        }
        stage('部署到 Web 服务目录') {
            steps {
                echo '🚀 开始部署前端文件...'  
                script {
                    // 确保目标目录存在
                    sh 'mkdir -p /app/suanfa/www'
                    // 清空旧文件
                    sh 'rm -rf /app/suanfa/www/*' 
                    // 复制新构建的 dist 文件到挂载目录
                    sh 'cp -r dist/* /app/suanfa/www/'
                    
                    echo '✅ 前端文件部署到 Web 服务目录完成！'
                    
                    // 可选：列出部署的文件以便验证
                    sh 'ls -la /app/suanfa/www/ | head -10'
                } 
            }
        }
    }
    post{
        success{
            echo '🎉 构建成功完成！'
        }
        failure{
            echo '❌ 构建失败，请检查详细日志！'
        }
    }
}
