detail.page.js 30.9 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 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
/**
 * 商品详情页
 * @author: tao.huang<tao.huang@yoho.cn>
 * @date: 2016/9/22
 */

/**
 *  说明:这里有一些优化方法。
 *  页面已经被 nginx 缓存,变化后的数据需要通过 ajax 进行获取后,重新绑定事件。
 */

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

var lazyLoad = require('yoho-jquery-lazyload');
var yas = require('../common/data-yas');
var dataLazyLoad = require('../plugins/lazy-load')(document);

var bindEvent = $.Callbacks(); // eslint-disable-line
var clickAcquireCouponEvent = $.Callbacks('unique'); // eslint-disable-line

var $main = $('.main'),
    id = $main.data('id'),
    md5 = $main.data('md5'),
    skn = $main.data('skn'),
    deposit = $main.data('deposit') === 'Y',
    secKill = $main.data('seckill') === 'Y',
    limitCode = encodeURIComponent($main.data('limitcode'));

var SLIDETIME = 200;

var colTxt = {
    def: '收藏商品',
    coled: '已收藏',
    hover: '取消收藏'
};

var oldtatus = {
    txt: '已领取',
    html: '<a class="coupon-btn">去使用</a>'
};

var $saleReturn = $('#saleReturn');

var dialogTpl = require('hbs/product/coupon-dialog.hbs');

var $goodsIdArr = [];

$('.recommend-slider .img-item .goods-id').each(function() {
    $goodsIdArr.push($(this).html());
});

function productUrl(s) {
    return window.location.href + '?openby:yohobuy={"action":"go.productDetail","params":{"product_skn":"' + s + '"}}';
}

function isEmpty(el) {
    return !$.trim(el.html());
}

require('../plugins/slider');
require('../common/center-slider');

bindEvent.add(function() {
    var $imgShow = $('#img-show'),
        $thumbs = $('#thumbs > .thumb-wrap');

    var $size = $('#sizes'),
        $sizes = $size.children('.size'),
        $sizeWarn = $size.find('.size-warn'),
        $colorSizeTip = $size.children('.color-size-tip');

    var $num = $('#num'),
        $plusNum = $('#plus-num'),
        $minusNum = $('#minus-num');

    var $addToCart = $('#add-to-cart'),
        $soldOut = $('#sold-out');

    var $lcContainer = $('.lc-container'),
        $itemBuy = $('.item-buy');

    var $qrcode = $('.qr-code');

    var $descColor = $('#desc-color');

    var thumbsLoaded = {};

    var isTicket = $('input[name="isTicket"]').length > 0 && $('input[name="isTicket"]').val() === 'true';

    var maxStock = -1; // 记录当前选中的颜色-尺码的库存量,若为-1,代表未选择尺码

    var brandDomain = $('.home').attr('href');

    var Alert = require('../common/dialog').Alert;

    var Dialog = require('../common/dialog').Dialog;

    var $moreCoupon = $('.more-coupon');

    var $couponItem = $('.coupon-item');

    function openCouponDialog(e) {
        var $coupons = $couponItem.map(function(i) {
            var $this = $(this);

            return {
                couponId: $this.data('id'),
                couponName: $this.data('name'),
                amount: $this.data('amount'),
                acquireStatus: $this.data('status'),
                rule4ShortName: $this.data('rule'),
                i: i
            };
        }).get();

        var newCoupons = $.grep($coupons, function(val) {
            return val.acquireStatus === 1;
        });

        var oldCoupons = $.grep($coupons, function(val) {
            return val.acquireStatus === 3;
        });

        var couponData = {
            newList: {
                title: '可以领取的券',
                body: newCoupons

            },
            oldList: {
                title: '已领取的券',
                body: oldCoupons
            }
        };

        new Dialog({
            content: dialogTpl({coupon: couponData}),
            className: 'coupon-big'
        }).show();

        e.stopPropagation();
    }

    function getSku() {
        return $('.size:not(.hide) li.focus').data('sku');
    }

    function imgShow(src) {
        $imgShow.attr('src', src);
    }

    function getCouponAsync(cid) {
        var uid = getUid();  // eslint-disable-line

        if (!uid) {
            return $.Deferred().reject({refer: window.signinUrl()}).promise(); // eslint-disable-line
        }

        return $.getJSON('/product/detail/coupon', {
            couponId: cid
        }).then(function(result) {
            var defer = $.Deferred(); //eslint-disable-line

            if (result.code === 200) {
                defer.resolve();
            } else if (result.code === 400) {
                defer.reject({refer: window.signinUrl()});
            } else {
                defer.reject();
            }

            return defer.promise();
        });
    }

    /**
     * 获取当前选择的商品数目
     * @return [Number]
     */

    function getNum() {
        return +$num.text();
    }

    // 重置Num显示为1
    function resetNum() {
        $num.text('1');

        // +-按钮状态重置
        if (maxStock === 1 || maxStock === 0) {

            // 数目为1/0时
            $plusNum.addClass('dis');
            $minusNum.addClass('dis');
        } else {
            $plusNum.removeClass('dis');
            $minusNum.addClass('dis');
        }
    }

    // 加入购物车和已售罄状态控制
    function switchBtnStatus($color) {
        if ($itemBuy.length === 0) {

            // 全部售罄,按钮状态不变
            return;
        }

        // 选中的商品存量为0或者某个颜色的total为0
        if (maxStock === 0 || ($color && ~~$color.data('total') === 0)) {
            $itemBuy.addClass('hide'); // 隐藏加入购物车、即将开始、立即购买等相同位置的按钮
            $soldOut.removeClass('hide');
        } else {

            // 包括默认的-1情况下
            $itemBuy.removeClass('hide');
            $soldOut.addClass('hide');
        }
    }

    // size warn
    function showSizeWarn() {
        $sizes.not('.hide').children('.size-warn').removeClass('hide');
    }

    // size title
    (function() {
        var $sizeTitleJson = $('#size-title-json'),
            jsonHtml = $sizeTitleJson.html(),
            sizeTitle;

        if (!jsonHtml) {
            return;
        }

        sizeTitle = $.parseJSON(jsonHtml);

        // 数据获取后删除
        $sizeTitleJson.remove();

        $sizes.children('li').each(function() {
            var $this = $(this),
                key = $this.data('name');

            $this.data('title', sizeTitle[key]);
        });
    }());

    require('../plugins/share');
    require('yoho-jquery-qrcode');

    // 颜色
    $('.colors').on('click', 'li', function() {
        var $this = $(this),
            index = $this.index();

        var $imgs;

        // 初始化color-size显示或隐藏
        $colorSizeTip.addClass('hide');

        // 隐藏尺码提示
        $sizeWarn.addClass('hide');

        maxStock = -1;

        if ($this.hasClass('focus')) {

            // 已获取焦点的颜色再次点击,清除尺码的选中
            $sizes.eq(index).children('li').removeClass('focus');
        } else {

            // 未获取焦点,选择尺码
            $this.siblings('.focus').removeClass('focus');
            $this.addClass('focus');

            // 切换图片显示
            $thumbs.not('.hide').addClass('hide');
            $imgs = $thumbs.eq(index).removeClass('hide').find('img');

            if (typeof thumbsLoaded[index] === 'undefined') {

                // trigger layLoad
                lazyLoad($imgs, {
                    event: 'sporty'
                });

                $imgs.trigger('sporty');

                thumbsLoaded[index] = true;
            }

            imgShow($imgs.first().data('shower'));

            // 切换详细信息的颜色显示
            $descColor.text($this.data('color'));

            // 切换尺码显示
            $sizes.not('.hide').addClass('hide').children('li').removeClass('focus');
            $sizes.eq(index).removeClass('hide');

            // 是否展览票
            if (isTicket) {
                $sizes.eq(index).children('li').trigger('click');
                $('.chose-size').addClass('hide');
            }
        }

        resetNum();
        switchBtnStatus($this);
    });

    // 缩略图鼠标移入显示
    $('#thumbs').on('mouseenter', '.thumb', function() {
        imgShow($(this).data('shower'));
    });

    // 尺码
    $size.on('click', 'li', function() {
        var $this = $(this);

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

        maxStock = +$this.data('num');

        $this.siblings('.focus').removeClass('focus');
        $this.addClass('focus');

        $colorSizeTip.html($this.data('title')).removeClass('hide');

        $sizeWarn.addClass('hide');

        switchBtnStatus();

        resetNum();
    }).on('click', '.size-ruler', function() {

        // 尺码帮助

        $('body,html').animate({
            scrollTop: $('.size-info').offset().top
        }, 300);
    });

    // 增加购买数量
    $plusNum.click(function() {
        var num = getNum();

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

        if (maxStock === -1) {
            showSizeWarn();// 显示选择尺码提示
            return;
        }

        // 已售罄
        if (maxStock === 0) {
            return;
        }

        if (num === maxStock - 1) {

            // +按钮不可点
            $(this).addClass('dis');
        }

        // 数目为1时点+则移除-不可点状态
        if (num === 1) {
            $minusNum.removeClass('dis');
        }

        $num.text(num + 1 > maxStock ? maxStock : num + 1);
    }).on('selectstart', function() {
        return false;
    });

    // 减少购买数量
    $minusNum.click(function() {
        var num = getNum();

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

        if (num === 2) {
            $(this).addClass('dis');
        }

        if (num === maxStock) {

            // 恢复+可点
            $plusNum.removeClass('dis');
        }

        $num.text(num - 1 < 0 ? 0 : num - 1);
    }).on('selectstart', function() {
        return false;
    });

    // 限购码
    $('.get-lc:not(.dis)').hover(function() {
        $lcContainer.removeClass('hide');

        if (isEmpty($qrcode)) {
            $qrcode.qrcode({
                render: 'table',
                size: 140,
                text: productUrl(skn)
            });
        }

    }, function() {
        $lcContainer.addClass('hide');
    });

    // 加入购物车
    $addToCart.click(function() {
        if (maxStock === -1) {
            showSizeWarn();
            return;
        }

        // 加入购物车埋點
        yas.givePoint('YB_GDS_DT_ADD_TO_SC', {PRD_ID: getSku(), PRD_NUM: getNum() });

        $.ajax({
            type: 'POST',
            url: '/cart/index/add',
            data: {
                productSku: getSku(),
                buyNumber: getNum()
            }
        }).then(function(data) {
            var code = data.code;
            var alert;

            if (code === 200) {
                $('#type-chose').slideUp(SLIDETIME);
                $('#balance').slideDown(SLIDETIME);

                $('#cart-num').text(data.data.goods_count); // 更新数目
            } else if (code === 500) {
                if (deposit) {
                    alert = new Alert('定金预售商品只能在APP端购买');
                    alert.show();
                }

                if (secKill) {
                    alert = new Alert('秒杀商品只能在APP端购买');
                    alert.show();
                }
            }
        });
    });

    // 收藏
    $('#collect-product').click(function() {
        var $this = $(this),
            cancel,
            coltyp;

        if ($this.hasClass('coled')) {
            cancel = true;
        }

        coltyp = cancel ? 2 : 1;

        // 收藏埋點
        yas.givePoint('YB_COLLECTION_C', {PRD_ID: id, COL_TYP: coltyp });

        $.ajax({
            type: 'POST',
            url: '/product/item/togglecollect',
            data: {
                productId: id,
                type: cancel ? 'cancel' : 'add'
            }
        }).then(function(data) {
            var code = data.code;

            if (code === 200) {

                $this.toggleClass('coled');

                if (cancel) {
                    $this.find('em').text(colTxt.def);
                } else {
                    $this.find('em').text(colTxt.coled);
                }
            } else if (code === 403) {
                location.href = data.data.url;
            }
        });
    }).hover(function() {
        var $this = $(this);

        if ($this.hasClass('coled')) {
            $this.find('em').text(colTxt.hover);
        }
    }, function() {
        var $this = $(this);

        if ($this.hasClass('coled')) {
            $this.find('em').text(colTxt.coled);
        }
    });

    // 继续购物
    $('#keep-shopping').click(function() {
        $('#type-chose').slideDown(SLIDETIME);
        $('#balance').slideUp(SLIDETIME);
    });

    // 电子票立即购买
    $('#buy-ticket').click(function() {
        var sku,
            buyNumber;

        if (maxStock === -1) {
            showSizeWarn();
            return;
        }

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

        sku = $('.size:not(.hide) li.focus').data('sku');
        buyNumber = getNum();

        $.ajax({
            type: 'POST',
            url: '/cart/index/setTicket',
            data: {
                productSku: sku,
                buyNumber: buyNumber
            }
        }).then(function(data) {
            var $ticketForm,
                myAlert;

            if (data.code * 1 === 200) {
                $ticketForm = $('form[name="ticket-form"]');
                $ticketForm.html(
                    '<input name="productSku" value="' + sku + '" />' +
                    '<input name="buyNumber" value="' + buyNumber + '" />'
                );
                $ticketForm.submit();
            } else if (data.code * 1 === 401) {
                document.location.href = data.message;
            } else {
                myAlert = new Alert(data.message);
                myAlert.show();
            }
        });
    });

    // 立即购买
    $('#buy-now').click(function() {
        var sku,
            base,
            myAlert;

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

        if (maxStock === -1) {
            showSizeWarn();
            return;
        }

        base = $(this).data('base');

        // 潮流尖货
        if (!base) {
            myAlert = new Alert('打开APP可抢购该商品哦~~');
            myAlert.show();
            return;
        }

        sku = $sizes.find('.focus').data('sku');

        if (limitCode && sku && skn && base) {
            location.href = base + '?sku=' + sku + '&skn=' + skn + '&limitcode=' + limitCode;
            return;
        }

        if (sku && base) {
            location.href = base + '?product_sku=' + sku;
            return;
        }
    });

    // 按钮鼠标移入效果【dis状态的按钮状态不变】
    $('.buy-btn').mouseover(function() {
        if ($(this).hasClass('dis')) {
            return;
        }

        $(this).addClass('hover');
    }).mouseleave(function() {
        $(this).removeClass('hover');
    });

    // 只有一个尺码(多个或一个颜色)时默认选中第一个未售罄的颜色的第一个尺码
    (function() {
        var hasOnlyOneSize = true,
            i;

        for (i = 0; i < $sizes.length; i++) {
            if ($sizes.eq(i).find('li').length !== 1) {
                hasOnlyOneSize = false;
                break;
            }
        }

        if (hasOnlyOneSize) {
            $sizes.eq($('.colors .focus').index()).find('li').click();
        }
    }());

    // 打开优惠券列表
    $moreCoupon.on('click', openCouponDialog);

    function acquireCoupon($ele) {
        var couponId = $ele.data('id');
        var status = $ele.data('status');
        var i = $ele.data('i');
        var $item = $($couponItem.get(i));

        switch (status) {
            case 1:
                getCouponAsync(couponId).then(function() {
                    $ele.find('.coupon-status').text(oldtatus.txt);
                    $ele.find('.coupon-go').empty().append(oldtatus.html);

                    $item.data('status', 3);
                }).fail(function(err) {
                    if (err.refer) {
                        return window.jumpUrl(err.refer);
                    }
                });
                break;
            default:
                window.jumpUrl(brandDomain);
        }
    }

    // 增加事件
    clickAcquireCouponEvent.add(acquireCoupon);
});

// yas
require('../common');

require('./detail/latest-walk'); // 最近浏览

// 优惠券的领取
$(document).on('click', '.status', function() {
    clickAcquireCouponEvent.fire($(this));
});

// 品牌收藏
$('#brand-favour').click(function() {
    var $this = $(this);

    $.ajax({
        type: 'POST',
        url: '/product/index/favoriteBrand',
        data: {
            brandId: $this.data('id')
        }
    }).then(function(data) {
        if (data.code === 200) {
            $this.toggleClass('coled');
        } else if (data.code === 403) {
            location.href = data.data.url;
        }
    });
});

// 商品详情/材质洗涤切换
$('.description-material').on('click', '.title', function() {
    var $this = $(this),
        index = $this.index();

    var $description = $('.description-content'),
        $material = $('.material-content');

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

    $this.addClass('cur');
    $this.siblings('.cur').removeClass('cur');

    if (index === 0) {

        // 商品信息
        $description.slideDown(SLIDETIME);
        $material.slideUp(SLIDETIME);
    } else {
        $description.slideUp(SLIDETIME);
        $material.slideDown(SLIDETIME);
    }
});

// 售后服务
$('.after-service-switch').click(function() {
    var $this = $(this),
        $content = $this.next('.after-service-content');

    var html = {
        def: '&#xe610;',
        spread: '&#xe615;'
    };

    if ($content.css('display') === 'none') {
        $content.slideDown(SLIDETIME);

        $this.find('.triangle').html(html.spread);
    } else {
        $content.slideUp(SLIDETIME);

        $this.find('.triangle').html(html.def);
    }
});

// 商品详情区的热点
function fetchHotArea() {
    $.ajax({
        type: 'GET',
        url: '/product/detail/hotarea',
        data: {
            productId: id
        }
    }).then(function(html) {
        $('#details-html').prepend(html);

        // 修正热区尺寸使居中
        $('.hot-point-wrap > img').load(function() {
            $(this).parent('.hot-point-wrap').width($(this).width());
        });

        // Bind Hover event
        $('.hot-point').hover(function() {
            $(this).addClass('hover');
        }, function() {
            $(this).removeClass('hover');
        });
    });
}

window.fetchHotArea = fetchHotArea;

// 商品详情图片懒加载
lazyLoad($('#details-html img'));

// 咨询和评价
function fetchComment() {
    var commentPage = {},   // 每个类型的分页页码
        currentType = '7',  // 当前评论展示的类型
        consultPage = 1,
        cNumReady = false;  // 只第一次请求后更新数量

    var commentsTpl = require('hbs/product/comment-item.hbs'),
        consultsTpl = require('hbs/product/consult-item.hbs'),
        $consultsUl = $('#consults-ul'),
        $consultNum = $('.consult-num'),
        loadingComments,
        loadingConsults;

    function loadComments(type) {
        if (loadingComments) {
            return;
        }

        commentPage[type] = commentPage[type] || 1;

        loadingComments = true;
        return $.ajax({
            type: 'GET',
            url: '/product/detail/comment',
            data: {
                productId: id,
                page: commentPage[type],
                filterId: type
            }
        });
    }

    // 购买评价
    function loadAllComments(type) {
        loadComments(type).then(function(data) {
            var res, filter, $ul;

            if (data.code === 200) {
                res = data.data;
                filter = data.filter || [];
                $ul = $('.comments [data-comment-list=' + type + '] ul');

                if (res.length === 0) {
                    $ul.next('.more-wrap').addClass('hide');
                    return;
                }

                if (filter && filter.length && !cNumReady) {
                    cNumReady = true;
                    $(filter).each(function(idx, fit) {
                        if (fit.num) {
                            $('.comments [data-comment-type=' + fit.filterId + '] em').text(fit.num);

                            if (fit.filterId === '7') {  // 全部数量
                                $('.consult-comment .block-title .comment-num').text(fit.num);
                            }
                        }
                    });
                }

                $ul.append(commentsTpl({
                    comments: res
                }));
                commentPage[type]++;
            }
        }).always(function() {
            loadingComments = false;
        });
    }

    // 顾客咨询
    function loadConsults() {
        if (loadingConsults) {
            return;
        }

        loadingConsults = true;

        $.ajax({
            type: 'GET',
            url: '/product/detail/consult',
            data: {
                productId: id,
                page: consultPage
            }
        }).then(function(data) {
            var res;

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

                if (res.length === 0) {
                    $consultsUl.next('.more-wrap').addClass('hide');
                    return;
                }

                // 更新总数显示
                $consultNum.text(res[0].total);

                $consultsUl.append(consultsTpl({
                    consults: res
                }));
                consultPage++;
            }
        }).always(function() {
            loadingConsults = false;
        });
    }

    // 评价和咨询切换
    $('.consult-comment').on('click', '.title', function() {
        var $this = $(this),
            index = $this.index();

        var $comments = $('.comments'),
            $consults = $('.consults');

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

        $this.addClass('cur');
        $this.siblings('.cur').removeClass('cur');

        if (index !== 0) {

            // 咨询
            $consults.slideDown(SLIDETIME);
            $comments.slideUp(SLIDETIME);
        } else {
            $consults.slideUp(SLIDETIME);
            $comments.slideDown(SLIDETIME);
        }
    }).on('click', '.load-more', function() {
        var $this = $(this);

        if ($this.hasClass('load-more-comments')) {
            loadAllComments(currentType);
        } else {
            loadConsults();
        }
    });

    // 我要咨询
    $('#consults-btn').click(function() {

        // TODO:点击我要资讯的时候更新验证码显示
        $('.new-consult').removeClass('hide');
        $('.consult-success').addClass('hide');
    });

    // 提交咨询
    $('#submit-consult').click(function() {
        var $this = $(this),
            $parent = $this.closest('.new-consult'),
            $textarea = $parent.find('.my-consult'),
            content = $.trim($textarea.val());

        var $consultWarn = $parent.find('.consult-warn');

        var pass = true;

        if (content === '') {
            $textarea.addClass('error');
            $consultWarn.removeClass('hide');

            pass = false;
        } else {
            $textarea.removeClass('error');
            $consultWarn.addClass('hide');
        }

        if (pass === false) {
            return;
        }

        $.ajax({
            type: 'POST',
            url: '/product/detail/consult',
            data: {
                productId: id,
                content: content
            }
        }).then(function(data) {
            var code = data.code;

            if (code === 200) {
                $parent.addClass('hide');

                $parent.siblings('.consult-success').removeClass('hide');

                // 清空输入
                $textarea.val('');
            } else if (code === 400) {

                // 跳转登录页
                location.href = data.data.refer;
            }
        });
    });

    // 评论类型的切换
    $('.comments').on('click', '.comment-tabs h2[data-comment-type]', function() {

        var $t = $(this),
            $tabs = $t.closest('.comment-tabs'),
            type = $t.attr('data-comment-type');

        currentType = type;
        $tabs.find('h2[data-comment-type]').removeClass('active');
        $t.addClass('active');

        $('.comments').find('[data-comment-list]').hide();
        $('.comments').find('[data-comment-list=' + type + ']').show();

        if (!commentPage[type]) {    // 首次切换自动加载
            loadAllComments(type);
        }
    });

    loadAllComments(currentType);
    loadConsults();
}

window.fetchComment = fetchComment;

// 购买评价的相关事件
$('.comments').on('click', '.img-preview .img-thumb', function() {
    var $t = $(this);
    var $d = $t.closest('.img-preview').find('.img-detail');

    $d.toggle();
    if ($d.is(':visible')) {
        $t.addClass('active');
    } else {
        $t.removeClass('active');
    }
});
$('.comments').on('click', '.img-preview [data-role="preview-close"]', function() {

    var $img = $(this).closest('.img-preview').find('.img-wrap img'),
        rotate = 0;

    $(this).closest('.img-detail').hide();
    $img.data('rotate', rotate);
    $img.css('transform', 'rotate(' + rotate + 'deg)');
});

$('.comments').on('click', '.img-preview [data-role="preview-left"]', function() {

    var $img = $(this).closest('.img-preview').find('.img-wrap img'),
        rotate = ($img.data('rotate') || 0) * 1;

    rotate -= 90;
    $img.data('rotate', rotate);
    $img.css('transform', 'rotate(' + rotate + 'deg)');
});
$('.comments').on('click', '.img-preview [data-role="preview-right"]', function() {

    var $img = $(this).closest('.img-preview').find('.img-wrap img'),
        rotate = ($img.data('rotate') || 0) * 1;

    rotate -= 90;
    $img.data('rotate', rotate);
    $img.css('transform', 'rotate(' + rotate + 'deg)');
});


function randomString(len) {
    var $chars = 'ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-';

    var maxPos = $chars.length,
        pwd = '',
        i;

    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }

    return pwd;
}

/*
 * 页面加载完
 */
function initPageYas() {
    var loadYas = {};

    loadYas = {
        REC_POSE: 100013,
        REC_ID: randomString(40),
        PRD_ID: $goodsIdArr.join(','),
        PRD_NUM: $goodsIdArr.length,
        ORDER_CODE: '',
        ACTION_ID: 0,
        PAGE_NUM: 1
    };


    // 关键词搜索结果页展示时
    yas.givePoint('YB_CHOOSE_FOR_YOU_Y', loadYas);
}

// 店铺推荐
function loadRecommend() {
    $.ajax({
        type: 'GET',
        url: '/product/detail/recommend',
        data: {
            skn: skn,
            size: 20,
            num: 1
        }
    }).then(function(data) {
        var pro = data.data.products;
        var recommendTpl = require('hbs/product/recommend.hbs');
        var html = recommendTpl(data.data);

        if (data.code === 200) {
            if (pro.length === 0) {
                $('.individual-comment').find('.block-title .title:first-child').addClass('hide');
                $('.individual-comment').find('.block-title').find('.title')
                  .addClass('cur').prev('.sep').addClass('hide');
                $('#recommend-shop').detach();
            }

            $('#recommend-shop').removeClass('hide');
            $('#recommend-content').append(html);
            $('.recommend-slider').slider2({
                shownum: 5,
                isCircle: false
            });
        } else {
            $('.individual-comment').find('.block-title .title:first-child').addClass('hide');
            $('.individual-comment').find('.block-title').find('.title').addClass('cur').prev('.sep').addClass('hide');
            $('#recommend-shop').detach();
        }

        // 页面加载完,埋点
        initPageYas();

        // 点击为您推荐商品埋点
        $('.recommend-slider .img-item').click(function() {
            var $this = $(this);

            var loadYas = {
                REC_POSE: 100013,
                REC_ID: randomString(40),
                PRD_ID: $this.find('.goods-id').html(),
                PRD_NUM: parseInt($this.index(), 10) + 1,
                ORDER_CODE: '',
                ACTION_ID: 1,
                PAGE_NUM: 1
            };


            // 关键词搜索结果页展示时
            yas.givePoint('YB_CHOOSE_FOR_YOU_Y', loadYas);
        });
    });
}

window.loadRecommend = loadRecommend;

// 推荐和浏览切换
$('.individual-comment').on('click', '.title', function() {
    var $this = $(this),
        index = $this.index();

    var $latestWalk = $('.latest-walk'),
        $recommendComment = $('#recommend-shop');

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

    $this.addClass('cur');
    $this.siblings('.cur').removeClass('cur');

    if (index === 0) {
        // 店铺推荐
        $recommendComment.slideDown(SLIDETIME);
        $latestWalk.slideUp(SLIDETIME);
    } else {
        // 最近游览
        fetchLatestWalk();  // eslint-disable-line
        $recommendComment.slideUp(SLIDETIME);
        $latestWalk.slideDown(SLIDETIME);
    }
});

$('.recommend-content').find('.iconfont').mouseenter(function() {
    $(this).addClass('focus');
}).mouseleave(function() {
    $(this).removeClass('focus');
});

// 特殊商品退换货
function fetchReturn() {
    return $.ajax({
        type: 'GET',
        url: '/product/detail/return',
        data: {
            skn: skn
        }
    }).then(function(result) {
        if (result.code === 200) {
            if (result.data.result === 'N') {
                $saleReturn.removeClass().addClass('not-support-saleReturned-service');
            }
        }
    });
}

window.fetchReturn = fetchReturn;

// 首屏加载后,对比数据是否变化,如果变化,重新渲染,重新绑定事件
bindEvent.fire();

// 当前只渲染商品详情页的变化敏感的部分
(function() {
    $.ajax({
        type: 'GET',
        url: '/product/detail/header',
        dataType: 'html',
        data: {
            productId: id,
            md5: md5
        }
    }).then(function(result) {
        if (result) {
            $('.main').html(result);
            bindEvent.fire(); // 重新绑定事件
        }
    });

    $.ajax({
        type: 'GET',
        url: '/product/index/isfav',
        data: {
            brandId: $('#brand-favour').data('id')
        }
    }).then(function(result) {
        if (result.code === 200) {
            $('#brand-favour').addClass('coled');
        }
    });

}());

// 数据懒加载
dataLazyLoad.init({cls: '.datalazyload', threshold: 0});