const path = require('path');
const fs = require('fs');

// 获取当前命令行上下文路径
const currentDirectory = process.cwd();
console.log(`----------------------------`)
console.log(`正在处理编译打包前的准备...`)

//修改版本更新信息
console.log(`更新版本更新信息...`)
const versionPath = path.join(currentDirectory, '/public/version.json');
const versionContent = fs.readFileSync(versionPath, 'utf8');
//修改配置文件
const versionJson = JSON.parse(versionContent);
versionJson.value = dateFormat(new Date());         //版本号

//更新版本更新信息
fs.writeFileSync(versionPath, JSON.stringify(versionJson, null, 2));

console.log(`----------------------------`)

//删除上次打包相关的文件
console.log(`正在删除上次打包相关的文件...`)
const distZipPath = path.join(currentDirectory, '/zip/lar.zip');
if(fs.existsSync(distZipPath)) {
    fs.unlinkSync(distZipPath);
}

console.log(`----------------------------`)

// 获取配置文件
console.log(`获取当前的配置文件...`)
const indexJsonPath = path.join(currentDirectory, 'src/config/index.json');
const indexJsonContent = fs.readFileSync(indexJsonPath, 'utf8');

console.log(`----------------------------`)

// 检测上次打包异常中断的缓存文件是否存在
console.log(`检测上次打包异常中断的缓存文件是否存在...`)
const cacheFilePath = path.join(currentDirectory, 'scripts/cache.json');
if(!fs.existsSync(cacheFilePath)) {
    //创建缓存文件
    console.log(`创建配置缓存文件...`)
    const cacheJsonPath = path.join(currentDirectory, 'scripts/cache.json');
    fs.writeFileSync(cacheJsonPath, indexJsonContent, 'utf8');
}

console.log(`----------------------------`)

//修改配置文件
const indexJson = JSON.parse(indexJsonContent);
indexJson.version = dateFormat(new Date());         //版本号
indexJson.target = "http://127.0.0.1:8090";         //接口地址
indexJson.smsPhone = "";                            //短信接口手机号
indexJson.vite = {};                                //vite配置

//更新配置文件
console.log(`修改配置文件为生产环境的配置...`)
fs.writeFileSync(indexJsonPath, JSON.stringify(indexJson, null, 2));

//时间格式化
function dateFormat(date) {
    let format = 'yyyyMMddhhmmss';
    let o = {
        "M+": date.getMonth() + 1, //month
        "d+": date.getDate(), //day
        "h+": date.getHours(), //hour
        "m+": date.getMinutes(), //minute
        "s+": date.getSeconds(), //second
        "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
        "S": date.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}
