/**
 * 品牌店铺首页
 */

require('product/shop/shop.page.css');
require('./shop/coupon');

let $ = require('yoho-jquery'),
    lazyLoad = require('yoho-jquery-lazyload'),
    Swiper = require('yoho-swiper');

let myScroll,
    nav1H,
    $nav1 = $('#pos-nav'),
    $nav2 = $('#pos-list');

let tip = require('plugin/tip'),
    filter = require('plugin/filter'),
    loading = require('plugin/loading');

let $subNav = $('.home-sub-nav'),
    $collect = $('#collect'),
    $goodsContainer = $('#goods-container'),
    $goodsChildren = $goodsContainer.children(),
    $defaultgc = $goodsContainer.children('.default-goods'),
    $ngc = $($goodsChildren.get(0)),
    $pgc = $($goodsChildren.get(1)),
    $dgc = $($goodsChildren.get(2)),
    $popularity = $($goodsChildren.get(3)),
    $newList = $('.new-list'),
    shopId = $('input[name="shop_id"]').val(),
    appVersion = $('input[name="app_version"]').val(),
    brand = $('input[name="brand"]').val(),
    coverChannel = $('input[name="coverChannel"]').val(),
    favId = $('input[name="favId"]').val(),
    $dropList = $('.drop-list'),
    uid = window.queryString.uid;

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

require('common');
require('common/invite-share');

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

// pagecache判断app设置cookie,判断是否收藏
(function() {
    let param = location.search;
    let isApp = param.indexOf('app_version') > -1 || param.indexOf('appVersion') > -1;

    // 不阻塞字体文件加载
    setTimeout(function() {
        if (isApp) {
            $.ajax({
                type: 'GET',
                url: '/product/index/shopAppCookie',
                xhrFields: {
                    withCredentials: true
                },
                error: function() {
                    tip.show('网络断开连接了~');
                }
            });
        }

        if ($('.not-collect').data('switch') !== true) {
            $.ajax({
                type: 'GET',
                url: location.protocol + '//m.yohobuy.com/product/index/shopFav',
                xhrFields: {
                    withCredentials: true
                },
                data: {
                    shopId: $('.shopId').val(),
                    uid: uid
                },
                success: function(data) {
                    if (data.collect) {
                        $collect.attr('class', 'already-collect');
                    }
                },
                error: function() {
                    tip.show('网络断开连接了~');
                }
            });
        }
        if ($('.popularity-title').data('skns')) {
            $.ajax({
                type: 'GET',
                url: '/product/new/shop/hotlist?app_version=' + appVersion,
                xhrFields: {
                    withCredentials: true
                },
                data: {
                    skns: $('.popularity-title').data('skns'),
                },
                success: function(data) {
                    $('.product-warp>.goods-container').html(data);
                },
                error: function() {
                    tip.show('网络断开连接了~');
                }
            });
        }
        $.ajax({
            type: 'GET',
            url: '/product/search/filter',
            data: {
                shop_id: $('.shopId').val(),
                order: '0',
                channel: defaultOpt.channel
            },
            xhrFields: {
                withCredentials: true
            },
            success: function(data) {
                $('.shop-index').after(data);

                // 初始化filter&注册filter回调
                filter.initFilter({
                    fCbFn: search, // eslint-disable-line
                    hCbFn: function() {
                        $('.filter ').removeClass('active');

                        // 切换active状态到$pre上
                        // $pre.addClass('active');

                        $('#pos-list').addClass('hide');

                        // $pre.siblings('.filter').removeClass('active');
                        scrollHandler(); // eslint-disable-line
                        subNavScrollTo(); // eslint-disable-line
                    }
                });
            }
        });
    }, 0);

}());


let $listNav = $('#list-nav'),

    // 导航数据信息
    navInfo = {
        new: {
            order: 1,
            reload: true,
            page: 1,
            end: false
        },
        default: {
            order: 0,
            reload: true,
            page: 0,
            end: false
        },
        hot: {
            order: 1,
            reload: true,
            page: 1,
            end: false
        },
        newest: {
            order: 0,
            reload: true,
            page: 0,
            end: false
        },
        price: {
            order: 1,
            reload: true,
            page: 0,
            end: false
        },
        discount: {
            order: 1,
            reload: true,
            page: 0,
            end: false
        },
        popularity: {
            order: 0,
            reload: true,
            page: 0,
            end: false
        }
    },
    $pre = $listNav.find('.active'), // 纪录进入筛选前的active项,初始为选中项
    searching;

let viewType = 1, // 1-首页,2-上新,3-人气
    listCount = $('.category-list li').length,
    listModValue = 4 - listCount % 4,
    listIndex;

// 焦点效果
if ($('.banner-swiper').find('li').size() > 1) {
    new Swiper('.banner-swiper', {
        lazyLoading: true,
        lazyLoadingInPrevNext: true,
        loop: true,
        autoplay: 3000,
        autoplayDisableOnInteraction: false,
        paginationClickable: true,
        slideElement: 'li',
        pagination: '.banner-top .pagination-inner'
    });
}

if ($('.multi-browse').find('li').size() > 1) {
    new Swiper('.multi-browse', {
        lazyLoading: true,
        lazyLoadingInPrevNext: true,
        lazyLoadingOnTransitionStart: true,
        grabCursor: true,
        slidesPerView: 'auto',
        slideElement: 'li',
        watchSlidesVisibility: true
    });
}

// 根据热门品类的个数来改变样式展示
//
if ($('.category-list li').length % 4 !== 0) {
    $('.category-list li:last-child').addClass('category-list-last-li');
}

if ($('.category-list li').length < 4) {
    $('.category-list').addClass('category-list-top-board');
    $('.category-list').find('.buriedpoint').addClass('category-list-only-one-row');
} else if ($('.category-list li').length >= 5) {
    for (listIndex = listModValue; listIndex >= 0; listIndex--) {
        $('.category-list li').eq(listCount - 4 + listIndex - 1).addClass('category-list-last-full-row');
    }
}

function getPageGoods(info) {
    let nav, navType;

    if (searching) {
        return;
    }

    navType = info.data.type;
    nav = navInfo[navType];

    // 不需要重新加载并且数据请求结束
    if (nav.end) {
        return;
    }

    if (info.data && coverChannel) {
        info.data.coverChannel = coverChannel;
    }

    searching = true;
    $.ajax({
        type: 'GET',
        url: info.url,
        data: info.data,
        success: function(data) {
            if (data === '' || (data.list && data.list.length <= 0)) {
                nav.end = true;
            }
            info.callBack(data);
        },
        error: function() {
            tip.show('网络断开连接了~');
            searching = false;
        }
    });
}

function getParam(req) {
    if (brand) {
        req.data.brand = brand;
    }

    if (shopId) {
        req.data.shop_id = shopId;
    }
}

function newData(callback) {
    let req = {};

    req.url = '/product/search/search';
    req.data = {
        type: 'new',
        order: '0',
        page: navInfo.new.page,
        tagNew: '1',
        appVersion: appVersion
    };

    getParam(req);

    req.callBack = function(data) {
        $('#new-arrival').append(data);
        navInfo.new.page++;
        lazyLoad($('#new-arrival .lazy'));
        searching = false;
        callback && $.isFunction(callback) && callback();
    };
    let result = getPageGoods(req);

    if (!result) {
        return callback && callback();
    }
}

function hotData(callback) {
    let req = {};

    req.url = '/product/search/search';
    req.data = {
        type: 'hot',
        order: '1',
        page: navInfo.hot.page,
        showTag: '1',
        appVersion: appVersion
    };

    getParam(req);

    req.callBack = function(data) {
        $('#popularity').append(data);
        navInfo.hot.page++;
        lazyLoad($('#popularity .lazy'));
        searching = false;
        callback && $.isFunction(callback) && callback();
    };
    let result = getPageGoods(req);

    if (!result) {
        return callback && callback();
    }
}

function tabChange(dom, index) {
    let li = dom.eq(index);

    dom.removeClass('active color');
    li.addClass('active color');
}


// 首页导航
(function(nav, posNav, main) {
    let scrollToNav1 = function() {
        setTimeout(function() {
            window.scrollTo(0, $('#nav').offset().top + 5);
        }, 100);
    };

    $(nav + ' li, ' + posNav + ' li').not('li.all-goods').on('touchstart', function() {
        let isPos = $(this).parent().attr('id') === 'pos-nav';
        let index = $(this).index(),
            activeTab = $(this).attr('tab');

        if ($('.filter-mask').length && !$('.filter-mask').hasClass('hide')) {
            return;
        }

        $nav1.removeClass('fixed-top');
        tabChange($(nav + ' li'), index);
        tabChange($(posNav + ' li'), index);
        $(main).hide();
        $('#' + activeTab).fadeIn();
        if (activeTab === 'new-arrival') {
            newData(isPos ? scrollToNav1 : function() {});
            viewType = 2;
        } else if (activeTab === 'popularity') {
            hotData(isPos ? scrollToNav1 : function() {});
            viewType = 3;
        } else if (activeTab === 'home-page') {
            $nav1.removeClass('fixed-top absolute');
            $nav2.removeClass('fixed-top absolute');
            viewType = 1;
            isPos && scrollToNav1();
        }
    });
}('#nav', '#pos-nav', '.main'));




function scrollHandler() {
    if (!$('.filter-mask').hasClass('hide')) {
        return;
    }
    let sTop = $(document).scrollTop(),
        scH = $('#scroller').outerHeight(),
        nav1OffsetTop = $('#nav').length ? $('#nav').offset().top : 0,
        nav2OffsetTop = $('#list-nav').length ? $('#list-nav').offset().top : 0;

    // 分页加载店铺商品列表
    if (sTop > scH - winH * 2 && viewType === 1) {
        if (typeof $pre !== 'undefined') {
            search({ // eslint-disable-line
                type: 'shop_id',
                id: shopId,
                brand: brand,
                url: '/product/search/search',
                nextPage: true
            });
        }
    }

    // 分页加载“上新”和“人气”商品数据
    if (sTop + winH * 2 > scH) {
        switch (viewType) {
            case 2:
                newData();
                break;
            case 3:
                hotData();
                break;
            default:
                break;
        }
    }

    if (sTop > nav2OffsetTop && $('#list-nav').length) {
        if ($('#home-page').is(':hidden')) {
            return false;
        }
        $nav2.removeClass('hide');
        $nav1.addClass('hide');
        if (!$newList.hasClass('hide')) {
            $newList.addClass('classics');
        }
    } else if (sTop > nav1OffsetTop && $('#nav').length) {
        $nav1.removeClass('hide');
        $nav2.addClass('hide');
        if (!$newList.hasClass('hide')) {
            $newList.removeClass('classics');
        }
    } else {
        $nav1.addClass('hide');
        $nav2.addClass('hide');
    }
}

// window ready 后重新refresh iscroll
$(window).ready(function() {
    // myScroll && myScroll.refresh();
    nav1H = $('#nav').outerHeight();


    $(document).scroll(scrollHandler);
    lazyLoad($('img.lazy'));
});

function bindGoodThumbClick() {
    $(document).trigger('rebindBpEvent');
}

function search(opt, callback) {
    let setting = {},
        ext,
        att,
        nav, navType,
        page;

    if (searching) {
        return;
    }

    if (!opt.url) {
        opt.url = '/product/search/search';
    }

    $pre = $listNav.find('.active').eq(0);

    if (!opt.nextPage) {

        // 筛选项变更则重置reload为true
        for (att in navInfo) {
            if (navInfo.hasOwnProperty(att)) {
                navInfo[att].reload = true;
            }
        }

        $listNav.children('.active').removeClass('active');
        $pre.addClass('active');
        if (opt.hasOwnProperty('id')) {
            switch (opt.type) {
                case 'shop_id':
                    ext = {
                        shop_id: opt.id
                    };
                    break;
                case 'gender':
                    ext = {
                        gender: opt.id
                    };

                    ext.coverChannel = opt.id;
                    break;
                case 'brand':
                    ext = {
                        brand: opt.id
                    };
                    break;
                case 'sort':
                    ext = {
                        sort: opt.id
                    };
                    break;
                case 'color':
                    ext = {
                        color: opt.id
                    };
                    break;
                case 'size':
                    ext = {
                        size: opt.id
                    };
                    break;
                case 'price':
                    ext = {
                        price: opt.id
                    };
                    break;
                case 'discount':
                    ext = {
                        discount: opt.id
                    };
                    break;
                case 'ageLevel':
                    ext = {
                        age_level: opt.id
                    };
                    break;
                default:
                    break;
            }
            $.extend(defaultOpt, ext); // 扩展筛选项
        }
    }

    // 导航类别
    if ($pre.hasClass('new')) {
        navType = 'newest';
    } else if ($pre.hasClass('price')) {
        navType = 'price';
    } else if ($pre.hasClass('discount')) {
        navType = 'discount';
    } else if ($pre.hasClass('default')) {
        navType = 'default';
    } else if ($pre.hasClass('popu')) {
        navType = 'popularity';
    }

    nav = navInfo[navType];

    page = nav.page + 1;
    if (nav.reload) {
        page = 1;
    } else if (nav.end) {

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

    // 封面图,defaultOpt对象也有可能包含coverChannel,但defaultOpt优先级高
    if (coverChannel) {
        setting.coverChannel = coverChannel;
    }

    $.extend(setting, defaultOpt, {
        type: navType,
        order: nav.order,
        page: page,
        appVersion: appVersion
    });

    if (brand) {
        setting.brand = brand;
    }
    if (shopId) {
        setting.shop_id = shopId;
    }

    searching = true;
    loading.showLoadingMask();

    $.ajax({
        type: 'GET',
        url: opt.url ? opt.url : '',
        data: setting,
        success: function(data) {
            let $container,
                num;

            switch (navType) {
                case 'newest':
                    $container = $ngc;
                    break;
                case 'price':
                    $container = $pgc;
                    break;
                case 'discount':
                    $container = $dgc;
                    break;
                case 'default':
                    $container = $defaultgc;
                    break;
                case 'popularity':
                    $container = $popularity;
                    break;
                default:
                    break;
            }

            if (data === '' || (data.list && data.list.length <= 0)) {
                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);
                    lazyLoad($container.find('.good-info:gt(' + (num - 1) + ') .lazy'));
                }
            }

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

            searching = false;
            loading.hideLoadingMask();

            window.rePosFooter();

            // myScroll && myScroll.refresh();
            // reNav1Pos();

            bindGoodThumbClick();
            setTimeout(function() {
                callback && typeof callback === 'function' && callback();
            }, 0);
        },
        error: function() {
            tip.show('网络断开连接了~');
            searching = false;
            loading.hideLoadingMask();
            callback && typeof callback === 'function' && callback();
        }
    });
}


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

$newList.on('touchstart', 'li', function(e) {
    let navType, bpIdData = $(this).attr('data-bp-id') || '';

    e.preventDefault();
    if ($(this).hasClass('new')) {
        navType = 'newest';
    } else if ($(this).hasClass('default')) {
        navType = 'default';
    } else if ($(this).hasClass('sale')) {
        navType = 'sale';
    }

    $(document).trigger('shouldSendBpData', [bpIdData]);

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

    switch (navType) {
        case 'newest':
            $ngc.removeClass('hide');
            break;

        case 'price':
            $pgc.removeClass('hide');
            break;

        case 'discount':
            $dgc.removeClass('hide');
            break;

        case 'default':
            $defaultgc.removeClass('hide');
            break;

        default:
            break;
    }

    let nav = navInfo[navType];

    if (nav.reload) {
        search({
            type: 'shop_id',
            id: shopId,
            brand: brand,
            appVersion: appVersion,
            url: '/product/search/search',
            nextPage: false
        }, function() {
        });
    }
    subNavScrollTo(); // eslint-disable-line
    e.stopPropagation();

});

function subNavScrollTo() {
    setTimeout(function() {
        window.scrollTo(0, $('#list-nav').offset().top + 5);
    }, 100);
}

$dropList.on('touchend', 'li', function(e) {
    let navType,
        nav,
        bpIdData = $(this).attr('data-bp-id') || '',
        $firstLiDom = $subNav.find('li.first-li-more');

    e.preventDefault();

    if ($(this).hasClass('default')) {
        navType = 'default';
    } else {
        navType = 'discount';
    }

    if ($(this).hasClass('active')) {
        $dropList.addClass('hide');
        return;
    }

    $(this).addClass('active').siblings().removeClass('active');
    $firstLiDom.find('.nav-txt').text($(this).data('text'));
    $firstLiDom.attr('data-bp-id', bpIdData).addClass('active').siblings().removeClass('active');
    $subNav.find('.first-li-more').removeClass('new default sale discount').addClass(navType);

    nav = navInfo[navType];

    if ($(this).hasClass('asc')) {
        nav.order = 1;
        nav.reload = true;
        $('.drop-list').find('.asc').addClass('active').siblings().removeClass('active');
    } else {
        nav.order = 0;
        nav.reload = true;

        if ($(this).hasClass('dec')) {
            $('.drop-list').find('.dec').addClass('active').siblings().removeClass('active');
        } else {
            $('.drop-list').find('.default').addClass('active').siblings().removeClass('active');
        }
    }

    $defaultgc.removeClass('hide');

    $goodsContainer.children('.container:not(.hide)').addClass('hide');

    switch (navType) {
        case 'newest':
            $ngc.removeClass('hide');
            break;

        case 'price':
            $pgc.removeClass('hide');
            break;

        case 'discount':
            $dgc.removeClass('hide');
            break;

        case 'default':
            $defaultgc.removeClass('hide');
            break;

        case 'popularity':
            $popularity.removeClass('hide');
            break;

        default:
            break;
    }

    $pre = $firstLiDom;

    if (nav.reload) {
        $(document).trigger('shouldSendBpData', [bpIdData]);
        search({filtering: true});
    }

    if (!$('.filter-mask').hasClass('hide')) {
        filter.hideFilter();
    }

    $dropList.addClass('hide');
});

$subNav.on('touchend touchcancel', function(e) {
    let $this = $(e.target).closest('li'),
        cname,
        nav,
        navType,
        $active;
    let bpIdData = $this.attr('data-bp-id') || '';

    e.preventDefault();
    $(document).trigger('shouldSendBpData', [bpIdData]);

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

    if ($this.hasClass('first-li-more') && $this.hasClass('active')) {

        if (!$this.parent().hasClass('list-nav')) {
            $dropList = $('.pos-drop');
        } else {
            $dropList = $('.first-list');
        }

        $dropList.toggleClass('hide');

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

        return true;
    }

    // 最新li 列表
    $newList.addClass('hide');

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

        // 筛选面板切换状态
        if ($this.hasClass('active') && !$('.filter-mask').hasClass('hide')) {
            $('.home-sub-nav>li.filter').removeClass('active');
            $this.removeClass('active');
            filter.hideFilter();
        } else {
            $('.home-sub-nav>li.filter').addClass('active');
            $this.addClass('active');

            filter.showFilter();

            if ($this.closest('.pos-list').length > 0) {
                $('.filter-mask').addClass('call-by-fix').css('top', '');
            } else {
                $('.filter-mask').removeClass('call-by-fix').css('top', $this.offset().top + nav1H);
            }
            if ($('#pos-list').hasClass('hide')) {
                $('#pos-list').removeClass('hide');
            }
        }
        subNavScrollTo();
    } else {

        filter.hideFilter();// 隐藏面板

        if ($this.hasClass('new')) {
            cname = '.new';
            navType = 'newest';
        } else if ($this.hasClass('price')) {
            cname = '.price';
            navType = 'price';
        } else if ($this.hasClass('discount')) {
            cname = '.discount';
            navType = 'discount';
        } else if ($this.hasClass('default')) {
            cname = '.default';
            navType = 'default';
        } else if ($this.hasClass('popu')) {
            cname = '.popu';
            navType = 'popularity';
        }

        nav = navInfo[navType];
        let reloadCb = function() {
            $goodsContainer.children('.container:not(.hide)').addClass('hide');
            switch (navType) {
                case 'newest':
                    $ngc.removeClass('hide');
                    break;

                case 'popularity':
                    $popularity.removeClass('hide');
                    break;

                case 'price':
                    $pgc.removeClass('hide');
                    break;

                case 'discount':
                    $dgc.removeClass('hide');
                    break;
                case 'default':
                    $defaultgc.removeClass('hide');
                    break;
                default:
                    break;
            }
        };

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

            // 最新无排序切换
            if ($this.hasClass('new') || $this.hasClass('popu')) {
                return;
            }

            if ($this.hasClass('price') || $this.hasClass('discount')) {
                $this = $subNav.find(cname);

                // 价格/折扣切换排序状态
                $this.find('.icon > .iconfont').toggleClass('cur');
                nav.reload = true; // 重置reload,HTML会被替换为逆序的HTML
                nav.order = nav.order === 0 ? 1 : 0; // 切换排序

            }
        } else {
            $active = $subNav.find('.active');

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

                // 若之前active项为筛选,则隐藏筛选面板
                filter.hideFilter();
            }
            $subNav.children().removeClass('active');
            $subNav.find(cname).addClass('active');
        }
        if (!$('#pos-list').hasClass('hide')) {
            subNavScrollTo();
        }
        if (nav.reload) {
            search({
                type: 'shop_id',
                id: shopId,
                brand: brand,
                appVersion: appVersion,
                url: '/product/search/search',
                nextPage: false
            }, reloadCb);
        }
    }

    if ($('#list-nav').offset().top > $(document).scrollTop() && $('.filter-mask').hasClass('hide')) {
        $('#pos-list').addClass('hide');
    } else {
        $('.new-list').removeClass('full-height');
    }

    if (!$dropList.hasClass('hide')) {
        $dropList.addClass('hide');
    }

    e.stopPropagation();
});


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

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

$('.shop-foot-wrapper .buriedpoint').click(function() {
    let subGroup = $(this).find('.sub-group');

    if (subGroup.hasClass('hide')) {
        subGroup.removeClass('hide');
    } else {
        subGroup.addClass('hide');
    }
});

// 店铺收藏 || 取消收藏
$collect.on('touchstart', function() {
    let opt;

    if (searching) {
        return;
    }
    searching = true;

    if ($collect.hasClass('already-collect')) {
        opt = 'cancel';
    } else {
        opt = 'ok';
    }

    $.ajax({
        method: 'get',
        url: location.protocol + '//m.yohobuy.com/product/opt/favoriteBrand',
        data: {
            id: favId ? favId : shopId,
            appVersion: appVersion,
            opt: opt,
            type: 'shop',
            uid: uid
        },
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            let url = '';

            if (data.code === 200) {
                if ($collect.hasClass('already-collect')) {
                    $collect.attr('class', 'not-collect');
                    tip.show('店铺取消收藏成功');
                } else {
                    $collect.attr('class', 'already-collect');
                    tip.show('店铺收藏成功');
                }
            }

            if (data.code === 400) {
                url = data.data;
                if ($('#jump-login').length <= 0) {
                    $('body').append('<a href=\'' + url + '\'><span id="jump-login"><span></a>');
                }
                $('#jump-login').click();
            }

            setTimeout(function() {
                myScroll && myScroll.refresh();
            }, 500);
            searching = false;
        },
        error: function() {
            tip.show('网络断开连接了~');
            searching = false;
        }
    });
});