/**
 * 断码区
 * @author: wsl<shuiling.wang@yoho.cn>
 * @date: 2016/5/20
 */

require('scss/product/sale/break-code-index.page.scss');

let $ = require('yoho-jquery'),
    Swiper = require('yoho-swiper2'),
    lazyLoad = require('yoho-jquery-lazyload'),
    tip = require('js/plugin/tip'),
    filter = require('js/plugin/filter'),
    loading = require('js/plugin/loading');

let $goodsContainer = $('#goods-container'),
    $goodsChildren = $goodsContainer.children(),
    $coatGc = $($goodsChildren.get(0)),
    $trouserGc = $($goodsChildren.get(1)),
    $shoesgc = $($goodsChildren.get(2)),
    $othergc = $($goodsChildren.get(3));

let $filterMask;

let winH = $(window).height(),
    noResult = '<p class="no-result">未找到相关搜索结果</p>';

// 默认筛选条件
let defaultOpt = require('js/common/query-param');

let storeOpt = {};

let $listNav = $('#list-nav'),
    $sizeArea = $('.size-area'),
    $subSize = $('.sub-size'),

    // 导航数据信息
    navInfo = {
        coat: {
            reload: true,
            page: 0,
            end: false
        },
        trouser: {
            reload: true,
            page: 0,
            end: false
        },
        shoes: {
            reload: true,
            page: 0,
            end: false
        },
        other: {
            reload: true,
            page: 0,
            end: false
        }
    },
    $pre = $listNav.find('.active'), // 纪录进入筛选前的active项,初始为选中项
    searching;

let goodsType = ['coat', 'trouser', 'shoes', 'other'];

require('js/common');
require('js/common/suspend-cart'); // 悬浮购物车

// 获取url里面的参数的值
function getUrlParam(name) {
    // 构造一个含有目标参数的正则表达式对象
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');

    // 匹配目标参数
    let r = window.location.search.substr(1).match(reg);

    if (r !== null) {
        return r[2];
    }
    return null; // 返回参数值
}

defaultOpt = $.extend({
    yh_channel: getUrlParam('channel') || defaultOpt.channel || 'boys', // TODO  GO ON!
    saleType: 1,
    currentUrl: location.pathname
}, defaultOpt);

storeOpt = $.extend({}, defaultOpt);

$.each($listNav.find('li'), function(key, item) {
    $(item).addClass(goodsType[key]);
});

$.each($sizeArea, function(key, item) {
    $(item).addClass(goodsType[key]);
});

// 判断导航类型
function judgeType(dom) {
    let navType;

    if (dom.hasClass('coat')) {
        navType = 'coat';
    } else if (dom.hasClass('trouser')) {
        navType = 'trouser';
    } else if (dom.hasClass('shoes')) {
        navType = 'shoes';
    } else {
        navType = 'other';
    }

    return navType;
}

/**
 * 筛选注册的回调,筛选子项点击后逻辑
 * 需要执行search的场景:1.点选筛选项;2.relaod为true时切换导航;3.下拉加载
 * @param opt {type, id}
 */
function search(opt) {
    let setting = {},
        ext = {},
        att,
        nav, navType,
        page,
        i;

    if (searching) {
        return;
    }

    if ($.type(opt) === 'object') {
        opt = [opt];
    }

    if (opt) {

        // 筛选项变更则重置reload为true
        for (att in navInfo) {
            if (navInfo.hasOwnProperty(att)) {
                navInfo[att].reload = true;
            }
        }
        for (i = 0; i < opt.length; i++) {
            switch (opt[i].type) {
                case 'gender':
                    ext = {
                        gender: opt[i].id
                    };
                    break;
                case 'brand':
                    ext = {
                        brand: opt[i].id
                    };
                    break;
                case 'sort':
                    ext = {
                        sort: opt[i].id
                    };
                    break;
                case 'color':
                    ext = {
                        color: opt[i].id
                    };
                    break;
                case 'size':
                    ext = {
                        size: opt[i].id
                    };
                    break;
                case 'price':
                    ext = {
                        price: opt[i].id
                    };
                    break;
                case 'discount':
                    ext = {
                        discount: opt[i].id
                    };
                    break;
                case 'p_d':
                    ext = {
                        p_d: opt[i].id
                    };
                    break;
                case 'ageLevel':
                    ext = {
                        age_level: opt[i].id
                    };
                    break;
                case 'breakSort':
                    ext = {
                        breakSort: opt[i].id
                    };
                    break;
                case 'breakSize':
                    ext = {
                        breakSize: opt[i].id
                    };
                    break;
                default:
                    break;
            }

            $.extend(defaultOpt, ext); // 扩展筛选项
        }
    }

    // 导航类别
    navType = judgeType($pre);

    nav = navInfo[navType];
    page = nav.page + 1;
    if (nav.reload) {
        page = 1;
    } else if (nav.end) {

        // 不需要重新加载并且数据请求结束
        return;
    }

    $.extend(setting, defaultOpt, {
        type: 'stock',
        order: 0,
        page: page
    });

    searching = true;
    loading.showLoadingMask();

    $.ajax({
        type: 'GET',
        url: '/product/sale/search',
        data: setting,
        success: function(data) {
            let $container,
                num;

            switch (navType) {
                case 'coat':
                    $container = $coatGc;
                    break;
                case 'trouser':
                    $container = $trouserGc;
                    break;
                case 'shoes':
                    $container = $shoesgc;
                    break;
                default:
                    $container = $othergc;
                    break;
            }

            if ($container.hasClass('hide')) {
                $container.siblings().addClass('hide');
                $container.removeClass('hide');
            }

            if (data === '') {
                nav.end = true;

                if (nav.reload) {
                    $container.html(noResult);
                }
            } else {
                if (nav.reload) {
                    $container.html(data);
                    lazyLoad($container.find('.lazy'));
                } else {
                    num = $container.find('.good-info').length;
                    $container.append(data);

                    // lazy good-infos who append in
                    lazyLoad($container.find('.good-info:gt(' + (num - 1) + ') .lazy'));
                }
            }

            nav.reload = false;
            nav.page = page;

            searching = false;
            loading.hideLoadingMask();

            window.rePosFooter();
        },
        error: function() {
            tip.show('网络断开连接了~');
            searching = false;
            loading.hideLoadingMask();
        }
    });

}

// 筛选初始化
function filterInit(option) {

    $.ajax({
        type: 'GET',
        url: '/product/sale/filter',
        data: $.extend(defaultOpt, {
            saleType: '1'
        }, option),
        success: function(data) {

            $filterMask && $filterMask.remove();

            $goodsContainer.append(data);

            $filterMask = $('.filter-mask');

            // 初始化filter&注册filter回调
            filter.initFilter({
                fCbFn: search,
                hCbFn: function() {
                    // 切换active状态到$pre上
                    $pre.addClass('active');
                    $pre.siblings('.filter').removeClass('active');
                    $subSize.show();
                },
                missStatus: true
            });
        }
    });
}

setTimeout(function() {
    if ($('.banner-swiper .swiper-slide').length > 1) {
        new Swiper('.swiper-container', {
            observer: true,
            observeParents: true,
            lazyLoading: true,
            lazyLoadingInPrevNext: true,
            loop: true,
            autoplay: 3000,
            autoplayDisableOnInteraction: true,
            paginationClickable: true,
            pagination: '.banner-top .pagination-inner'
        });
    }

    lazyLoad($('.lazy'));
}, 50);

$listNav.bind('contextmenu', function() {
    return false;
});

$listNav.on('touchend touchcancel', function(e) {
    let $this = $(e.target).closest('li'),
        nav, sortId, allSub, navType, $active;

    e.preventDefault();
    if ($this.hasClass('filter')) {

        // 筛选面板切换状态
        if ($this.hasClass('active')) {
            $('.filter-mask').addClass('hide');

            // 点击筛选钱的active项恢复active
            $pre.addClass('active');
            $this.removeClass('active');
            $subSize.show();
        } else {
            $pre = $this.siblings('.active');
            $('.sub-size').hide();
            $pre.removeClass('active');
            $this.addClass('active');
            filter.showFilter();
        }
    } else {

        // 导航类别
        navType = judgeType($this);

        nav = navInfo[navType];

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

            $active = $this.siblings('.active');

            if ($this.attr('class') !== $pre.attr('class')) {
                // 重置筛选项
                filter.resetFilter();
                $('.classify .shower').removeClass('default');

                defaultOpt.breakSort = $this.data('id');
                defaultOpt.breakSize = $this.data('allsub');

                filterInit();
                defaultOpt = $.extend({}, storeOpt);
            }

            $pre = $this; // $pre为除筛选导航的其他导航项,若当前active的为筛选,则把$pre置为当前点击项

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

                // 若之前active项为筛选,则隐藏筛选面板
                filter.hideFilter();
            } else {

                // 切换container显示
                $goodsContainer.children('.container:not(.hide)').addClass('hide');

                switch (navType) {
                    case 'coat':
                        $coatGc.removeClass('hide');
                        break;

                    case 'trouser':
                        $trouserGc.removeClass('hide');
                        break;

                    case 'shoes':
                        $shoesgc.removeClass('hide');
                        break;
                    case 'other':
                        $othergc.removeClass('hide');
                        break;
                    default:
                        break;
                }
            }

            $active.removeClass('active');
            $this.addClass('active');
            sortId = $this.data('id');
            allSub = $this.data('allsub');
            $sizeArea.eq($this.index()).show().siblings().hide();
        }

        if (nav.reload) {
            search([{
                type: 'breakSort',
                id: sortId
            }, {
                type: 'breakSize',
                id: allSub
            }]);
        }
    }
    e.stopPropagation();
});

// 尺码选择事件
$sizeArea.on('click', function(e) {
    let $this = $(e.target).closest('li'),
        index = $this.parents('.size-area').index(),
        $parentType = $listNav.find('li').eq(index),
        nav, sortId, sizeId, navType, $active;

    e.preventDefault();

    if (typeof $this === 'undefined' || $this.length === 0) {
        return;
    }

    // 导航类别
    navType = judgeType($parentType);

    nav = navInfo[navType];

    if ($this.hasClass('active')) {
        return;
    } else {
        nav.reload = true;
        $active = $this.siblings('.active');
        $pre = $parentType; // $pre为除筛选导航的其他导航项,若当前active的为筛选,则把$pre置为当前点击项
        $active.removeClass('active');
        $this.addClass('active');
        sortId = $parentType.data('id');
        sizeId = $this.data('id');
    }

    if (nav.reload) {
        search([{
            type: 'breakSort',
            id: sortId
        }, {
            type: 'breakSize',
            id: sizeId
        }]);
    }
    e.stopPropagation();
});

function scrollHandler() {

    // 当scroll到1/4$goodsContainer高度后继续请求下一页数据
    if ($(window).scrollTop() + winH >
        $(document).height() - 0.25 * $goodsContainer.height() - 50) {
        if (typeof $pre !== 'undefined') {
            search();
        }
    }
}

// srcoll to load more
$(window).scroll(function() {
    window.requestAnimationFrame(scrollHandler);
});

// 初始请求最新第一页数据
$(function() {
    let type = window.queryString.type;
    let selector;
    let $selectNav;

    // type 1: 上装, 3:下装, 6: 鞋装
    if (type && type !== '1') {
        selector = type === '3' ? '.trouser' : '.shoes';
    } else {
        selector = '.coat';
    }
    $selectNav = $listNav.find(selector);
    $selectNav.addClass('active').siblings().removeClass('active');
    $sizeArea.hide();
    $sizeArea.filter(selector).show();

    filterInit({
        breakSort: $selectNav.data('id'),
        breakSize: $selectNav.data('allsub')
    });
    search([{
        type: 'breakSort',
        id: $selectNav.data('id')
    }, {
        type: 'breakSize',
        id: $selectNav.data('allsub')
    }]);
});

$listNav.on('touchstart', 'li', function() {
    $(this).addClass('bytouch');
}).on('touchend touchcancel', function() {
    $listNav.find('li').removeClass('bytouch');
});