/**
 *解析全部的参数，返回一个Object
 *
 * @returns
 */
function parseUrlParams(url = location.search) {
    var paramsArr = decodeURIComponent(url)
        .replace(/amp;/g, '')
        .split('&'),
        result = {};
    // 删除？
    paramsArr[0] = paramsArr[0].substr(1);
    for (var i = 0, j = paramsArr.length; i < j; i++) {
        var valArr = paramsArr[i].split('=');
        result[valArr[0]] = decodeURIComponent(valArr[1]);
    }

    return result;
}

/**
 * 格式化url，添加参数
 *
 * @param {*} url
 * @param {*} params
 * @returns
 */
const formatUrl = (url, params) => {
    if (!url) {
        return '';
    }
    let keys = Object.keys(params);
    if (keys.length === 0) {
        return url;
    }
    let base = url.indexOf('?') > -1 ? `${url}&` : `${url}?`;
    return keys.reduce((acc, v, i) => {
        if (i === 0) {
            return (acc += `${v}=${params[v]}`);
        } else {
            return (acc += `&${v}=${params[v]}`);
        }
    }, base);
};

/**
 * 获取url中特定字符串的值
 * @param {*} name 字符串key
 * @param {*} path 默认为页面链接地址，也可自己传某段string
 */
const getUrlParameter = (name, path = window.location.href) => {
    const result =
        decodeURIComponent(
            (new RegExp('[?|&]' + name + '=([^&;]+?)(&|#|;|$)').exec(path) || [
                undefined,
                ''
            ])[1].replace(/\+/g, '%20')
        ) || null;
    return result ? result : '';
};


/**
 * 判断是否在小程序内部
 */
const isWeChatApplet = () => {
    const ua = window.navigator.userAgent.toLowerCase();
    if (ua.indexOf('miniprogramhtmlwebview') != -1) {
        return true;
    }
    return false;
}

//获取缩略文字，超出半角尺寸显示省略号
function getEllipsisText(str, maxSize) {
    if(!str){
        return "";
    }
    var num = getCharSize(str);
    if (num > maxSize) {
        // return str.substr(0, maxSize / 2) + "...";
        return getMaxSizeChar(str, maxSize) + "...";
    }
    return str;
}

//获取字符的半角尺寸
function getCharSize(str) {
    var match = str.match(/[^\u0000-\u00ff]/g);
    if (match) {
        return str.length + match.length;
    }
    return str.length;
}

//获取行文字
function getMaxSizeChar(str, maxSize) {
    var len = str.length;
    var total = 0;
    var i;
    for (i = 0; i < len; i++) {
        if (str.charCodeAt(i) > 128) {
            total += 2;
        } else {
            total += 1;
        }
        if (total >= maxSize) {
            break;
        }
    }
    return str.substr(0, i);
}


export {
    getUrlParameter,
    parseUrlParams,
    formatUrl,
    isWeChatApplet,
    getEllipsisText
};