export default {
    // 时间戳转换
    format: (time) => {
        var days = parseInt(time / (1000 * 60 * 60 * 24));
        var hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = (time % (1000 * 60)) / 1000;
        return days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 ";
    },
    // 时间处理
    timerFormat() {
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let h =
            date.getHours() < 10 ?
                "0" + date.getHours() :
                date.getHours();
        let m =
            date.getMinutes() < 10 ?
                "0" + date.getMinutes() :
                date.getMinutes();
        let s =
            date.getSeconds() < 10 ?
                "0" + date.getSeconds() :
                date.getSeconds();
        return year +
            "年" +
            month +
            "月" +
            day +
            "日" +
            " " +
            h +
            ":" +
            m +
            ":" +
            s;
    },
    //计算字符串长度，英文1个字符，中文2个字符
    computedStrLen(str) {
        var len = 0;
        for (var i = 0; i < str.length; i++) {
            var c = str.charCodeAt(i);
            //单字节加1
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                len++;
            } else {
                len += 2;
            }
        }
        return len;
    },
    /**
     * 对象的深度拷贝
     * @param data 需要拷贝的元数据
     * @return {any} 返回拷贝后的新数据
     */
    deepClone(data) {
        const type = this.getType(data);
        let obj;

        if (type === 'array') {
            obj = [];
        } else if (type === 'object') {
            obj = {};
        } else {
            //不再具有下一层次
            return data;
        }
        if (type === 'array') {
            for (let i = 0, len = data.length; i < len; i++) {
                obj.push(this.deepClone(data[i]));
            }
        } else if (type === 'object') {
            for (let key in data) {
                obj[key] = this.deepClone(data[key]);
            }
        }

        const constructor = data.constructor;
        if (constructor) {
            return Object.assign(new constructor(), obj);
        }
        return obj;
    },
    cleanData(data) {
        let _data = {};
        for (let key in data) {
            if (Object.prototype.toString.call(data[key]) === '[object Object]') {
                _data[key] = null;
            } else if (data[key] instanceof Array) {
                _data[key] = [];
            } else {
                _data[key] = undefined;
            }
        }
        return _data;
    },
    /**
     * 判断对象类型
     * @param {Object} object
     * @return {String} object type
     */
    getType(object) {
        var toString = Object.prototype.toString;
        var map = {
            '[object Boolean]': 'boolean',
            '[object Number]': 'number',
            '[object String]': 'string',
            '[object Function]': 'function',
            '[object Array]': 'array',
            '[object Date]': 'date',
            '[object RegExp]': 'regExp',
            '[object Undefined]': 'undefined',
            '[object Null]': 'null',
            '[object Object]': 'object'
        };
        if (object instanceof Element) {
            return 'element';
        }
        return map[toString.call(object)];
    },
    // 下载
    downloadFile(fileName, blob) {
        if (window.navigator.msSaveBlob) {
            // for ie10 and later
            try {
                window.navigator.msSaveBlob(blob, fileName);
            } catch (e) {
                console.log(e);
            }
        } else {
            // 只有 Firefox 和 Chrome 支持 download 属性。
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = window.URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
        }
    },
    downloadFileUrl(fileName, fileUrl) {
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = fileUrl
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
    },
    /*
     * 根据文件名的尾缀 返回文件类型
     * @param {any} fileName 文件名
     */
    getFileType(fileName) {
        // 后缀获取
        let suffix = '';
        // 获取类型结果
        let result = '';
        try {
            const flieArr = fileName.split('.');
            suffix = flieArr[flieArr.length - 1];
        } catch (err) {
            suffix = '';
        }
        // fileName无后缀返回 false
        if (!suffix) {
            return false;
        }
        suffix = suffix.toLocaleLowerCase();
        // 图片格式
        const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
        // 进行图片匹配
        result = imglist.find(item => item === suffix);
        if (result) {
            return 'image';
        }
        // 匹配txt
        const txtlist = ['txt'];
        result = txtlist.find(item => item === suffix);
        if (result) {
            return 'txt';
        }
        // 匹配 excel
        const excelist = ['xls', 'xlsx'];
        result = excelist.find(item => item === suffix);
        if (result) {
            return 'excel';
        }
        // 匹配 word
        const wordlist = ['doc', 'docx'];
        result = wordlist.find(item => item === suffix);
        if (result) {
            return 'word';
        }
        // 匹配 pdf
        const pdflist = ['pdf'];
        result = pdflist.find(item => item === suffix);
        if (result) {
            return 'pdf';
        }
        // 匹配 ppt
        const pptlist = ['ppt', 'pptx'];
        result = pptlist.find(item => item === suffix);
        if (result) {
            return 'ppt';
        }
        // 匹配 视频
        const videolist = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
        result = videolist.find(item => item === suffix);
        if (result) {
            return 'video';
        }
        // 匹配 音频
        const radiolist = ['mp3', 'wav', 'wmv'];
        result = radiolist.find(item => item === suffix);
        if (result) {
            return 'radio';
        }
        // 其他 文件类型
        return 'other';
    },
    // 千位分隔符
    numFormat(num) {
        var res = num.toString().replace(/\d+/, (n) => { // 先提取整数部分
            return n.replace(/(\d)(?=(\d{3})+$)/g, ($1) => {
                return $1 + ",";
            });
        })
        return res;
    },
    treeToArray(list, newArr = []) {
        list.forEach((item) => {
            const {
                children
            } = item;
            if (children) {
                delete item.children;

                if (children.length) {
                    newArr.push(item);
                    return this.treeToArray(children, newArr);
                }
            }
            newArr.push(item);
        });
        return newArr;
    },
    translateDataToTree(data, key) {
        let parents = data.filter(value => value.parentId === 0);
        let children = data.filter(value => value.parentId !== 0);
        let translator = (parents, children) => {
            parents &&
                parents.forEach(parent => {
                    children &&
                        children.forEach((current, index) => {
                            if (current.parentId === parent.id) {
                                // 深拷贝
                                let temp = JSON.parse(
                                    JSON.stringify(children)
                                );
                                // 减少递归时节点数
                                temp.splice(index, 1);
                                // 加入父节点的children
                                parent.children && parent.children.length
                                    ? parent.children.push(current)
                                    : (parent.children = [current]);
                                // 将匹配的子节点作为下一次的父节点开始滚雪球
                                translator([current], temp);
                            }
                        });
                });
        };
        translator(parents, children);
        parents = parents.filter(item => item.rights === key);
        return parents && parents.length && parents[0].children;
    }
}
