"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
var Fs = __importStar(require("fs"));
var Path = __importStar(require("path"));
var LogUtil_1 = __importDefault(require("./LogUtil"));
//--------------------------------创建文件操作----------------------------
var asciiList = {
    "33": '!',
    "34": '"',
    "35": '#',
    "36": '$',
    "37": '%',
    "38": '&',
    "39": "'",
    "40": '(',
    "41": ')',
    "42": '*',
    "43": '+',
    "44": ',',
    "45": '-',
    "46": '.',
    "47": '/',
    "48": '0',
    "49": '1',
    "50": '2',
    "51": '3',
    "52": '4',
    "53": '5',
    "54": '6',
    "55": '7',
    "56": '8',
    "57": '9',
    "58": ':',
    "59": ';',
    "60": '<',
    "61": '=',
    "62": '>',
    "63": '?',
    "64": '@',
    "65": 'A',
    "66": 'B',
    "67": 'C',
    "68": 'D',
    "69": 'E',
    "70": 'F',
    "71": 'G',
    "72": 'H',
    "73": 'I',
    "74": 'J',
    "75": 'K',
    "76": 'L',
    "77": 'M',
    "78": 'N',
    "79": 'O',
    "80": 'P',
    "81": 'Q',
    "82": 'R',
    "83": 'S',
    "84": 'T',
    "85": 'U',
    "86": 'V',
    "87": 'W',
    "88": 'X',
    "89": 'Y',
    "90": 'Z',
    "91": '[',
    "92": '\\',
    "93": ']',
    "94": '^',
    "95": '_',
    "96": '`',
    "97": 'a',
    "98": 'b',
    "99": 'c',
    "100": 'd',
    "101": 'e',
    "102": 'f',
    "103": 'g',
    "104": 'h',
    "105": 'i',
    "106": 'j',
    "107": 'k',
    "108": 'l',
    "109": 'm',
    "110": 'n',
    "111": 'o',
    "112": 'p',
    "113": 'q',
    "114": 'r',
    "115": 's',
    "116": 't',
    "117": 'u',
    "118": 'v',
    "119": 'w',
    "120": 'x',
    "121": 'y',
    "122": 'z',
    "123": '{',
    "124": '|',
    "125": '}',
    "126": '~'
};
var FileUtil = /** @class */ (function () {
    function FileUtil() {
    }
    /**
         * 复制文件/文件夹
         * @param {Fs.PathLike} srcPath 源路径
         * @param {Fs.PathLike} destPath 目标路径
         */
    FileUtil.copy = function (srcPath, destPath) {
        if (!Fs.existsSync(srcPath))
            return;
        var stats = Fs.statSync(srcPath);
        if (stats.isDirectory()) {
            if (!Fs.existsSync(destPath))
                Fs.mkdirSync(destPath);
            var names = Fs.readdirSync(srcPath);
            for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
                var name_1 = names_1[_i];
                this.copy(Path.join(srcPath, name_1), Path.join(destPath, name_1));
            }
        }
        else if (stats.isFile()) {
            Fs.writeFileSync(destPath, Fs.readFileSync(srcPath));
        }
    };
    /**
     * 删除文件/文件夹
     * @param {Fs.PathLike} path 路径
     */
    FileUtil.deleteFile = function (path) {
        if (!Fs.existsSync(path))
            return;
        var stats = Fs.statSync(path);
        if (stats.isDirectory()) {
            var names = Fs.readdirSync(path);
            for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
                var name_2 = names_2[_i];
                this.deleteFile(Path.join(path, name_2));
            }
            Fs.rmdirSync(path);
        }
        else if (stats.isFile()) {
            Fs.unlinkSync(path);
        }
    };
    /**
     * 遍历文件/文件夹并执行函数
     * @param {Fs.PathLike} path 路径
     * @param {(filePath: Fs.PathLike, stat: Fs.Stats) => void} handler 处理函数
     */
    FileUtil.map = function (path, handler) {
        if (!Fs.existsSync(path))
            return;
        var stats = Fs.statSync(path);
        if (stats.isDirectory()) {
            var names = Fs.readdirSync(path);
            for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
                var name_3 = names_3[_i];
                this.map(Path.join(path, name_3), handler);
            }
        }
        else if (stats.isFile()) {
            handler(path, stats);
        }
    };
    // 方法
    //写入文件
    FileUtil.writePathFile = function (path, codes, callback) {
        var pathA = path.split("/");
        pathA.pop();
        this.createDirsSync(pathA.join("/"), function () {
            // 写入文件内容的回调函数
            Fs.writeFileSync(path, codes);
            callback && callback();
        });
    };
    // 判断有没有当前文件夹，有就查询下一层文件夹，没有就创建
    FileUtil.createDirsSync = function (dir, callback) {
        // if(Fs.existsSync(dir)){
        // }
        // else{
        //     //如果该路径不存在
        //     console.log(dir+"路径不存在")
        //     let tempDir = getFilePathName(dir);      //拿到上级路径
        //     if(tempDir){
        //         console.log(tempDir)
        //         createDirsSync(tempDir)
        //     }
        //     else{
        //     }
        // }
        // let sortDir = sortPath(dir)
        var sortDir = dir;
        var dirs = sortDir.split('/');
        if (dirs[0] == '.' || dirs[0] == "..") {
            dirs[1] = dirs[0] + "/" + dirs[1];
            dirs.shift();
        }
        if (dirs[dirs.length - 1] == "") {
            dirs.pop();
        }
        var len = dirs.length;
        var i = 0;
        var url = dirs[i];
        // 逐级检测有没有当前文件夹，没有创建，有就继续检测下一级
        var mkDirs = function (url) {
            if (Fs.existsSync(url)) {
                i = i + 1;
                if (len > i) {
                    url = url + "/" + dirs[i];
                    mkDirs(url);
                }
                else {
                    callback && callback();
                }
            }
            else {
                mkDir(url);
            }
        };
        // 创建文件
        var mkDir = function (url) {
            // console.log(url,i,len)
            Fs.mkdirSync(url);
            i = i + 1;
            if (len > i) {
                url = url + "/" + dirs[i];
                mkDir(url);
            }
            else {
                callback && callback();
            }
        };
        // 启动递归函数
        mkDirs(url);
    };
    FileUtil.sortPath = function (path) {
        var newPath = "";
        for (var index = 0; index < path.length; index++) {
            var letter = path[index];
            if (letter == "\\") {
                letter = "/";
            }
            newPath += letter;
        }
        // console.log("sortPath :",newPath)
        return newPath;
    };
    FileUtil.isJSONFile = function (file) {
        if (Fs.existsSync(file)) {
            var data = Fs.readFileSync(file, 'utf-8');
            if (typeof data == 'string') {
                try {
                    var obj = JSON.parse(data);
                    if (typeof obj == 'object' && obj) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
                catch (e) {
                    console.log('error：' + data + '!!!' + e);
                    return false;
                }
            }
        }
        else {
            LogUtil_1["default"].logError("文件不存在:" + file);
            return {};
        }
    };
    //加载json文件
    FileUtil.loadJsonByPath = function (file) {
        if (Fs.existsSync(file)) {
            var data = Fs.readFileSync(file, 'utf-8');
            if (data) {
                try {
                    return JSON.parse(data.toString());
                }
                catch (e) {
                    // console.log(data)
                    // console.log(file)
                    // LogUtil.logError("文件非标准json:",file,data)
                    // console.log('error：'+data+'!!!'+e);
                    return false;
                }
            }
            else {
                // console.log(data)
                // console.log(file)
                LogUtil_1["default"].logError("文件非标准json:" + file);
                return false;
            }
        }
        else {
            LogUtil_1["default"].logError("文件不存在:" + file);
            return false;
        }
    };
    /** 删除文件目录 */
    FileUtil.removeDirsSync = function (url) {
        var _this = this;
        var files = [];
        /**
         * 判断给定的路径是否存在
         */
        if (Fs.existsSync(url)) {
            /**
             * 返回文件和子目录的数组
             */
            if (Fs.statSync(url).isDirectory()) {
                files = Fs.readdirSync(url);
                files.forEach(function (file, index) {
                    var curPath = Path.join(url, file);
                    /**
                     * Fs.statSync同步读取文件夹文件，如果是文件夹，在重复触发函数
                     */
                    if (Fs.statSync(curPath).isDirectory()) { // recurse
                        _this.removeDirsSync(curPath);
                    }
                    else {
                        Fs.unlinkSync(curPath);
                    }
                });
                /**
                 * 清除文件夹
                 */
                Fs.rmdirSync(url);
            }
            else {
                Fs.unlinkSync(url);
            }
        }
        else {
            console.log("路径不存在，无法删除: " + url);
        }
    };
    /** 复制文件 */
    FileUtil.copyFile = function (file, toFile) {
        var pathA = toFile.split("/");
        // console.log(pathA)
        pathA.pop();
        this.createDirsSync(pathA.join("/"), function () {
            // 写入文件内容的回调函数
            Fs.copyFileSync(file, toFile);
        });
    };
    /** 复制文件夹路径 */
    FileUtil.copyFolder = function (srcDir, tarDir, cb) {
        var _this = this;
        // console.log(srcDir, tarDir)
        var files = Fs.readdirSync(srcDir);
        files.forEach(function (file) {
            var srcPath = srcDir + "/" + file;
            var tarPath = tarDir + "/" + file;
            var stats = Fs.statSync(srcPath);
            if (stats.isDirectory()) {
                // console.log('mkdir----------', tarPath)
                _this.createDirsSync(tarPath);
                _this.copyFolder(srcPath, tarPath);
            }
            else {
                // console.log('copyFile----------', srcPath,tarPath)
                _this.copyFile(srcPath, tarPath);
            }
        });
    };
    FileUtil.getAllFileName = function (path) {
        var jsonStr = {};
        var searchDir = function (dir) {
            var files = Fs.readdirSync(dir);
            files.forEach(function (item, index) {
                //lstatSync方法返回一个stat数组对象
                var stat = Fs.lstatSync(dir + "/" + item);
                if (stat.isDirectory() === true) {
                    searchDir(dir + "/" + item);
                }
                else {
                    jsonStr[item] = dir + "/" + item;
                }
            });
        };
        searchDir(path);
        return jsonStr;
    };
    /** 获取相对路径与绝对路径的映射关系 */
    FileUtil.getAllFilePath = function (path) {
        var jsonStr = {};
        var searchDir = function (dir, rootPath) {
            var files = Fs.readdirSync(dir);
            files.forEach(function (item, index) {
                //lstatSync方法返回一个stat数组对象
                var stat = Fs.lstatSync(dir + "/" + item);
                if (stat.isDirectory() === true) {
                    searchDir(dir + "/" + item, Path.join(rootPath, item));
                }
                else {
                    jsonStr[Path.join(rootPath, item)] = dir + "/" + item;
                }
            });
        };
        searchDir(path, "");
        return jsonStr;
    };
    /** 重命名此文件 */
    FileUtil.reFileNameByPath = function (oldFilePath, newFilePath) {
        Fs.renameSync(oldFilePath, newFilePath);
    };
    /** 返回文件的文件夹名 */
    FileUtil.getFilePathName = function (filePath) {
        return Path.dirname(filePath);
    };
    FileUtil.getFloderPath = function (filePath) {
        var floderList = filePath.split("/");
        var str = "";
        for (var i = 0; i < floderList.length - 1; i++) {
            var floderName = floderList[i];
            if (i != 0) {
                str += "/";
            }
            str += floderName;
        }
        return str;
    };
    /** 返回文件的文件夹名 */
    FileUtil.isFileExist = function (filePath) {
        if (Fs.existsSync(filePath)) {
            return true;
        }
        else {
            return false;
        }
    };
    FileUtil.getCharByAsciiList = function (number) {
        return asciiList[number];
    };
    //递归创建目录 同步方法  
    FileUtil.mkdirsSync = function (dirname) {
        if (Fs.existsSync(dirname)) {
            return true;
        }
        else {
            if (this.mkdirsSync(Path.dirname(dirname))) {
                // console.log("mkdirsSync = " + dirname);
                Fs.mkdirSync(dirname);
                return true;
            }
        }
    };
    /**  */
    FileUtil._copy = function (src, dist, curCount, maxCount) {
        var _this = this;
        if (curCount === void 0) { curCount = 0; }
        if (maxCount === void 0) { maxCount = 1; }
        var countData = {
            curCount: 0,
            maxCount: 0
        };
        countData.curCount = curCount;
        countData.maxCount = maxCount;
        var paths = Fs.readdirSync(src);
        paths.forEach(function (p) {
            var _src = src + '/' + p;
            var _dist = dist + '/' + p;
            var stat = Fs.statSync(_src);
            if (stat.isFile()) { // 判断是文件还是目录
                countData.curCount++;
                // console.log("copy:"+ _src+"\n");
                Fs.writeFileSync(_dist, Fs.readFileSync(_src));
                var progress = countData.curCount / countData.maxCount;
                progress = (progress > 1) ? 1 : progress;
                //只输出这一行
                LogUtil_1["default"].logLine("copy: " + countData.curCount + "个文件 ==> " + (Math.floor(progress * 100)) + " % " + "\n");
            }
            else if (stat.isDirectory()) {
                countData = _this.tocopyFolderSync(_src, _dist, countData.curCount, countData.maxCount); // 当是目录是，递归复制
            }
        });
        return countData;
    };
    /* 同步复制文件夹
     * 复制目录、子目录，及其中的文件
     * @param src {String} 要复制的目录
     * @param dist {String} 复制到目标目录
     */
    FileUtil.tocopyFolderSync = function (src, dist, curCount, maxCount) {
        if (curCount === void 0) { curCount = 0; }
        if (maxCount === void 0) { maxCount = 1; }
        var b = Fs.existsSync(dist);
        //   console.log("copy:", dist)
        if (!b) {
            // console.log("mk dist = ",dist)
            this.mkdirsSync(dist); //创建目录
        }
        //   console.log("_copy start")
        var countData = this._copy(src, dist, curCount, maxCount);
        return countData;
    };
    /* 同步复制文件夹
     * 复制目录、子目录，及其中的文件
     * @param src {String} 要复制的目录
     * @param dist {String} 复制到目标目录
     */
    FileUtil.copyFolderSync = function (src, dist) {
        var jsonList = this.getAllFileName(src);
        var fileCount = Object.keys(jsonList).length;
        // console.log(Object.keys(jsonList).length);
        this.tocopyFolderSync(src, dist, 0, fileCount);
        // console.log(Object.keys(jsonList).length);
        // console.log(jsonList);
    };
    /* 同步复制文件
     * @param src {String} 要复制的目录
     * @param dist {String} 复制到目标目录
     */
    FileUtil.copyFileSync = function (file, toFile) {
        var str = "/";
        var pathA = toFile.split(str);
        // console.log(pathA)
        if (pathA.length <= 1) {
            str = "\\";
            pathA = toFile.split(str);
        }
        pathA.pop();
        this.createDirsSync(pathA.join(str), function () {
            // 写入文件内容的回调函数
            Fs.copyFileSync(file, toFile);
        });
    };
    /* 同步移动文件
     * @param src {String} 要复制的目录
     * @param dist {String} 复制到目标目录
     */
    FileUtil.moveFileSync = function (file, toFile) {
        var str = "/";
        var pathA = toFile.split(str);
        // console.log(pathA)
        if (pathA.length <= 1) {
            str = "\\";
            pathA = toFile.split(str);
        }
        pathA.pop();
        this.createDirsSync(pathA.join(str), function () {
            // 写入文件内容的回调函数
            Fs.renameSync(file, toFile);
        });
    };
    // 获取文件夹内某名字文件，并移动到另一个文件夹
    FileUtil.moveFileBySearchName = function (path, toPath, name) {
        var _this = this;
        var jsonStr = {};
        var searchDir = function (dir, toDir) {
            var files = Fs.readdirSync(dir);
            files.forEach(function (item, index) {
                //lstatSync方法返回一个stat数组对象
                var stat = Fs.lstatSync(dir + "/" + item);
                if (stat.isDirectory() === true) {
                    searchDir(dir + "/" + item, toDir + "/" + item);
                }
                else {
                    jsonStr[item] = dir + "/" + item;
                    if (item == name) {
                        // console.log("检测到匹配内容", jsonStr[item], item)
                        _this.moveFileSync(dir + "/" + item, toDir + "/" + item);
                    }
                }
            });
        };
        searchDir(path, toPath);
        return jsonStr;
    };
    return FileUtil;
}());
exports["default"] = FileUtil;
