import Vue from "vue";
// import "@/lib/spark-md5.min.js";
const SparkMD5 = require('spark-md5')


// 缓存
const DicsCatch = {};
// 单级下拉字典项
Vue.prototype.$dicsListsInit = function (selectList) {

    return new Promise((resolve, reject) => {
        let noSelectList = {};
        for (let selectNames in selectList) {
            let dicsName = selectList[selectNames];
            if (!!DicsCatch[dicsName]) {
                this[selectNames] = DicsCatch[dicsName]
            } else {
                noSelectList[selectNames] = dicsName
            }
        }

        if (Object.values(noSelectList).length <= 0) {
            resolve()
        } else {
            this.$axios({
                method: "post",
                url: this.$api.common.getDictListsByTypes,
                data: {
                    dictTypes: Object.values(noSelectList).join(",")
                }
            }).then(res => {
                if (res.code != 200) {
                    this.$message.error(res.message || "字典获取失败");
                    reject();
                    return false;
                }
                let result = res.info;
                for (let selectNames in noSelectList) {
                    let dicsName = noSelectList[selectNames];
                    for (let i = 0; i < result[dicsName].length; i++) {
                        this[selectNames].push({
                            caption: result[dicsName][i].dictName,
                            code: result[dicsName][i].dictCode,
                        });
                    }
                    DicsCatch[dicsName] = this[selectNames]
                }
                resolve();
            }).catch(error => {
                this.$message.error("网络异常");
                reject(error);
            });
        }
    });
}



// 缓存
const DicsTreeCatch = {};
// 单级下拉字典项
Vue.prototype.$dicsTreesInit = function (selectList) {

    return new Promise((resolve, reject) => {
        let noSelectList = {};
        for (let selectNames in selectList) {
            let dicsName = selectList[selectNames];
            if (!!DicsTreeCatch[dicsName]) {
                this[selectNames] = DicsTreeCatch[dicsName]
            } else {
                noSelectList[selectNames] = dicsName
            }
        }

        if (Object.values(noSelectList).length <= 0) {
            resolve()
        } else {
            this.$axios({
                method: "post",
                url: this.$api.common.getDictTreesByTypes,
                data: {
                    dictTypes: Object.values(noSelectList).join(",")
                }
            }).then(res => {
                if (res.code != 200) {
                    this.$message.error(res.message || "字典获取失败");
                    reject();
                    return false;
                }
                let result = res.info;
                for (let selectNames in noSelectList) {
                    let dicsName = noSelectList[selectNames];
                    // for (let i = 0; i < result[dicsName].length; i++) {
                    //     this[selectNames].push({
                    //         name: result[dicsName][i].dictName,
                    //         code: result[dicsName][i].dictCode,
                    //     });
                    // }
                    this[selectNames] = result[dicsName]
                    DicsTreeCatch[dicsName] = this[selectNames]
                }
                resolve();
            }).catch(error => {
                this.$message.error("网络异常");
                reject(error);
            });
        }
    });
}


/**
 * 计算文件的MD5
 * @param file 文件
 * @param chunkSize 分片大小
 * @returns Promise
 */
function md5(file, chunkSize) {
    // element 中组件对 file 进行加工，这里使用未加工的对象，只有未加工的对象才能在 blobSlice.call() 中正常操作
    let fileRaw = file

    // console.log('fileRaw',fileRaw);

    return new Promise((resolve, reject) => {
        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
        let fileReader = new FileReader()
        let chunkSize = 2097152;
        let chunks = Math.ceil(file.size / chunkSize)
        let currentChunk = 0
        let spark = new SparkMD5()

        fileReader.onload = function (e) {
            spark.appendBinary(e.target.result);
            currentChunk++;
            if (currentChunk < chunks) {
                loadNext();
            } else {
                let md5 = spark.end();
                // console.log('computed hash', md5)
                resolve(md5);
            }
        };

        fileReader.onerror = function (e) {
            console.warn('FileReader error.')
            reject(e);
        };

        function loadNext() {
            let start = currentChunk * chunkSize
            let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize
            fileReader.readAsBinaryString(blobSlice.call(file, start, end));
        }

        loadNext();
    });
}

// 深度优先遍历
/* deepFirstSearch(node, nodeList) {
    if (node) {
        nodeList.push(node);
        var children = node.children;
        if (children) {
            for (var i = 0; i < children.length; i++)
                //每次递归的时候将 需要遍历的节点 和 节点所存储的数组传下去
                this.deepFirstSearch(children[i], nodeList);
        }
    }
    return nodeList;
}, */

// 获取objectPath，由于截取去掉的'0.'后的字符串位数为15-17位不等(不一定是16位)，所以采取拼接的方式
Vue.prototype.$getObjectPathByRandom = function () {
    let a = Math.random().toString().slice(2, 10);
    let b = Math.random().toString().slice(2, 10);
    return a + b;
}

Vue.prototype.$md5 = md5

function TimeFormatter(time){
    if(!time){
        return ''
    }
    let date = new Date(time)
    let year = date.getFullYear()
    let month = date.getMonth()+1
    let day = date.getDate()
    let hour = date.getHours()
    let min = date.getMinutes()
    let second = date.getSeconds()
    month<10?month = '0' + month:undefined
    day<10?day = '0' + day:undefined
    hour<10?hour = '0' + hour:undefined
    min<10?min = '0' + min:undefined
    second<10?second = '0' +second:undefined
    return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + second
}
 Vue.prototype.$timeFormatter = TimeFormatter

 function ValidatePhone(val){
    let phoneReg = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    // let mobReg = /0?1[3|4|5|8][0-9]\d{8}$/;
    let mobReg = /0?1[0-9]\d{9}$/;
    if(phoneReg.test(val)||mobReg.test(val)){
        return true
    }else{
        return false
    }
 }

 Vue.prototype.$validatePhone = ValidatePhone

 function ValidateMobilePhone(val){
    let mobReg = /0?1[0-9]\d{9}$/;
    if (mobReg.test(val)) {
        return true
    } else {
        return false
    }
 }

 Vue.prototype.$ValidateMobilePhone = ValidateMobilePhone

 function ValidateInteger(val,max){
    let reg = /(^[0-9]\d*$)/
    if(reg.test(val)){
        return true 
    }else{
        return false
    }
 }
 Vue.prototype.$validateInteger = ValidateInteger

// 流文件下载处理  压缩包
function blobZipDown (blob, name){
   const url = window.URL.createObjectURL(
     new Blob([blob], {
       // 设置该文件的类型，这里对应的类型对应为.zip格式
       type: 'application/zip',
     }),
   );
   const link = document.createElement('a');
   link.href = url;
   const fileName = decodeURI(name);
   link.setAttribute('download', `${fileName}.zip`);
   document.body.appendChild(link);
   link.click();
 };

 Vue.prototype.$blobZipDown = blobZipDown