ticket.page.js 8.89 KB
/**
 * Created by TaoHuang on 2017/6/22.
 */


var $ = require('jquery');

var yas = require('../common/data-yas'),
    dialog = require('../common/dialog');

var $orderPrice = $('#order-price');
var order = {};

var yohoCoin,
    giftCard;

var lastOrderPrice = $orderPrice.data('price');
var submitting = false;

var giftCardTpl = require('hbs/cart/ensure-gift-card-list.hbs');

require('../common');
require('../simple-header');

function errorInfo(info, url) {
    new dialog.Dialog({
        content: info,
        className: 'ensure-back-alert',
        btns: [{
            id: 'back-sure',
            btnClass: ['back-sure'],
            name: '返回商品详情页',
            cb: function() {
                window.jumpUrl(url);
            }
        }]
    }).show();
}

if ($('.error').length === 1) {
    errorInfo(
        $('.error').find('.info').text(),
        $('.error').find('.url').text()
    );
}

function validateUserInfo(info) {
    var errTip = '';

    if (!info.mobile) {
        errTip = '您还没有填写手机号';
    }

    if (!errTip && !/^\d{11}$/ig.test(info.mobile)) {
        errTip = '手机号只能是11位数字';
    }

    if (errTip) {
        new dialog.Alert((errTip)).show();
        return false;
    }

    return true;
}

function handleOrderInfo(info) {
    var $goods = $('.goods-item');

    info.sku = $goods.data('sku');
    info.count = $goods.data('num');
    info.mobile = $('.ticket-mobile-input').val();

    return info;
}

function compute(coin) {
    var req;

    order = handleOrderInfo(order);
    req = $.extend({}, order, {
        coin: coin || 0
    });

    $.ajax({
        type: 'POST',
        url: '/cart/ticketcompute',
        data: req
    }).then(function(result) {
        if (result.code === 200) {
            order.coin = result.data.usedCoinNum;
            yohoCoin.maxCoin = result.data.canUseCoinNum;

            lastOrderPrice = result.data.last_order_amount;

            $orderPrice.html('¥ ' + lastOrderPrice);

            giftCard.setUseStatus(lastOrderPrice);
        }
    });
}

// 有货币
yohoCoin = {
    $el: $('#yoho-coin-box'),
    init: function() {
        var data;

        if (!this.$el.length) {
            return;
        }

        data = this.$el.data();

        if (data) {
            order.coin = data.coin || 0;
            this.maxCoin = data.max;
            this.totalCoin = data.total;
        }

        this.eventBind();
    },
    eventBind: function() {
        var that = this;

        this.$el.on('click', '.coin-use-btn', function() {
            if (order.coin * 1 !== this.maxCoin * 1) {
                compute(that.maxCoin);
            }

            that.close();
        }).on('click', '.coin-cancel-btn', function() {
            if (order.coin * 1 !== 0) {
                order.coin = 0;
                compute();
            }

            that.close();
        });
    },
    close: function() {
        this.$el.prev().children('.locker-switch').trigger('click');
    }
};

// 礼品卡
giftCard = {
    $el: $('#use-gift-card'),
    init: function() {
        if (!this.$el.length) {
            return;
        }

        this.$giftCardWrap = this.$el.next();

        this.getList();
        this.eventBind();
    },
    getList: function() {
        var that = this;

        $.ajax({
            type: 'GET',
            url: '/cart/ensure/giftcards'
        }).then(function(data) {
            if (data.code === 200) {
                if (data.data && data.data.usable_giftCards && data.data.usable_giftCards.length) {
                    that.$el.removeClass('hide').next().removeClass('hide');
                    $('.can-use-tip', that.$el).text('(' + data.data.usable_giftCards.length + '张可用)');
                }

                if (data.data.usable_giftCards.length) {
                    $('tbody', that.$giftCardWrap).html(giftCardTpl(data.data));

                    that.$radios = $('.gift-card-radio', that.$giftCardWrap);
                }

                that.checkContent = '<h2>安全验证</h2>' +
                    '<p class="tip-info">您正在使用礼品卡支付,为了保证您的账户安全,需要进行安全验证。</p>' +
                    '<p class="receiver-info">验证码已发送至' + (data.data.userMobile || '您绑定的') + '手机号</p>' +
                    '<p><input type="text" placeholder="短信验证码" maxlength="8"><span class="send-sms">获取验证码</span></p>';
            }
        });
    },
    eventBind: function() {
        var that = this;

        this.$giftCardWrap.on('click', '.gift-card-radio', function() {
            var $this = $(this);

            if ($this.hasClass('disabled')) {
                return;
            }

            if ($this.hasClass('on')) {
                // 取消使用礼品卡,设置其他礼品卡可用
                that.setUseStatus(2);
            } else if (+$this.data('price') >= lastOrderPrice * 1) { // 已选礼品卡总价大于订单总价,设置其他礼品卡不可选
                that.setUseStatus();
            }

            $this.toggleClass('on');
            that.changeCardUse();
        });
    },
    changeCardUse: function() {
        var codes = [];

        if (!this.$radios) {
            return;
        }

        this.$radios.filter('.on').each(function() {
            codes.push($(this).data('id'));
        });

        order.giftCard = codes.join(',');
        compute(order.coin);
    },
    setUseStatus: function(price) {
        if (!this.$radios) {
            return;
        }

        if (price && price * 1 > 0) {
            this.$radios.filter('.disable').removeClass('disable');
        } else {
            this.$radios.not('.on').addClass('disable');
        }
    }
};

function submitOrder(reqData, url) {
    submitting = true;
    $.ajax({
        type: 'POST',
        url: '/cart/ticketSubmit',
        data: reqData
    }).then(function(data) {
        if (data.code === 200) {
            window.location.href = data.data.refer;
        } else if (data.code === 500) {
            errorInfo(data.message, url);
        } else {
            new dialog.Alert(data.message || '网络异常~').show();
        }
    }).always(function() {
        submitting = false;
    });
}

function sendCkeckSms() {
    return $.ajax({
        type: 'POST',
        url: '/cart/property/checksms',
        data: {giftCard: order.giftCard}
    });
}

$('.locker-switch').click(function() {
    var $this = $(this),
        $par = $this.parent();

    $par.toggleClass('open');
});

$('#order-submit').on('click', function() {
    var errUrl = $(this).data('url'),
        checkDg;

    if (submitting) {
        return;
    }

    order = handleOrderInfo(order);

    if (!validateUserInfo(order)) {
        return;
    }

    // 使用礼品卡时候进行短信校验
    if (order.giftCard) {
        checkDg = new dialog.Dialog({
            content: giftCard.checkContent || '',
            className: 'gift-card-check-dialog',
            btns: [{
                id: 'check-cancel',
                btnClass: ['check-cancel'],
                name: '取消',
                cb: function() {
                    checkDg.close();
                }
            }, {
                id: 'check-sure',
                btnClass: ['check-sure'],
                name: '确定',
                cb: function() {
                    order.checkCode = $('input', checkDg.$el).val();

                    if (order.checkCode) {
                        submitOrder(order, errUrl);
                        checkDg.close();
                    }
                }
            }]
        });

        checkDg.$sendBtn = $('.send-sms', checkDg.$el);
        checkDg.sendSms = function() {
            var that = this;

            if (!this.$sendBtn || this.seconds > 0) {
                return;
            }

            sendCkeckSms(); // 发送验证码

            if (!this.seconds || this.seconds < 1) {
                this.seconds = 59;
            }

            this.timer && clearInterval(this.timer);

            this.$sendBtn.text('重新获取(' + (this.seconds--) + '秒)').addClass('timer');

            this.timer = setInterval(function() {
                if (that.seconds > 0) {
                    that.$sendBtn.text('重新获取(' + (that.seconds--) + '秒)').addClass('timer');
                } else {
                    that.$sendBtn.text('重新获取').removeClass('timer');
                    clearInterval(that.timer);
                }
            }, 1000);

            return this;
        };

        checkDg.$sendBtn.click(function() {
            checkDg.sendSms();
        });

        checkDg.sendSms().show();

        return;
    }

    order.checkCode && delete order.checkCode;
    submitOrder(order, errUrl);
});

yohoCoin.init();
giftCard.init();

// 获取用户是否新客(品众统计)写cookie
$.ajax({type: 'GET', url: '/home/newuser'});

// 订单确认页默认埋点
yas.givePoint('YB_SC_ORDER_ENSURE');