/**
 * 商品列表搜索
 * @author: wsl<shuiling.wang@yoho.cn>
 * @date: 2016/5/23
 */
let $ = require('yoho-jquery'),
    lazyLoad = require('yoho-jquery-lazyload'),
    tip = require('plugin/tip'),
    filter = require('plugin/filter'),
    loading = require('plugin/loading');

let $goodsContainer = $('#goods-container'),
    $defaultgc = $goodsContainer.find('.default-goods'),
    $ngc = $goodsContainer.find('.new-goods'),
    $dgc = $goodsContainer.find('.discount-goods'),
    $pgc = $goodsContainer.find('.price-goods'),
    $agc = $goodsContainer.find('.all-goods'),
    $cgc = $goodsContainer.find('.category-goods'),
    $sgc = $goodsContainer.find('.sale-goods');

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

let previousScrollTop = 0;

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

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

    // 导航数据信息
    navInfo = {
        all: {
            order: 0,
            reload: true,
            page: 0,
            end: false
        },
        new: {
            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
        },
        sale: {
            order: 0,
            reload: true,
            page: 0,
            end: false
        },
        category: {
            order: 0,
            reload: true,
            page: 0,
            end: false
        },
        default: {
            order: 0,
            reload: true,
            page: 0,
            end: false
        },
        popularity: {
            order: 0,
            reload: true,
            page: 0,
            end: false
        }
    },
    $pre = $listNav.find('.active'), // 纪录进入筛选前的active项,初始为选中项
    searching;

require('common');

// 获取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; // 返回参数值
}

if ($('.sale-vip-page').length > 0) {
    defaultOpt.saleType = 2;
} else if ($('.discount-detail-page').length > 0) {
    defaultOpt.saleType = 3;
    defaultOpt.productPool = $('.discount-detail-page').data('product-pool') || '';
}

// 获取频道
$.extend(defaultOpt, {
    yh_channel: getUrlParam('channel') || defaultOpt.channel || 'all',
    currentUrl: location.pathname
});

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

    if (dom.hasClass('new')) {
        navType = 'new';
    } else if (dom.hasClass('price')) {
        navType = 'price';
    } else if (dom.hasClass('discount')) {
        navType = 'discount';
    } else if (dom.hasClass('sale')) {
        navType = 'sale';
    } else if (dom.hasClass('all')) {
        navType = 'all';
    } else if (dom.hasClass('category')) {
        navType = 'category';
    } else if (dom.hasClass('default')) {
        navType = 'default';
    } else if (dom.hasClass('popularity')) {
        navType = 'popularity';
    }

    return navType;
}

/**
 * 筛选注册的回调,筛选子项点击后逻辑
 * 需要执行search的场景:1.点选筛选项;2.relaod为true时切换导航;3.下拉加载
 * @param opt {type, id}
 * @param params {Object} 分类商品导航专用参数
 * @param isScroll {Boolen} 滚动时不清空数据,分类导航专用参数
 */
function search(opt, params, isScroll) {
    let setting = {},
        ext,
        att,
        nav, navType,
        page;

    if (searching) {
        return;
    }

    if (opt && !isScroll) {

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

        // 处理active状态
        $listNav.children('.active').removeClass('active');
        $pre.addClass('active');

        switch (opt.type) {
            case 'gender':
                ext = {
                    gender: opt.id
                };
                break;
            case 'ageLevel':
                ext = {
                    age_level: 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 'p_d':
                ext = {
                    p_d: opt.id
                };
                break;
            default:
                break;
        }

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

    $.extend(params || {}, defaultOpt); // 扩展筛选项

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

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

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

    if (params) {
        defaultParams = params;
        $.extend(setting, params, {
            type: navType,
            order: nav.order,
            page: page
        });
    } else {
        defaultParams = null;
        $.extend(setting, defaultOpt, {
            type: navType,
            order: nav.order,
            page: page,
            currentUrl: location.pathname
        });
    }

    searching = true;
    loading.showLoadingMask();

    /* TODO tar add 161125 sale dicount no yh_channel*/
    let discount = $('#discount').val();

    if (discount === 'discount') {
        delete setting.yh_channel;
    }

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

            switch (navType) {
                case 'new':
                    $container = $ngc;
                    break;
                case 'price':
                    $container = $pgc;
                    break;
                case 'discount':
                    $container = $dgc;
                    break;
                case 'sale':
                    $container = $sgc;
                    break;
                case 'all':
                    $container = $agc;
                    break;
                case 'categroy':
                    $container = $cgc;
                    break;
                case 'default':
                    $container = $defaultgc;
                    break;
                default:
                    $container = $agc;
                    break;
            }

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

            if (data === '' || (data.list && data.list.length <= 0)) {
                nav.end = true;

                if (nav.reload) {
                    $container.html(noResult);
                }
            } else {
                if (navType === 'category') {
                    nav.page = 1;
                }

                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() {
    $.ajax({
        type: 'GET',
        url: '/product/sale/filter',
        data: defaultOpt,
        success: function(data) {
            if (data === '') {
                return false;
            }

            $goodsContainer.append(data);

            // 初始化filter&注册filter回调
            filter.initFilter({
                fCbFn: search,
                hCbFn: function() {

                    // 切换active状态到$pre上
                    $pre.addClass('active');
                    $pre.siblings('.filter').removeClass('active');
                },
                missStatus: true
            });
        }
    });
}

setTimeout(function() {
    if ($('.outlet-index-page').length === 0) {
        filterInit();
    }
}, 300);

lazyLoad($('.lazy'));

// 导航栏点击逻辑说明:
// 1.点击非active项时切换active状态
// 2.价格和折扣active状态时继续点击切换排序
// 3.筛选无active时点击展开筛选面板
// 4.筛选有active时点击隐藏筛选面板并恢复点击筛选前active项的active状态
// 5.当前active为筛选并且点击其他项时,隐藏筛选面板
$listNav.bind('contextmenu', function() {
    return false;
});


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

    e.preventDefault();

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

    if ($(this).hasClass('active')) {
        $('.drop-list').addClass('hide');
        return;
    }

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

    nav = navInfo[navType];

    // $defaultgc.removeClass('hide');
    // $fsgc.removeClass('hide');

    $defaultgc.removeClass('hide');

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

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

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

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

        case 'sale':
            $sgc.removeClass('hide');
            break;

        case 'all':
            $agc.removeClass('hide');
            break;

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

    $pre = $firstLiDom;

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

    $('.drop-list').addClass('hide');
});

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

    e.preventDefault();

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

    if ($this.hasClass('first-li-more')) {
        $('.drop-list').toggleClass('hide');

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

        return true;
    } else if (!$('.drop-list').hasClass('hide')) {
        $('.drop-list').addClass('hide');
    } else {
        $('.drop-list').find('li').removeClass('active');
    }

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

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

            // 点击筛选钱的active项回复active
            $pre.addClass('active');
            $this.removeClass('active');
        } else {
            $pre = $this.siblings('.active');

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

            filter.showFilter();
        }
    } else {

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

        nav = navInfo[navType];

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

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

            if ($this.hasClass('price') || $this.hasClass('discount')) {

                // 价格/折扣切换排序状态
                $this.find('.icon > .iconfont').toggleClass('cur');
                $pre = $this; // 更新pre为当前项
                nav.reload = true; // 重置reload,HTML会被替换为逆序的HTML
                nav.order = nav.order === 0 ? 1 : 0; // 切换排序
            }
        } else {
            $active = $this.siblings('.active');

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

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

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

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

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

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

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

                    case 'sale':
                        $sgc.removeClass('hide');
                        break;

                    case 'all':
                        $agc.removeClass('hide');
                        break;

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

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

        if (nav.reload) {
            search();
        }
    }
    e.stopPropagation();
});

function scrollHandler() {
    let curScrollTop = $(window).scrollTop();

    // 当scroll到1/4$goodsContainer高度后继续请求下一页数据
    if (curScrollTop > previousScrollTop &&
        (curScrollTop + winH >
        $(document).height() - 0.25 * $goodsContainer.height() - 50)) {
        if (typeof $pre !== 'undefined') {
            if (defaultParams) {
                search({type: 'category'}, defaultParams, true);
            } else {
                search();
            }
        }
    }

    previousScrollTop = curScrollTop;
}

// srcoll to load more
$(window).scroll(function() {
    if ($('.outlet-index-page').length === 0) {
        window.requestAnimationFrame(scrollHandler);
    }
});


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

module.exports = {
    start: search
};