var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var path = require('path');
var del = require('del');

// 先设置环境变量，确保任务定义时可以正确访问
var env = process.env.npm_config_qa ? 'qa' : process.env.npm_config_uat ? 'uat' : 'prod';

var distPath = path.resolve('./dist');
var version = ''; // 版本号
var versionPath = ''; // 版本号路径

// 创建版本号(年月日时分)
(function () {
    var d = new Date();
    var yy = d.getFullYear().toString().slice(2);
    var MM = (d.getMonth() + 1).toString().padStart(2, '0');
    var DD = d.getDate().toString().padStart(2, '0');
    var h = d.getHours().toString().padStart(2, '0');
    var mm = d.getMinutes().toString().padStart(2, '0');
    version = yy + MM + DD + h + mm;
    versionPath = path.join(distPath, version); // 使用path.join更安全
})();

// 编译
gulp.task('build', $.shell.task(['node build/build.js']));

// 创建版本号目录
gulp.task('create:versionCatalog', gulp.series('build', function () {
    return gulp.src(path.join(distPath, 'static', '**', '*'))
        .pipe(gulp.dest(path.join(versionPath, 'static')));
}));

// 替换cdnUrl占位变量
gulp.task('replace:cdnUrl', gulp.series('create:versionCatalog', function () {
    const assetsPublicPath = require('./config').build.assetsPublicPath;
    return gulp.src(path.join(versionPath, 'static', 'js', 'manifest.js'))
        .pipe($.replace(new RegExp(`"${assetsPublicPath}"`, 'g'), 'window.SITE_CONFIG.cdnUrl + "/"'))
        .pipe(gulp.dest(path.join(versionPath, 'static', 'js')));
}));

// 替换version配置变量
gulp.task('replace:version', gulp.series('create:versionCatalog', function () {
    return gulp.src(path.join(versionPath, 'static', 'config', `index-${env}.js`))
        .pipe($.replace(/window.SITE_CONFIG\['version'\] = '.*'/g, `window.SITE_CONFIG['version'] = '${version}'`))
        .pipe(gulp.dest(path.join(versionPath, 'static', 'config')));
}));

// 合并配置文件
gulp.task('concat:config', gulp.series('replace:version', function () {
    return gulp.src([
            path.join(versionPath, 'static', 'config', `index-${env}.js`),
            path.join(versionPath, 'static', 'config', 'init.js')
        ])
        .pipe($.concat('index.js'))
        .pipe(gulp.dest(path.join(distPath, 'config')));
}));

// 清空文件历史
gulp.task('clean', function () {
    console.log('--clean--');
    return del([distPath]);
});

// 构建结束清理
gulp.task('build-end', function () {
    console.log('--builed-end--');
    return del([
        path.join(distPath, 'static'),
        path.join(versionPath, 'static', 'config')
    ]);
});

// 主任务 - 按正确顺序执行
gulp.task('default', gulp.series(
    'clean',
    'build',
    'create:versionCatalog',
    gulp.parallel('replace:cdnUrl', 'replace:version'),
    'concat:config',
    'build-end',
    function (done) {
        console.log(`构建完成，环境: ${env}，版本号: ${version}`);
        done();
    }
));
