import SnToast from '../toast';
export function formatToMoney(str) {
    var decimalLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;

    //单位元
    str = parseFloat(str);
    str = str.toFixed(decimalLength) + '';
    var rex = /\d{1,3}(?=(\d{3})+$)/g;
    return str.replace(/^(-?)(\d+)((\.\d+)?)$/, function (s, s1, s2, s3) {
        return s1 + s2.replace(rex, '$&,') + s3;
    });
}

export function toUpperCase(str) {
    //无小数点时默认为分
    str = str + '';
    if (str.indexOf('.') < 0) {
        str = (str / 100).toFixed(2);
    }
    var part = str.split('.');
    part[0] = part[0].replace(/^(0+)/g, '');
    part[1] = part[1].substring(0, 2).replace(/(0+)$/g, '');
    if (!part[0].length && !part[1].length) {
        return '零元';
    }
    var upperMoney = '';
    var numberArr = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = ['', '拾', '佰', '仟'];
    if (part[0].length > 20) {
        this.$toast('数字过大，无法计算');
        return upperMoney;
    }

    for (var i = 0; i < 2; i++) {
        var t = part[i];
        var tLen = t.length;
        for (var j = 0; j < tLen; j++) {
            var curBig = numberArr[t.charAt(j)];
            var figure = tLen - 1 - j;
            var curNum = '';
            if (i === 0) {
                curNum = curBig === '零' ? curBig : curBig + unit[figure % 4];
                if (!(figure % 4)) {
                    curNum = curBig === '零' ? ['', '万', '亿', '亿'][figure / 4] : curBig + ['', '万', '亿', '万'][figure / 4];
                }
            } else if (j === 0) {
                curNum = curBig === '零' ? curBig : curBig + '角';
            } else {
                curNum = curBig + '分';
            }
            upperMoney = upperMoney + curNum;
            if (i === 0 && j === tLen - 1) {
                upperMoney = upperMoney + '元';
            }
        }
    }
    while (upperMoney.search('零零') !== -1) {
        upperMoney = upperMoney.replace('零零', '零');
    }
    upperMoney = upperMoney.replace('零万', '').replace('零亿', '').replace('亿万', '亿');
    return upperMoney;
}

export default {
    formatToMoney: formatToMoney,
    toUpperCase: toUpperCase
};