// 判断给定的字符串是否是有效的用户名
export function validUsername(str) {
    const valid_map = ['admin', 'editor'];
    return valid_map.indexOf(str.trim()) >= 0;
}

/**
 * 判断url是否是http或https
 * @param {string} path
 * @returns {Boolean}
 */
export function isHttp(url) {
    return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1;
}

// 数字转化为大写金额
export function digitUppercase(n) {
    const fraction = ['角', '分'];
    const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟'],
    ];
    // eslint-disable-next-line no-param-reassign
    n = Math.abs(n);
    let s = '';
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < fraction.length; i++) {
        // eslint-disable-next-line no-restricted-properties
        s += (digit[Math.floor(n * 10 * 10 ** i) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    // eslint-disable-next-line no-param-reassign
    n = Math.floor(n);
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < unit[0].length && n > 0; i++) {
        let p = '';
        // eslint-disable-next-line no-plusplus
        for (let j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            // eslint-disable-next-line no-param-reassign
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return s
        .replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整');
}

// 将一个数组中的空元素去掉
export function cleanArray(actual) {
    const newArray = [];
    for (let i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i]);
        }
    }
    return newArray;
}

// 数组去重
export function uniqueArr(arr) {
    return Array.from(new Set(arr));
}

// 将URL中的查询参数转换为对象
export function param2Obj(url) {
    const search = url.split('?')[1];
    if (!search) {
        return {};
    }
    return JSON.parse(`{"${decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`);
}

// 将对象转为为数组 =====》 待验证
export function toNumericPairs(obj) {
    const entries = Object.entries(input);
    return entries.map((entry) => [Number(entry[0]), entry[1]]);
}

/**
 * 判断path是否为外链
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
    return /^(https?:|mailto:|tel:)/.test(path);
}
