import { isNotEmpty } from "../index"
// 支持四舍五入的小数位数，超过位数的再做保留，没超过的原样返回
export function toFixed(value, len) {
    if (!isNotEmpty(value)) {
        return value
    }
    let mathSym = ""
    value += ""

    if (/^(-|\+)/.test(value)) {
        let allStr = value
        value = allStr.replace(/^(-|\+)+/, "")
        mathSym = allStr.replace(value, "")
    }
    // 将小数末尾0全去掉
    value = value.includes(".") ? value.replace(/\.?0*$/g, "") : value
    const regExp = new RegExp(`^\\d*(\\.\\d{${len + 1},})$`)
    // 小数位超标的才进行转换
    if (regExp.test(value)) {
        value = Number(value).toFixed(len)
        // 将小数末尾0全去掉，为了避免js出现的计算溢出
        value = value.includes(".") ? value.replace(/\.?0*$/g, "") : value
    }
    return mathSym + value
}

// 强制保留小数位
export function toFixedForce(value, len) {
    if (!isNotEmpty(value)) {
        return value
    }
    value += ""
    return Number(value).toFixed(len)
}

export function toRMB(n) {
    let fraction = ['角', '分'];
    let digit = [
        '零', '壹', '贰', '叁', '肆',
        '伍', '陆', '柒', '捌', '玖'
    ];
    let unit = [
        ['圆', '万', '亿'],
        ['', '拾', '佰', '仟']
    ];
    let IsNum = Number(n);
    if (!isNaN(IsNum)) {
        let head = n < 0 ? '欠' : '';
        n = Math.abs(n);
        let s = '';
        for (let i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(n * 100 / 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        n = Math.floor(n);
        for (let i = 0; i < unit[0].length && n > 0; i++) {
            let p = '';
            for (let j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零圆/, '圆')
            .replace(/(零.)+/g, '零')
            .replace(/^整$/, '零圆整');
    } else {
        return "";
    }
}

export function minusSign(value) {
    if (isNotEmpty(value) && value > 0) {
        return "-" + value
    }
    return value
}