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

// 获取当前命令行上下文路径
const currentDirectory = process.cwd();
console.log(`----------------------------`)

const backupPath = path.join(currentDirectory, '/backup/')

//获取文件列表
const files = fs.readdirSync(backupPath);
if (files.length > 5) {
    //遍历文件列表
    console.log(`准备清理备份文件...`)
    let newfiles = []
    files.forEach((file) => {
        const time = file.split('_');
        if (time.length >= 2) {
            newfiles.push({time: time[0], file: file})
        }
    })
    //文件列表排序
    newfiles = arrKeySort(newfiles, 'time', 'desc');
    //移除文件
    newfiles.forEach((item, index) => {
        if (index >= 5) {
            fs.unlinkSync(backupPath + item.file);
            console.log(`已清理${item.file}`)
        }
    })
    console.log('---------- 清理完成 ----------')
} else {
    console.log(`备份文件小于5份，不执行清理操作...`)
}


//数组对象排序
function arrKeySort(arr, field = 'id', order = 'asc')
{
    return arr.sort(arrCompare(field, order));
}

function arrCompare(key, order = 'asc')
{
    return function innerSort(a, b) {
        if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
            // 该属性在任何一个对象上都不存在
            return 0;
        }
        const varA = (typeof a[key] === 'string')
            ? a[key].toUpperCase() : a[key];
        const varB = (typeof b[key] === 'string')
            ? b[key].toUpperCase() : b[key];
        let comparison = 0;
        if (varA > varB) {
            comparison = 1;
        } else if (varA < varB) {
            comparison = -1;
        }
        return (
            (order === 'desc') ? (comparison * -1) : comparison
        );
    };
}
