ensure.page.js 28.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
/**
 * 订单结算页
 * @author: yyq<yanqing.yang@yoho.cn>
 * @date: 2016/11/30
 */

var $ = require('yoho-jquery');

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

var $balanceDetail = $('#balance-detail'),
    $orderPrice = $('#order-price');

var order = {
    printPrice: 'Y'
};

var payWay,
    deliveryWay,
    multiPackage,
    coupon,
    yohoCoin,
    giftCard,
    refund;

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

var address = require('./order/address'),
    invoice = require('./order/invoice'),
    esaypayInfo = require('./order/easypay');

var giftCardTpl = require('hbs/cart/ensure-gift-card-list.hbs');
var coinTpl = Hbs.compile($('#yoho-coin-tpl').html());
var promotionTpl = Hbs.compile($('#promotion-list-tpl').html());

$.extend(order, esaypayInfo);

$('#hide-count-data').remove();

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

if (!$('.goods-item').length) {
    new dialog.Dialog({
        content: '暂无可结算商品,请返回购物车重新选择',
        className: 'ensure-back-alert',
        btns: [{
            id: 'back-sure',
            btnClass: ['back-sure'],
            name: '返回购物车',
            cb: function() {
                $('#go-cart-btn').trigger('click');
            }
        }]
    }).show();
}

order.cartType = window.queryString().type || 1;

// FE Helper
Hbs.registerHelper('round', function(num, precision) {
    precision = parseFloat('0' + precision, 10) || 2;

    return (+num).toFixed(precision);
});

// 订单计算
// 传有货币数量则使用有货币,否者不使用,更改订单总价有货币使用数量重置为0
function compute(coin, cb) {
    var reqData = {
        cartType: order.cartType,
        coin: coin ? coin : 0
    };

    // 支付方式
    if (order.paymentType) {
        reqData.paymentType = order.paymentType;
    }

    // 配送方式
    if (order.deliveryWay) {
        reqData.deliveryWay = order.deliveryWay;
    }

    // 优惠券
    if (order.couponCode) {
        reqData.couponCode = order.couponCode;
    } else if (order.promotionCode) {
        reqData.promotionCode = order.promotionCode;
    }

    // 有货币(保证更改其他价格yoho币不清零,调接口传最大数量,接口限制可使用数量)
    if (!coin && order.coin) {
        reqData.coin = yohoCoin.totalCoin;
    }

    // 红包
    if (order.redEnvelopes) {
        reqData.redEnvelopes = order.redEnvelopes;
    }

    // 礼品卡
    if (order.giftCard) {
        reqData.giftCard = order.giftCard;
    }

    if (esaypayInfo) {
        if (order.sku) {
            reqData.sku = order.sku;
        }

        if (order.skn) {
            reqData.skn = order.skn;
        }

        if (order.limitcode) {
            reqData.limitcode = order.limitcode;
        }

        if (order.bundle) {
            reqData.bundle = order.bundle;
        }
    }

    $.ajax({
        type: 'POST',
        url: '/cart/ensure/compute',
        data: reqData
    }).then(function(data) {
        var res;

        if (data.code === 200) {
            res = data.data;

            // update order used yoho coin
            order.coin = res.usedCoinNum;

            // update yoho coin max use num
            yohoCoin.maxCoin = res.canUseCoinNum;

            // update yoho coin using
            yohoCoin.$el.html(coinTpl(res));

            // update last order amount
            lastOrderPrice = res.last_order_amount;
            $orderPrice.html('¥ ' + res.last_order_amount);

            // update promotion formula list
            $balanceDetail.html(promotionTpl(res));

            // update giftCard use status
            giftCard.setUseStatus(lastOrderPrice);

        }

        // callback
        if (cb && typeof cb === 'function') {
            return cb(data);
        }
    });
}

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

    if (!errTip && !info.addressId) {
        errTip = '请填写配送地址';
    }

    if (!errTip && !info.paymentType) {
        errTip = '请选择支付方式';
    }

    if (!errTip && !info.deliveryWay) {
        errTip = '请选择配送方式';
    }

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

    return true;
}

// 支付方式
payWay = {
    $allType: $('.pay-wrap > p'),
    init: function() {
        var that = this;

        this.payType = {};
        this.$payType = this.$allType.not('.unsp-pay').find('.check-btn');
        this.$payType.each(function() {
            var $this = $(this),
                data = $this.data();

            that.payType[data.id] = {
                dom: $this,
                id: data.id,
                type: data.type
            };

            // 更新订单支付数据
            if ($this.hasClass('checked')) {
                that.updateOrder(data);
            }
        });
        this.eventBind();
    },
    eventBind: function() {
        var that = this;

        this.$payType.click(function() {
            var $this = $(this);
            var pt = that.payType[$this.data('id')];

            if ($this.hasClass('checked') || (pt && pt.unsupport)) {
                return;
            }

            that.$payType.removeClass('checked');
            $this.addClass('checked');

            // 更新订单支付数据
            that.updateOrder(pt);

            // 重新计算订单价格
            compute();
        });

        $('#pay-type2').change(function() {
            that.setSupportStatus('0', $(this).val() * 1);
        });
    },
    setSupportStatus: function(id, support) {
        var pt, vd, $tip;

        if (!id || !this.payType[id]) { // this.payType[id]不存在表示订单不支持货到付款
            return;
        }

        pt = this.payType[id];
        $tip = pt.dom.next();

        if (!pt.defTip) {
            pt.defTip = $tip.text();
        }

        if (support) {
            pt.dom.parent().removeClass('unsp-pay');
            pt.unsupport = false;
            $tip.text(pt.defTip || '');
        } else {
            pt.dom.parent().addClass('unsp-pay');
            pt.unsupport = true;
            $tip.text('您所选择的区域暂不支持货到付款');

            if (pt.dom.hasClass('checked')) {
                this.$payType.eq(0).trigger('click');
            }

            vd = new dialog.Dialog({
                content: '<div class="title">支付方式</div><p>很抱歉,该地区不支持货到付款,将为您选择<br>在线支付,是否继续?</p>',
                className: 'ensure-cashdeli-dialog',
                btns: [{
                    id: 'save',
                    btnClass: ['black'],
                    name: '继续',
                    cb: function() {
                        vd.close();
                    }
                }, {
                    id: 'cancel',
                    name: '修改地址',
                    cb: function() {
                        vd.close();
                        $('.addr-select .modify-addr').trigger('click');
                    }
                }]
            }).show();
        }
    },
    updateOrder: function(info) {
        if (!info) {
            return;
        }

        if (info.hasOwnProperty('id')) {
            order.paymentId = info.id;
        }

        if (info.hasOwnProperty('type')) {
            order.paymentType = info.type;
        }
    }
};

// 配送方式
deliveryWay = {
    $deliveryType: $('.delivery-way-wrap .check-btn'),
    $deliveryTime: $('.delivery-time-wrap .check-btn'),
    init: function() {
        var that = this;

        this.deliveryType = {};
        this.$deliveryType.each(function() {
            var $this = $(this),
                data = $this.data();

            that.deliveryType[data.id] = {
                dom: $this,
                id: data.id,
                unsupport: $this.parent().hasClass('unsp-way')
            };

            // 设置默认支持状态
            that.deliveryType[data.id].defaultSupport = !that.deliveryType[data.id].unsupport;

            // 更新订单配送方式数据
            if ($this.hasClass('checked')) {
                that.updateOrder({way: data.id});
            }
        });

        this.$deliveryTime.each(function() {
            var $this = $(this);

            // 更新订单送货时间数据
            if ($this.hasClass('checked')) {
                that.updateOrder({time: $this.data('id')});
            }
        });
        this.eventBind();
    },
    eventBind: function() {
        var that = this;

        this.$deliveryType.click(function() {
            var $this = $(this),
                id = $this.data('id');
            var dt = that.deliveryType[id];

            if ($this.hasClass('checked') || (dt && dt.unsupport)) {
                return;
            }
            that.$deliveryType.removeClass('checked');
            $this.addClass('checked');

            // 更新订单配送方式数据
            that.updateOrder({way: id});

            // 重新计算订单价格
            compute(0, function(data) {
                if (data.code === 200 && coupon && coupon.$ticketUseTip) {
                    coupon.$ticketUseTip.find('.price').text('- ¥' + data.data.coupon_amount.toFixed(2));
                }
            });
        });

        this.$deliveryTime.click(function() {
            var $this = $(this);

            if ($this.hasClass('checked')) {
                return;
            }
            that.$deliveryTime.removeClass('checked');
            $this.addClass('checked');

            // 更新订单送货时间数据
            that.updateOrder({time: $this.data('id')});
        });

        $('#support-way2').change(function() {
            that.setSupportStatus(2, $(this).val() * 1);
        });
    },
    setSupportStatus: function(id, support) {
        var dt;

        if (!id || !this.deliveryType[id]) {
            return;
        }

        dt = this.deliveryType[id];

        if (support && dt.defaultSupport) {
            dt.dom.parent().removeClass('unsp-way');
            dt.unsupport = false;
        } else {
            dt.dom.parent().addClass('unsp-way');
            dt.unsupport = true;

            if (dt.dom.hasClass('checked')) {
                this.$deliveryType.eq(0).trigger('click');
            }
        }
    },
    updateOrder: function(info) {
        if (!info) {
            return;
        }

        if (info.time) {
            order.deliveryTime = info.time;
        }

        if (info.way) {
            order.deliveryWay = info.way;
        }
    }
};

// jit拆单
multiPackage = {
    $el: $('.multi-package-row'),
    init: function() {
        var that = this;

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

        this.$pkgList = $('.package-list', this.$el);

        // 初始化数据
        that.pkgCache = {};
        $('.package-item', this.$el).each(function() {
            var $this = $(this);
            var $list = $this.find('.package-goods'),
                num = $list.children('li').length;

            $list.width(num * 86 + 4);

            if (num > 5) {
                $this.find('.toggle-btns').show();
            }

            that.pkgCache[$(this).index()] = {
                total: num
            };
        });

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

        this.$el.on('click', '.show-package', function(e) {
            that.$pkgList.toggleClass('hide');
            $(this).toggleClass('on');

            e.stopPropagation();
        }).on('click', '.toggle-icon', function() {
            var $this = $(this);
            var flag = $this.hasClass('left-icon') ? -1 : 1;

            that.pkgPageControl($this.closest('.package-item'), flag);
        });

        // 绑定document事件,去触发面板关闭
        $(document).on('click', function(e) {
            if (that.$pkgList.hasClass('hide') || $(e.target).closest('.package-list').length > 0) {
                return;
            }

            that.$pkgList.addClass('hide').prev().removeClass('on');
        });
    },
    pkgPageControl: function($el, flag) {
        var id = $el.index(),
            $ul = $el.find('.package-goods'),
            theCache = this.pkgCache[id],
            curPage = theCache.cur ? theCache.cur : 1,
            page = Math.ceil(theCache.total / 5);

        curPage += flag;

        // 第一页或最后一页
        if (curPage < 1 || curPage > page) {
            return;
        }

        $ul.animate({
            marginLeft: -(curPage - 1) * ($ul.parent('.package-goods-wrap').width() + 20)
        }, 200);

        theCache.cur = curPage;
    }
};

// 优惠券
coupon = {
    $el: $('#use-coupons'),
    init: function() {
        if (!this.$el.length) {
            return;
        }

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

        this.$errorTip = $('.coupon-err-tip', this.$el);
        this.$ticketUseTip = $('.ticket-use-tip', this.$couponWrap);

        this.$couponCode = $('.coupon-code', this.$couponWrap);
        this.$couponList = $('.coupon-list-wrap', this.$couponWrap);

        this.couponsTpl = Hbs.compile($('#coupons-tpl').html());

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

        $.ajax({
            type: 'GET',
            url: '/cart/ensure/coupons'
        }).then(function(data) {
            if (data.code === 200) {
                $('.coupon-list-wrap', that.$couponWrap).html(that.couponsTpl(that.selectUsedCoupon(data.data)));

                if (choose) { // 兑换券后默认使用该券
                    $('.coupon-radio', that.$couponWrap).each(function() {
                        $(this).data('id') === choose && $(this).trigger('click');
                    });
                }
            }
        });
    },
    useCode: function(code) {
        var that = this;

        if (!code) {
            return;
        }

        $.ajax({
            type: 'GET',
            url: '/cart/ensure/couponcode',
            data: {code: code}
        }).then(function(data) {
            if (data.code === 200) {
                that.getList(data.data.coupon_code);
            } else {
                that.$errorTip.text(data.message || '兑换失败,请稍后再试');
            }
        });
    },
    selectUsedCoupon: function(data) {
        var i;

        if (order.couponCode) {
            data.usable_coupons = data.usable_coupons || [];
            data.usable_frees_coupons = data.usable_frees_coupons || [];

            for (i = 0; i < data.usable_coupons.length; i++) {
                if (order.couponCode.indexOf(data.usable_coupons[i].coupon_code) > -1) {
                    data.usable_coupons[i].using = true;
                }
            }

            for (i = 0; i < data.usable_frees_coupons.length; i++) {
                if (order.couponCode.indexOf(data.usable_frees_coupons[i].coupon_code) > -1) {
                    data.usable_frees_coupons[i].using = true;
                }
            }
        }

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

        this.$couponWrap.on('click', '.cancel-use-ticket', function() {
            that.cancelTicketUse();
        }).on('change', '.coupon-code', function() {
            that.$errorTip.empty();
        }).on('click', '.sure-convert', function() {
            that.useCode($(this).siblings('.coupon-code').val());
        }).on('click', '.coupon-radio', function() {
            var $this = $(this),
                $par = $this.parent();

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

            $par.siblings('.red').removeClass('red').children('.coupon-radio').removeClass('on');
            $this.addClass('on');
            $par.addClass('red');

            // 改变优惠券使用搭配,重新计算订单价格
            that.changeTicketsUse();
        });
    },
    changeTicketsUse: function() {
        var that = this;
        var coupons = [];

        this.$couponWrap.find('.coupon-radio.on').each(function() {
            var data = $(this).data();

            if (data) {
                coupons.push(data.id);
            }
        });

        if (coupons.length) {
            this.$ticketUseTip.find('.num').text(coupons.length);
            order.couponCode = coupons.join(',');

            // 重新计算订单价格
            compute(0, function(data) {
                if (data.code === 200) {
                    that.$ticketUseTip.find('.price').text('- ¥' + data.data.coupon_amount.toFixed(2));
                    that.$ticketUseTip.removeClass('hide');
                }
            });
        }
    },
    cancelTicketUse: function() {
        if (order.couponCode) {
            this.$ticketUseTip.addClass('hide');
            this.$couponWrap.find('li.red').removeClass('red').find('.on').removeClass('on');

            delete order.couponCode;
            compute(); // 重新计算订单价格
        }
    },
    cancelCodeUse: function() {
        this.$errorTip.empty();
        this.$couponCode.val('');

        if (order.couponCode) {
            delete order.couponCode;
            compute(); // 重新计算订单价格
        }
    },
    close: function() {
        this.$el.children('.locker-switch').trigger('click');
    }
};

// 有货币
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) {
                $('.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();
    },
    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');
        }
    }
};

// 退换货提示
refund = {
    $el: $('.special-tip'),
    init: function() {
        if (!this.$el.length) {
            return;
        }

        this.eventBind();
    },
    eventBind: function() {
        this.$el.on('click', '.special-limit-7day', function() {
            $(this).parent().find('.special-limit-tip').toggleClass('hide');
        });
    }
};

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

    $par.toggleClass('open');
    address.area.ieRefresh();
});

(function() {
    var $redSureBtn = $('#red-packet-sure');
    var $redPacketBox = $('#red-packet-box');
    var used;

    if (!$redSureBtn.length) {
        return;
    }

    used = $redSureBtn.data('used') * 1;

    if (used) {
        order.redEnvelopes = used;

        $redSureBtn.siblings('.radio-btn').addClass('on');
    }

    $redPacketBox.on('click', '.radio-btn', function() {
        $(this).toggleClass('on');
    }).on('click', '.sure-btn', function() {
        var $this = $(this),
            num = $this.data('num');

        // 触发关闭事件
        $redPacketBox.prev().children('.locker-switch').trigger('click');

        if (!num) {
            return;
        }

        if ($this.siblings('.on').length) {
            order.redEnvelopes = num;
        } else if (order.redEnvelopes) {
            delete order.redEnvelopes;
        }
        compute(); // 重新计算订单价格
    });
}());

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

function submitOrder(reqData) {
    $.ajax({
        type: 'POST',
        url: '/cart/ensure/submit',
        data: reqData
    }).then(function(data) {
        var rdata, subTip, newUser,
            tongJi = {
                num: 0,
                skn: [],
                sku: [],
                py: []
            };

        if (data.code === 200) {
            rdata = data.data;
            if (rdata && rdata.is_hint === 'Y') {
                if (rdata.hintInfo) {
                    subTip = rdata.hintInfo.productName || '';

                    if (subTip && subTip.length > 20) {
                        subTip = subTip.substr(0, 20) + '...';
                    }
                    subTip += rdata.hintInfo.suffix + '<br/>' + rdata.hintInfo.lastLine;
                }

                new dialog.Dialog({
                    content: subTip,
                    className: 'ensure-hint-confirm',
                    btns: [{
                        id: 'hint-sure',
                        btnClass: ['confirm-sure'],
                        name: '重新选择商品',
                        cb: function() {
                            $('#go-cart-btn').trigger('click');
                        }
                    }, {
                        id: 'hint-cancel',
                        btnClass: ['confirm-cancel'],
                        name: '继续结算',
                        cb: function() {
                            order.continueBuy = true;
                            $('#order-submit').trigger('click');
                        }
                    }]
                }).show();

            } else {
                $('.goods-item').each(function() {
                    var dt = $(this).data();

                    tongJi.num += dt.num * 1;
                    tongJi.skn.push(dt.skn);
                    tongJi.sku.push(dt.sku);
                    tongJi.py.push({
                        id: dt.skn,
                        count: dt.num,
                        price: dt.price
                    });
                });

                // yas统计
                yas.givePoint('YB_SC_TOPAY_CLICK', {ORDER_CODE: rdata.order_code, PRD_NUM: tongJi.num,
                    ORDER_AMOUNT: rdata.order_amount, PRO_SKN: tongJi.skn.join(','), PRO_SKU: tongJi.sku.join(',')});

                // 品友统计
                if (window.py) {
                    window.py('event', 'order', {
                        id: rdata.order_code,
                        money: rdata.order_amount,
                        items: tongJi.py
                    }).track('MC.ROh.yqkx8jgGASmo3McexF7XE0');
                }

                // 品众统计
                if (window._fxcmd) {
                    newUser = window.cookie('__NEW_USER') || 0;

                    window._fxcmd.push(['trackOrder', {
                        oid: rdata.order_code,
                        otp: rdata.order_amount,
                        u_info: window.getUid(),
                        u_type: newUser
                    }, []]);
                    window.setCookie('__NEW_USER', 0);
                }

                location.href = rdata.url;
            }
        } else if (data.message) {
            new dialog.Alert(data.message).show();
        }
    });
}

$('#remark-box').on('keyup', '.note-text', function() {
    var $this = $(this);
    var val = $.trim($this.val());

    if (val) {
        $this.addClass('has-text');

        if (val.length > 100) {
            val = val.substring(0, 99);
            $this.val(val);
        }

        order.remark = val;
    } else {
        $this.removeClass('has-text');
    }
}).on('click', '.radio-btn', function() {
    var $this = $(this);

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

    if ($this.hasClass('unprint')) {
        order.printPrice = 'N';
    } else {
        order.printPrice = 'Y';
    }

    $this.siblings('.on').removeClass('on');
    $this.addClass('on');
});

$('#order-submit').click(function() {
    var invoiceInfo = invoice.getInvoice();
    var checkDg;

    order.addressId = address.getAddress();

    // 发票信息
    if (invoiceInfo) {
        $.extend(order, invoiceInfo);
    }

    // 订单参数校验
    if (!validateOrderInfo(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);
                        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--) + 's').addClass('timer');

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

            return this;
        };

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

        checkDg.sendSms().show();

        return;
    } else {
        order.checkCode && delete order.checkCode;
    }

    submitOrder(order);
});

payWay.init();
deliveryWay.init();
multiPackage.init();
coupon.init();
yohoCoin.init();
giftCard.init();
refund.init();

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

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