filter.js 15.2 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
/**
 * 商品筛选逻辑
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/12/4
 */

var $ = require('yoho-jquery'),
    Handlebars = require('yoho-handlebars');

// 页面隐藏参数
var $hideInfo = $('#page-hide-info'),
    hideInfo = {};

var checkUnicode = {
        unchecked: '&#xe612;',
        checked: '&#xe613;'
    },
    moreUnicode = {
        up: '&#xe607;',
        down: '&#xe60b;'
    };

// 品牌相关变量
var moreBrandLoaded = false,
    $filterBrands = $('#yo-filter-brands'),
    $brandDefault = $('.brand .default'),
    $brandInput,    // $('#brand-search-input'),
    $brandPanel,    // = $('.brand .brand-panel'),
    $brandAttrs,    // = $brandPanel.find('.attr'),
    $brandsIndex,   // = $('.brands-index');
    $brandMore = $('#brand-more'),
    $brandMulti = $('#brand-multi');

var $brandMoreTxt, $brandMoreIcon;

var $sizeMore = $('#size-more'),
    $sizeMoreTxt = $sizeMore.children('em'),
    $sizeMoreIcon = $sizeMore.children('.iconfont'),
    $sizeContent = $sizeMore.siblings('.attr-content');

// 价格相关变量
var $udPrice = $('.ud-price-range'),
    interReg = /^\d+$/,
    $limit, $min, $max, $btn;

// 分类相关变量
var $sortSub = $('.sort-sub-wrap');

// 高级选项相关变量
var $seniorSubWrap = $('.senior-sub-wrap'),
    $seniorAttrWrap = $('.senior-attr-wrap');

var seniorHoverTime, hoveredIndex;

// 尺寸 handlebars 模板
var sizeTmpl = '{{# size}}<a class="attr {{#if checked}}checked{{/if}}" href="{{href}}">{{name}}</a>{{/ size}}',
    sizeCache = {}, // 缓存一下尺寸信息
    $sizeWrap = $('.filter-box .size');

var staticPage = $('.yoho-page.static-list-page').length; // 是否是伪静态页面

if ($hideInfo && $hideInfo.length) {
    hideInfo = $hideInfo.data();
    $hideInfo.remove();
}

sizeTmpl = Handlebars.compile(sizeTmpl);

// 清除checkbox选中状态[页面默认checked不清空]
function clearChecked($checkbox, $checked) {
    $checkbox.each(function() {
        if ($(this).closest('.attr').hasClass('checked')) {
            return;
        }
        $(this).removeClass('checked').html(checkUnicode.unchecked);
    });
    $checked.find('.checkbox').addClass('checked').html(checkUnicode.checked);
}

// 显示更多品牌面板
function brandShowMore() {
    $brandDefault.addClass('hide');
    $brandPanel.removeClass('hide');
}

// 隐藏更多品牌面板
function brandHideMore() {
    $brandPanel.addClass('hide');
    $brandDefault.removeClass('hide');

    // 清除索引状态
    $brandsIndex.children('span').removeClass('hover');
}

// url构造&跳转
function uriLoc(attr, val, uri) {
    var qs = window.queryString(),
        newHref;

    if (staticPage && uri) {
        newHref = uri.replace('{seat}', (val + '').replace('-', '__'));
    } else {
        qs[attr] = val;
        delete qs.page;
        newHref = '?' + decodeURIComponent($.param(qs));
    }

    window.location.href = newHref;
}

function replceStaticUrl(list, uri) {
    var i;

    list = list || [];

    if (staticPage && uri) {
        for (i = 0; i < list.length; i++) {
            list[i].href = uri.replace('{seat}', (list[i].id + '').replace('-', '__'));
        }
    }

    return list;
}

// 隐藏高级选项面板
function hideSeniorPanel() {
    $seniorSubWrap.children('.senior-sub:eq(' + hoveredIndex + ')').addClass('hide');
    $seniorAttrWrap.children('.attr:eq(' + hoveredIndex + ')').removeClass('hover');
    hoveredIndex = -1;
}

// 屏蔽筛选项双击文字选中
$('.filter-box').on('selectstart', '.attr, .brands-index span', function() {
    return false;
});

// 【分类】
$('.sort-pre').on('click', 'li', function() {
    var $this = $(this),
        index = $this.index(),
        id = $this.data('id');

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

        // 选中时,再次点击取消选中
        $this.removeClass('active');
        $sortSub.children(':eq(' + index + ')').addClass('hide');
        $sizeWrap.addClass('hide');
        return;
    }

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

    $sortSub.children(':not(.hide)').addClass('hide');
    $sortSub.children(':eq(' + index + ')').removeClass('hide');

    if (!$sizeWrap.data('load')) {
        if (sizeCache[id]) {
            $sizeWrap.find('.attr-content').html(sizeCache[id]);
            $sizeWrap.removeClass('hide');
        } else {
            $.ajax({
                url: '/product/search/sortSize',
                data: {
                    msort: id
                }
            }).then(function(res) {
                if ($.type(res) === 'array' && res.length) {
                    sizeCache[id] = sizeTmpl({
                        size: res
                    });
                    $sizeWrap.find('.attr-content').html(sizeCache[id]);
                    $sizeWrap.removeClass('hide');
                } else {
                    $sizeWrap.addClass('hide');
                }
            });
        }
    }
});

// 【品牌】
if ($brandMore.length > 0) {
    $brandMoreTxt = $brandMore.children('em');
    $brandMoreIcon = $brandMore.children('.iconfont');
}

// 【品牌】加载更多品牌数据
function checkMoreBrands(callback) {

    // /product/search/filter/brands?callback=?
    var url = '//search.yohobuy.com/product/search/filter/brands?callback=?';
    var brandsHtml;
    var params = window.queryString();
    var $changeKey = $('#rec-query-key');

    // 直出brands list取消异步加载,目前只用于5.6全球购商品列表
    if (!moreBrandLoaded && $filterBrands.find('.brand-panel').length) {
        moreBrandLoaded = true;

        // init brand vars
        $brandInput = $filterBrands.find('#brand-search-input');
        $brandPanel = $filterBrands.find('.brand-panel');
        $brandAttrs = $brandPanel.find('.attr');
        $brandsIndex = $('.brands-index');
    }

    if (staticPage) { // 伪静态化页面参数特殊处理
        params = {pathname: window.location.pathname};
    }

    if (params.query && $changeKey.length) {
        params.query = $changeKey.text();
    }

    if (hideInfo) {
        params = $.extend(params, hideInfo);
    }

    if (moreBrandLoaded === 'loading') {
        return;
    } else if (!moreBrandLoaded) {

        moreBrandLoaded = 'loading';
        $.getJSON(url, params, function(jsonData) {
            var resData, seatUrl;

            if (jsonData.code !== 200) {
                return;
            }

            resData = jsonData.data;

            if (resData) {
                seatUrl = $filterBrands.data('url');

                replceStaticUrl(resData.brandsShow, seatUrl);

                brandsHtml = Handlebars.compile($('#yo-brands-tpl').html() || '');
                $filterBrands.find('.attr-content [data-role=all-brand]').html(brandsHtml(resData));
            }

            moreBrandLoaded = true;

            // init brand vars
            $brandInput = $filterBrands.find('#brand-search-input');
            $brandPanel = $filterBrands.find('.brand-panel');
            $brandAttrs = $brandPanel.find('.attr');
            $brandsIndex = $('.brands-index');

            return callback && callback();
        });
    } else {
        return callback && callback();
    }
}

// 【品牌】多选
$brandMulti.click(function() {

    checkMoreBrands((function() {

        if ($brandPanel.css('display') === 'none') {

            // 显示品牌面板
            $brandMore.trigger('click');
        }

        brandShowMore();
        $brandPanel.removeClass('hide').addClass('multi'); // 显示出checkbox
        $(this).addClass('hide');

        // 隐藏更多按钮
        $brandMore.addClass('hide');
    }).bind(this));
});

// 【品牌】更多
$brandMore.click(function() {

    checkMoreBrands((function() {
        var $this = $(this);

        if ($this.hasClass('more')) {
            brandHideMore();

            $brandMoreTxt.text('更多');
            $brandMoreIcon.html(moreUnicode.down);

            // 清空搜索框和搜索结果
            $brandInput.val('').trigger('keyup');
        } else {
            brandShowMore();

            $brandMoreTxt.text('收起');
            $brandMoreIcon.html(moreUnicode.up);
        }

        $(this).toggleClass('more');
    }).bind(this));
});

// 【品牌】索引
$filterBrands.on('mouseenter', '.brands-index span', function() {
    var $this = $(this),
        index = $this.data('index');

    if ($this.hasClass('hover')) {
        return;
    }
    setTimeout(function() {
        $this.siblings('span.hover').removeClass('hover');
        $this.addClass('hover');

        if ($this.index() === 0) {
            // 全部
            $brandAttrs && $brandAttrs.removeClass('hide');
        } else {
            $brandAttrs && $brandAttrs.addClass('hide').filter('[data-index=' + index + ']').removeClass('hide');
        }
    }, 120);
});

// 【品牌】搜索
$filterBrands.on('keyup', '#brand-search-input', function() {
    var val = $(this).val().toLowerCase();

    if (val === '') {
        $brandAttrs.removeClass('hide');
    } else {
        $brandAttrs.addClass('hide').filter('[data-key*="' + val + '"]').removeClass('hide');
    }
});

// 【品牌】多选确定
$filterBrands.on('click', '#brand-multi-ok', function() {
    var val = [];

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

    $brandPanel.find('span.checked').each(function() {
        val.push($(this).data('id'));
    });

    uriLoc('brand', val.join(','), $filterBrands.data('url'));
});

// 【品牌/高级选项】多选取消
$filterBrands.on('click', '.multi-select-cancel', function() {
    var $panel = $(this).closest('.multi');

    if ($panel.hasClass('brand-panel')) {

        $brandMulti.removeClass('hide'); // 显示多选按钮
        $brandMore.trigger('click');

        // 显示出更多按钮
        $brandMore.removeClass('hide');

        // 清空搜索框和搜索结果
        $brandInput.val('').trigger('keyup');
        brandHideMore();
    }

    $panel.addClass('hide').removeClass('multi');
    clearChecked($panel.find('.checkbox.checked'), $panel.find('.attr.checked')); // 清除选中状态

    // 确定按钮状态恢复dis
    $(this).siblings('.multi-select-ok').addClass('dis');
});

// 【品牌/高级选项】checkbox
$filterBrands.on('click', '.check-container .attr', function() {
    var $this = $(this),
        $check = $this.find('.checkbox'),
        $btnOk = $this.closest('.brand-panel, .senior-sub').find('.multi-select-ok');

    $check.toggleClass('checked');

    if ($check.hasClass('checked')) {
        $check.html(checkUnicode.checked);
    } else {
        $check.html(checkUnicode.unchecked);
    }

    // 更新按钮状态
    if ($check.hasClass('checked') ||
        $this.siblings('.attr').find('.checked').length > 0) {
        $btnOk.removeClass('dis');
    } else {
        $btnOk.addClass('dis');
    }
});

// 【品牌/高级选项】当多选时阻止链接默认跳转
$('.brand, .senior').on('click', '.attr > a', function(e) {
    if ($(this).closest('.multi').length > 0) {
        e.preventDefault();
    }
});

// 已选中的条件,点击不刷新
$('.filter-box').on('click', 'li.checked, a.checked', function(e) {
    e.preventDefault();
});

// 【价格】用户定义价格处理
if ($udPrice.length > 0) {
    $limit = $udPrice.find('.limit');
    $min = $limit.filter('.min');
    $max = $limit.filter('.max');
    $btn = $udPrice.find('.price-sure');

    // 【价格】输入
    $limit.keyup(function() {
        var thisPrice = $.trim($(this).val()),
            isPriInt = interReg.test(thisPrice),
            intPrice,
            min,
            max;

        if (!isPriInt) {
            intPrice = parseInt(thisPrice, 10);
            $(this).val(isNaN(intPrice) ? '' : intPrice);
        }

        min = $.trim($min.val());
        max = $.trim($max.val());

        if (min !== '' || max !== '') {
            $btn.removeClass('hide');
        } else {
            $btn.addClass('hide');
        }
    });

    // 【价格】多项查询
    $btn.click(function() {
        var min = $.trim($min.val()),
            max = $.trim($max.val()),
            tmp;

        // 对于min大于max的情况,交换位置
        if (min !== '' && max !== '' && +min > +max) {
            tmp = max;
            max = min;
            min = tmp;
        }

        uriLoc('price', min + ',' + max, $(this).data('url'));
    });
}

// 【高级选项】鼠标移入显示子项
$seniorAttrWrap.on('mouseenter', '.attr', function() {
    var $this = $(this);
    var index = $this.index();

    if ($this.hasClass('no-sub')) {
        return;
    }
    $this.addClass('hover').siblings().removeClass('hover');

    $seniorSubWrap.children('.senior-sub:eq(' + index + ')').removeClass('hide').siblings().addClass('hide');
}).on('mouseleave', '.attr', function() {
    var $this = $(this),
        index = $this.index();

    if ($this.hasClass('no-sub')) {
        return;
    }

    hoveredIndex = index;

    seniorHoverTime = setTimeout(function() {
        hideSeniorPanel();
    }, 100);
});

$sizeMore.click(function() {
    var $this = $(this),
        $wrap = $this.siblings('.attr-content');

    if ($wrap.hasClass('more')) {
        $sizeMoreTxt.text('更多');
        $sizeMoreIcon.html(moreUnicode.down);
        $wrap.scrollTop(0);
    } else {
        $sizeMoreTxt.text('收起');
        $sizeMoreIcon.html(moreUnicode.up);
    }

    $wrap.toggleClass('more');
});

// 【高级选项】多选
$('.senior-sub').on('click', '.multi-select', function() {
    $(this).closest('.senior-sub').addClass('multi');
}).on('click', '.check-container .attr', function() {
    var $this = $(this),
        $check = $this.find('.checkbox'),
        $btnOk = $this.closest('.senior-content').find('.multi-select-ok');

    $check.toggleClass('checked');

    if ($check.hasClass('checked')) {
        $check.html(checkUnicode.checked);
    } else {
        $check.html(checkUnicode.unchecked);
    }

    // 更新按钮状态
    if ($check.hasClass('checked') ||
        $this.siblings('.attr').find('.checked').length > 0) {
        $btnOk.removeClass('dis');
    } else {
        $btnOk.addClass('dis');
    }
}).on('click', '.multi-select-ok', function() {
    var $btn2 = $(this),
        $sub = $btn2.closest('.senior-sub'),
        val = [];

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

    $sub.find('span.checked').each(function() {
        val.push($(this).data('id'));
    });

    uriLoc($sub.data('attr'), val.join(','), $sub.data('url'));
}).on('click', '.multi-select-cancel', function() {
    var $panel = $(this).closest('.multi');

    $panel.removeClass('multi');
    clearChecked($panel.find('.checkbox.checked'), $panel.find('.attr.checked')); // 清除选中状态

    // 确定按钮状态恢复dis
    $(this).siblings('.multi-select-ok').addClass('dis');
}).on('mouseenter', function() {
    clearTimeout(seniorHoverTime);
}).on('mouseleave', function() {
    hideSeniorPanel();
});

// 资源位三张四张样式调整
(function rejustActivityEntryDisplay() {
    var activityEntryNumb = $('.activity-entry').find('a').length,
        activityItemWidth = (1150 - (activityEntryNumb - 1) * 10) / activityEntryNumb;

    $('.activity-entry .entry-item').css('width', activityItemWidth);

}());

(function setSizeMoreBtnDisplay() {
    var bh = $sizeContent.height(),
        ch = $sizeContent.children().height();

    if (ch > bh) {
        $sizeMore.removeClass('hide');
    }
}());