repayment.js 2.35 KB
const Repayment = function(options) {
    this.settings = Object.assign({

        onSelectAll: $.noop,

        onDeselectAll: $.noop,

        /**
         * 获取选择
         *
         * @returns {Array}
         */
        onGetSelection: function() {
            return [];
        }
    }, options);

    this.currAmt = $('.repayment-bottom').find('.curr-amt');
    this.currFee = $('.repayment-bottom').find('.curr-fee');
    this.total = 0;
    this.fee = 0;

    const self = this;

    $('.repayment-btn').on('click', function() {
        const path = location.pathname;

        const params = {
            action: 'go.instalmentRepayment',
            list: self.getSelection()
        };

        $(this).attr('href', path + '?openby:yohobuy=' + encodeURIComponent(JSON.stringify(params)));
    });

    $('#repayment-total').click(()=> {
        const isChecked = $(this).data('checked');

        if (!isChecked) {
            this.settings.onSelectAll.bind(this)();
        } else {
            this.settings.onDeselectAll.bind(this)();
        }

        this.update();
        $(this).data('checked', !$(this).data('checked'));
    });
};

/**
 * 格式化金额
 *
 * @param amount
 * @returns {string}
 * @private
 */
Repayment.prototype._formatCurrency = function(amount) {
    const m = ('' + amount).match(/(\d+)\.?(\d+)?/);
    const fixedPart = m[1], floatPart = m[2];

    let ret = '0.00';

    if (m && m.length === 3) {
        ret = `${fixedPart}.${floatPart || '00'}`;
    }

    return ret;
};

/**
 * 设置总金额
 *
 * @param total
 */
Repayment.prototype.setTotal = function(total) {
    this.total = total;

    this.currAmt.text(this._formatCurrency(this.total));
};


/**
 * 设置费用
 *
 * @param fee
 */
Repayment.prototype.setFee = function(fee) {
    this.fee = fee;

    this.currFee.text(this._formatCurrency(this.fee));
};


Repayment.prototype.getSelection = function() {
    return this.settings.onGetSelection();
};

Repayment.prototype.update = function() {
    const values = this.getSelection();

    this.total = 0;
    this.fee = 0;

    if (values && values.length) {
        values.forEach((value)=> {
            // 计算还款总额和费用
            this.total += value.amount + value.fee;
            this.fee += value.fee;
        });
    }

    this.setTotal(this.total);
    this.setFee(this.fee);
};

module.exports = Repayment;