import SparkMD5 from 'spark-md5'
import { FileUpload } from '@/api/api'
//删除树中节点
export function searchOption(option, arr, type = 'delect', obj = {}) {
    //首先循环arr最外层数据
    for (let s = 0; s < arr.length; s++) {
        //如果匹配到了arr最外层中的我需要修改的数据
        if (arr[s].id === option.id) {
            //判断需要操作的类型
            if (type === 'delect') {
                //删除即删除即可
                arr.splice(s, 1)
            } else {
                //如果是修改，利用Object.assign()组合符合arr数据格式的对象，并进行修改
                this.$set(
                    arr,
                    s,
                    Object.assign(obj, {
                        id: obj.pid,
                        title: obj.menuName,
                        children: option.children,
                        scopedSlots: { title: 'custom' }
                    })
                )
            }
            break
        } else if (arr[s].children && arr[s].children.length > 0) {
            // 递归条件
            searchOption(option, arr[s].children, type, obj)
        } else {
            continue
        }
    }
}

//替换对象属性名
// const target =
//     [
//         ['nick_name', 'name'],
//         ['job', 'work']
//     ]
// changeKeys(jobList, target)
export function changeKeys(list, tar) {
    list.forEach(elem => {
        tar.forEach(pair => {
            const oldKey = pair[1];
            const newKey = pair[0];
            if (oldKey !== newKey && elem[oldKey]) {
                // 这里主要处理的是把新的属性给到老的属性
                Object.defineProperty(elem, newKey, Object.getOwnPropertyDescriptor(elem, oldKey));
                delete elem[oldKey];
            }
        });
    })
    return list;
}
//获取文件md5值
export function getFileMD5(file, callback) {
    //声明必要的变量
    var fileReader = new FileReader(),
        //文件每块分割2M，计算分割详情
        chunkSize = 2097152,
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        //创建md5对象（基于SparkMD5）
        spark = new SparkMD5()
    //每块文件读取完毕之后的处理
    fileReader.onload = function (e) {
        //每块交由sparkMD5进行计算
        spark.appendBinary(e.target.result)
        currentChunk++
        //如果文件处理完成计算MD5，如果还有分片继续处理
        if (currentChunk < chunks) {
            loadNext()
        } else {
            callback(spark.end())
        }
    }
    //处理单片文件的上传
    function loadNext() {
        var start = currentChunk * chunkSize,
            end = start + chunkSize >= file.size ? file.size : start + chunkSize

        fileReader.readAsBinaryString(file.slice(start, end))
    }
    loadNext()
}
//获取文件id
export const getFileID = (file, callback) => {
    return new Promise((resolve, reject) => {
        getFileMD5(file, md5 => {
            let params = {
                md5: md5
            }
            var formData = new FormData();
            formData.append("formFile", file);
            console.log(formData, 'formData', file)
            FileUpload(formData, params).then(res => {
                resolve(res)
            })
        })
    })
}
export function download(blob, fileName = '') {
    console.log(blob, 'blob')
    if (!fileName) {
        fileName = blob.headers["content-disposition"];
        fileName = fileName.split(";")[2].split("filename*=UTF-8''")[1];
        fileName = decodeURI(fileName);
    }
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
    } else {
        console.log(blob, 'blob')
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
}
//数组内容分组
export function groupArr(arr, key, name) {
    var obj = {}, newArr = [];
    arr.forEach(item => {
        if (!obj.hasOwnProperty(item[key])) {
            newArr.push({
                type: item[key],
                name: name ? item[name] : '',
                data: [item]
            })
            obj[item[key]] = item[key];
        } else {
            newArr.forEach(v => {
                if (v.type == item[key]) {
                    v.data.push(item)
                }
            })
        }
    })
    return newArr;
}
//阿拉伯数字转中文数字
export function NoToChinese(num) {
    if (!/^\d*(\.\d*)?$/.test(num)) {
        alert("Number is wrong!");
        return "Number is wrong!";
    }
    var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
    var BB = new Array("", "十", "百", "千", "万", "亿", "点", "");
    var a = ("" + num).replace(/(^0*)/g, "").split("."),
        k = 0,
        re = "";
    for (var i = a[0].length - 1; i >= 0; i--) {
        switch (k) {
            case 0:
                re = BB[7] + re;
                break;
            case 4:
                if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0]))
                    re = BB[4] + re;
                break;
            case 8:
                re = BB[5] + re;
                BB[7] = BB[5];
                k = 0;
                break;
        }
        if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re;
        if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
        k++;
    }
    if (a.length > 1) //加上小数部分(如果有小数部分) 
    {
        re += BB[6];
        for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
    }
    return re;
};
export function trimStr(str = '') {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
//字符串转换dom:
export function stringToDom(arg) {
    var objE = document.createElement("div");
    objE.innerHTML = arg;
    return objE;
}
//dom转换字符串：
export function domToStirng(node) {
    var tmpNode = document.createElement("div");
    tmpNode.appendChild(node.cloneNode(true));
    var str = tmpNode.innerHTML;
    tmpNode = node = null;
    return str;
}

export function getQueryString(name) { 
  let reg = `(^|&)${name}=([^&]*)(&|$)`
  let r = window.location.search.substr(1).match(reg); 
  if (r != null) return unescape(r[2]); return null; 
}

const DEFAULT_CONFIG = {
  id: 'id',
  children: 'children',
  pid: 'parentId',
};

const getConfig = (config) => Object.assign({}, DEFAULT_CONFIG, config);

// tree from list
export function listToTree(list, config= {}){
  const conf = getConfig(config);
  const nodeMap = new Map();
  const result = [];
  const { id, children, pid } = conf;

  for (const node of list) {
    node[children] = node[children] || [];
    nodeMap.set(node[id], node);
  }
  for (const node of list) {
    const parent = nodeMap.get(node[pid]);
    (parent ? parent.children : result).push(node);
  }
  return result;
}