import getScroll from './getScroll'
 /**
 * 正则表达式判定Url
 * @param url
 * @returns {Boolean}
 */
export function checkUrl(url){
    //url= 协议://(ftp的登录信息)[IP|域名](:端口号)(/或?请求参数)
    var strRegex = '^((https|http|ftp)://)?'//(https或http或ftp):// 可有可无
        + '(([\\w_!~*\'()\\.&=+$%-]+: )?[\\w_!~*\'()\\.&=+$%-]+@)?' //ftp的user@  可有可无
        + '(([0-9]{1,3}\\.){3}[0-9]{1,3}' // IP形式的URL- 3位数字.3位数字.3位数字.3位数字
        + '|' // 允许IP和DOMAIN（域名） 
        + '(localhost)|'	//匹配localhost
        + '([\\w_!~*\'()-]+\\.)*' // 域名- 至少一个[英文或数字_!~*\'()-]加上.
        + '\\w+\\.' // 一级域名 -英文或数字  加上.
        + '[a-zA-Z]{1,6})' // 顶级域名- 1-6位英文 
        + '(:[0-9]{1,5})?' // 端口- :80 ,1-5位数字
        + '((/?)|' // url无参数结尾 - 斜杆或这没有
        + '(/[\\w_!~*\'()\\.;?:@&=+$,%#-]+)+/?)$';//请求参数结尾- 英文或数字和[]内的各种字符
    
    var strRegex1 = '^(?=^.{3,255}$)((http|https|ftp)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/)?(?:\/(.+)\/?$)?(\/\w+\.\w+)*([\?&]\w+=\w*|[\u4e00-\u9fa5]+)*$';
    var re=new RegExp(strRegex,'i');//i不区分大小写 
    //将url做uri转码后再匹配，解除请求参数中的中文和空字符影响
    if (re.test(encodeURI(url))) {
        return (true);
    } else {
        return (false);
    }
}
export function getTargetRect(target) {
    return target !== window ? target.getBoundingClientRect() : { top: 0, left: 0, bottom: 0 };
}
export function getOffset(element, target) {
    const elemRect = element.getBoundingClientRect();
    const targetRect = getTargetRect(target);

    const scrollTop = getScroll(target, true);
    const scrollLeft = getScroll(target, false);

    const docElem = window.document.body;
    const clientTop = docElem.clientTop || 0;
    const clientLeft = docElem.clientLeft || 0;

    return {
        top: elemRect.top - targetRect.top + scrollTop - clientTop,
        left: elemRect.left - targetRect.left + scrollLeft - clientLeft,
        width: elemRect.width,
        height: elemRect.height,
    };
}

export function getDefaultTarget() {
    return typeof window !== 'undefined' ? window : null;
}

/**
 * @method setUrlValue
 * @description 设置地址栏参数值
 * @param url
 * @param pName
 * @param pValue
 * 
 * @example: urlAppend("http://www.fdauto.com","userid=03870");�����http://www.fdauto.com?userid=03870;1`
 *           urlAppend("http://www.fdauto.com?userid=03870","bumen=aj")�����http://www.fdauto.com?userid=03870&bumen=aj;
 */

export function setUrlValue(url, key, value) {
    var returnUrl = ''
    if (url.indexOf('?') == -1) {
        returnUrl += url + '?' + key + '=' + value
    } else {
        if (url.indexOf('?' + key + '=') == -1 && url.indexOf('&' + key + '=') == -1) {
            returnUrl += url + '&' + key + '=' + value
        } else {
            var isDone = false
            var startIndex = 0
            var endIndex = url.length - 1
            var parm = '?' + key + '='
            for (var i = 0; i < url.length; i++) {
                if (url.substr(i, parm.length) == parm) {
                    startIndex = i + parm.length
                    for (var j = startIndex; j < url.length; j++) {
                        if (url[j] == '&') {
                            endIndex = j
                            break
                        } else if (j == url.length - 1) {
                            endIndex = url.length
                        }
                    }
                    isDone = true
                    break
                }
            }
            if (!isDone) {
                parm = '&' + key + '='
                for (var i = 0; i < url.length; i++) {
                    if (url.substr(i, parm.length) == parm) {
                        startIndex = i + parm.length
                        for (var j = startIndex; j < url.length; j++) {
                            if (url[j] == '&') {
                                endIndex = j
                                break
                            } else if (j == url.length - 1) {
                                endIndex = url.length
                            }
                        }
                        break
                    }
                }
            }
            var parmKeyValue = parm + url.substring(startIndex, endIndex)
            returnUrl = url.replace(parmKeyValue, parm + value)
        }
    }
    return returnUrl
}
/**
 * @method getUrlValue
 * @description 获取地址栏参数值
 * @param name
 *            string
 * @param url
 *            string
 * @example: getUrlValue("p","http://www.baidu.com?p=5"); 
 */
export function getUrlValue(url, name) {

    var str = url || window.location.search;
    if (str.indexOf("&" + name) != -1 || str.indexOf("?" + name) != -1) {
        var pos_start = ""
        if (str.indexOf("?" + name) > -1)
            pos_start = str.indexOf("?" + name) + name.length + 2;
        else
            pos_start = str.indexOf("&" + name) + name.length + 2;
        var pos_end = str.indexOf("&", pos_start);
        if (pos_end == -1) {
            return str.substring(pos_start);
        } else {
            return str.substring(pos_start, pos_end)
        }
    } else {
        return "";
    }
}
export function getUrlSearch(url) {
    var name, value;
    var str = url; //取得整个地址栏
    var num = str.indexOf("?")
    str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

    var arr = str.split("&"); //各个参数放到数组里
    var search ={};
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            search[name] = value;
        }
    }
    return search;
}
/**
 * var str='这是一个测试的字符串：{0} {1}'.format('Hello','world');
 * var str='这是一个测试的字符串：{str0} {str1}'.format({str0:'Hello',str1:'world'});
 */
export function strFormat(str, args) {
    var result = str;
    if (arguments.length > 0) {
        if (arguments.length == 2 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 1; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({)" + (i - 1) + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

export function closeWindow(errorUrl){
    if (document.all) {
        if (window.location.pathname == window.parent.location.pathname) {
            window.opener = null;
            window.open('', '_top');
            window.top.close();
        }
    } else {
        window.close();
    }

    window.location.href = errorUrl || "about:blank";
}
/*5.0替换3.0菜单字段*/
export function field5Change3(_arr){
    /*5.0字段替换3.0*/
    let fieldConversion={
        isActive:"fisactive",
        isOffline:"fisoffline",
        isShow:"fshow",
        name:"fresname",
        orderIndex:"forder",
        parentId:"frespguid",
        resId:"fresguid",
        resUrl:"fresurl",
        type:"frestype",
        iconClass:"ficonclass",
        openType:"fc2",
    };
    _arr.map(item=>{
        if(item.children&&item.children.length>0){
            field5Change3(item.children);
        }
        if(item.customList&&item.customList.length>0){
            field5Change3(item.customList);
        }
        for(let i in fieldConversion){
            if(typeof(item[fieldConversion[i]])!="undefined"){
                item[i]=item[fieldConversion[i]];
                delete item[fieldConversion[i]];
            }
        } 
        //判断是不是url 地址
        //serverName 是有加e5  ,但现在做兼容了，可以不用
        // if(!window._global){//正式环境
        //     item.resUrl=window.HIVUI_SETTING.serverName+item.resUrl;
        // }
        return item;
    });
    return _arr;
}
export function turnMenuTree(data,isNotTop) {//data:平级数据;isNotTop:输出数据是否不包含根节点
    let map = {};
    let val = [];
    let virtualDirMap={};
    function getVDirPid(id){//获取虚拟目录的上级id
        let _pid=virtualDirMap[id];
        return _pid?getVDirPid(_pid):id;
    }
    //生成数据对象集合
    data.forEach(it=>{
        map[it.resId] = it;    //resId为每个节点的id
        if(it.type=="virtualDir"){//虚拟目录隐藏该级节点
            virtualDirMap[it.resId]=it.parentId;
        }
        if(it.parentId==-1&&it.type=="root"){
            isNotTop=true;
        }
    });
    //生成结果集
    data.forEach(it=>{
        if(it.type!="virtualDir"){//虚拟目录隐藏该级节点
            let parent = map[getVDirPid(it.parentId)||it.parentId];   //parentId为父节点的id
            if(it.customList&&it.customList.length>0){//自定义菜单项（动态流程）
                it.children=it.customList.filter((item)=>{
                    if(item.name && item.resUrl){
                        item.isShow=1;
                        return item;
                    }
                });
                if(it.children.length==0){
                    delete it.children;
                }
            }
            if(parent){
                if(!Array.isArray(parent.children)) parent.children = [];
                parent.children.push(it);
            }else{
                val.push(it);
            }
        }
    });
    val=__sort(val);
    //排序
    function __sort(__data,orderField="orderIndex"){
        let zeroArr=__data.filter(item=>{
            return item[orderField]==0;
        });
        let normalArr=__data.filter(item=>{
            return item[orderField]!=0;
        });
        normalArr.sort((a,b)=>{
            var value1 = a[orderField];
            var value2 = b[orderField];
            return value1 - value2;
        });
        __data=normalArr.concat(zeroArr);
        for(let i of __data){
            if(i.children&&i.children.length>0){
                i.children=__sort(i.children);
            }
        }
        return __data;
    }
    //排查子节点是否全部不显示
    function __filterHide(__data,total){
        let count=0;
        for(let i=0;i<__data.length;i++){
            if(__data[i].children&&__data[i].children.length>0){
                    if(!__filterHide(__data[i].children,__data[i].children.length)){
                        __data[i].isShow=0;
                        count++;
                    }
            }else{
                if(!__data[i].isShow){
                    count++;
                }
            }
        }
        return count!=total;
    }
    let __result=isNotTop?(val[0]&&val[0].children):val;
    if(__result){
        __filterHide(__result,__result.length);
        return __result;
    }else{
        Vue.prototype.$message.error(`名称“${val[0].name}”ID为“${val[0].resId}”的菜单项配置出错，请排查。`);
        return [];
    }
    
}
/*
*notificationFunc--弹起浏览器消息通知方法
*title:消息弹窗标题
*ctn:消息弹窗内容
*cb:点击事件回调
*type:弹窗类型：ele，饿了么组件
*/
export function notificationFunc(title,ctn,cb,type){
    //发起消息通知
    function popNotice() {
        if (Notification.permission == "granted") {
            var notification = new Notification(title, {
                body: ctn,//消息内容
            });
            notification.onclick = function() {//消息通知点击事件
                cb&&cb();
                window.focus();
                notification.close();    
            };
        }    
    };
    if (Notification.permission == "granted" && type!='ele') {
        popNotice();
    } else if (Notification.permission != "denied" && type!='ele') {
        Notification.requestPermission((permission)=>{//发起询问授权
            popNotice();
        });
    }else{
        Vue.prototype.$notify.info({
            title: title,
            message: ctn,
            position: 'bottom-right',
            onClick:(evt)=>{
                cb&&cb();
            }
        });
    }
}
/*
* map对象排序成数组对象
*/
export function sortMapTurnArr(map){
    let result=[];
    let __itemSort=map?.itemSort;
    if(__itemSort){
        __itemSort.forEach((item)=>{
            let pushData=map[item];
            if(item=="|"){
                pushData={ type: 'split' };
            }
            if(pushData){
                result.push(pushData);
            }else{}
        });
    }else{
        result=map;
    }
    return result;
}