// 转银行卡号格式，每4位一个空格
export function toBankCardNumber(number) {
    if (/\S{5}/.test(number)) {
        return number.replace(/\s/g, '').replace(/(.{4})/g, "$1 ");
    } else {
        return number;
    }
}

// 金额转换 保留2位小数 并每隔3位用逗号分开 1,234.56
export function toMoney2(val) {
    let str = val.toFixed(2) + '';
    let intSum = str.substring(0, str.indexOf(".")).replace(/\B(?=(?:\d{3})+$)/g, ',');//取到整数部分
    let dot = str.substring(str.length, str.indexOf("."))//取到小数部分搜索
    return intSum + dot;
}

// 转成金额模式
export function toMoney(val, decimalPlaces) {
    val = val.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    val = val.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    val = val.replace(/^0+\./g, '0.');
    val = val.match(/^0+[1-9]+/) ? val.replace(/^0+/g, '') : val
    val = (val.match(/^\d*(\.?\d{0,10})/g)[0]) || ''
    if (val.includes(".")) {
        let numDian = val.toString().split(".")[1].length;
        if (numDian > decimalPlaces ?? 2) {
            val = val.substring(0, val.length - (numDian - decimalPlaces));
        }
    }
    return val;
}


// 强制保留2位小数，不足补0
export function toFixed2(str) {
    str = str.toString();
    let index = str.indexOf('.');
    if (index < 0) {
        index = str.length;
        str += '.';
    }
    while (str.length <= index + 2) {
        str += '0';
    }
    return str;
}

// 仅保留字符串中的数字
export function toNumber(str) {
    return str.replace(/[^\d]/g, '')
}

// 移除字符串中的空格
export function removeSpace(str) {
    return str.replace(/\s+/g, "");
}

/**
 * @returns {String} 当前浏览器名称
 */
export const getExplorerTitle = () => {
    const ua = window.navigator.userAgent
    const isExplorer = (exp) => {
        return ua.indexOf(exp) > -1
    }
    if (isExplorer('MSIE')) return 'IE'
    else if (isExplorer('Firefox')) return 'Firefox'
    else if (isExplorer('Chrome')) return 'Chrome'
    else if (isExplorer('Opera')) return 'Opera'
    else if (isExplorer('Safari')) return 'Safari'
}


// 下划线转换驼峰
export const toHump = (name) => {
    return name.replace(/_(\w)/g, (all, letter) => letter.toUpperCase());
}
// 驼峰转换下划线
export const toLine = (name) => {
    return name.replace(/([A-Z])/g, "_$1").toLowerCase();
}

// 获取UUID
export const getUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}