/**
 *  品牌一览
 * @author: liangzhifeng<zhifeng.liang@yoho.cn>
 * @date: 2015/10/23
 */
require('channel/brand.page.css');

let $ = require('yoho-jquery'),
    Hammer = require('common/toy-hammer'),
    Swiper = require('yoho-swiper'),
    lazyLoad = require('yoho-jquery-lazyload');

let ranToken = ' ??++ ';
let ranToken2 = ' ???--- ';

let $brandList,
    $newBrandWall,
    $recommandBrandWall,
    $icon = $('.search-icon'),
    $genderItem = $('.gender-nav li'),
    $brandItem = $('.brand-nav li'),
    $searchAction = $('.search-action'),

    // $homebuttom = $('.homebuttom'),
    // $newSearch = $('.newbrand-search'),
    $netHistory = $('.net-history'),
    $searchResult = $('.search-result');

    // $navBtn = $('.nav-home');

let brandsData,
    $keyword = $('#keyword');

let $history = $('.local-history');

// let $searchPage = $('.search-brand-page');
let $historySearch = $('.history-search');
let $hotSearch = $('.hot-search');
let $clearHistory = $('#clear-history');
let isSearchPage = $('.brand-search-page').length > 0;

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

function getBrandList() {
    let listHbs = require('channel/brandlist.hbs');

    $.ajax({
        url: '/brands/getBrandList',
        data: {
            channel: window.queryString.channel || $('.query-param[data-attr="yhChannel"]').val()
        },
        success: function(data) {
            $('#placeholder-brandlist').replaceWith(listHbs(data));

            lazyLoad($('img.lazy'));

            // 改变背景色
            changeBackground(); //eslint-disable-line

            $brandList = $('.brand-list');
            $newBrandWall = $('.new-brand-wall');
            $recommandBrandWall = $('.recommand-brand-wall');
        },
        error: function() {
        }
    });
}

function changeBackground() {
    let brandList = $('.brand-list').find('p');

    brandList.on('touchstart', function() {
        brandList.css('background', '#fff');
        $(this).css('background', '#eee');
    }).on('touchend touchcancel', function() {
        $(this).css('background', '#fff');
    });
}

/**
 * 增加单条记录
 */
function addHistory(brandName) {
    $.ajax({
        type: 'POST',
        url: '/brands/addBrandSearch',
        data: 'brandName=' + encodeURIComponent(brandName),
        success: function() {
        },
        error: function() {
        }
    });
}

// 比较大小
function sequence(a, b) {
    if (a.time > b.time) {
        return 1;
    } else if (a.time < b.time) {
        return -1;
    } else {
        return 0;
    }
}

function searchInput() {
    if ($keyword.val().length) {
        $icon.css('color', '#444');

        // $(this).closest('.search-box').css('width', '11.25rem');
        $searchAction.show().find('.clear-text').show();
    } else {
        $icon.css('color', '#b2b2b2');
        $searchResult.css('margin-bottom', '0');

        // $(this).closest('.search-box').css('width', '12.5rem');
        $searchAction.find('.clear-text').hide();
    }
    searchResult(); //eslint-disable-line
}

function isLocalStorageSupported() {
    let testKey = 'test',
        storage = Window.prototype.localStorage || window.localStorage;

    try {
        storage.setItem(testKey, 'testValue');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
}

// 绑定提交前的存local操作
function bindWriteLocal(brandListEle, list) {
    brandListEle.on('click', 'p , li', function(e) {
        let brandName, url;
        let a = $(this).find('a');
        let myDate = new Date();
        let query = a.attr('brandName') + ranToken2 + myDate.getTime(),
            historys;

        brandName = a.attr('brandName');

        url = a.attr('href');

        e.preventDefault();

        if ($netHistory.length > 0) {
            addHistory(brandName);

            if (list) {
                location.href = url;
                return;
            }

            $keyword.val(brandName);
            searchInput();
            return;
        }

        if (localStorage) {
            if (isLocalStorageSupported()) {
                historys = localStorage.getItem('historys-brand');
            }

            historys = historys ? historys : '';

            if (historys.indexOf(ranToken + query + ranToken) > -1) {


                $keyword.val(brandName);
                searchInput();
                return;
            }

            if (historys === '') {
                query = ranToken + query;
            }

            historys += query + ranToken;

            if (isLocalStorageSupported()) {
                localStorage.setItem('historys-brand', historys);
            }
        }

        if (list) {
            location.href = url;
            return;
        }

        $keyword.val(brandName);
        searchInput();
    });
}

function searchResult() {
    let keyword = ($keyword.val() + '').toLowerCase();
    let result = {},
        i = 0,
        html = '';

    if (keyword !== '') {

        // 遍历首字母搜索
        $.each(brandsData, function(k, v) {
            if ($.isArray(v)) {

                // 遍历品牌,进行匹配
                $.each(v, function(index, brand) {
                    if (brand.searchName.toLowerCase().indexOf(keyword) > -1) {
                        result[k] = result[k] || [];
                        result[k].push(brand);
                    }
                });
            }
        });

        // 根据搜索结果生成 HTML
        $.each(result, function(k, v) {
            let brandHtml = ['<div class="brand-list bar-', i, '">'];

            i++;
            brandHtml.push('<div class="title-bar"><h2>');
            brandHtml.push(k);
            brandHtml.push('</h2></div>');
            $.each(v, function(index, brand) {

                brandHtml.push('<p><a href="' + brand.url + '" brandName = "' + brand.name +
                    '" brandId = "' + brand.brandId + '" brandDomain = "' + brand.brandDomain + '">' + brand.name);
                if (brand.isNew) {
                    brandHtml.push('<i class="icon-new">NEW</i>');
                }
                if (brand.isHot) {
                    brandHtml.push('<i class="icon-hot">HOT</i>');
                }
                brandHtml.push('</a></p>');
            });
            brandHtml.push('</div>');
            html += brandHtml.join('');

        });
    }

    // 没填入关键词时显示最热搜索
    if (keyword.length > 0) {
        $('.search-brand-page').addClass('hide');
    } else {
        $('.search-brand-page').removeClass('hide');
    }

    // 插入 dom,绑定事件
    $searchResult.html(html);
    changeBackground();
    bindWriteLocal($('.brand-list'), true);
}

$(window).resize(function() {
    window.rePosFooter();
});

(function() {
    if ($('.banner-top').length === 0) {
        let h1 = $('.gender-nav').height();
        let h2 = $('.newbrand-search').height();

        $('.hot-brands').css('padding-top', (h1 + h2) + 'px');
    }

    // banner滑动
    new Swiper('.swiper-container', {
        lazyLoading: true,
        loop: true,
        autoplay: 3000,
        pagination: '.swiper-pagination .pagination-inner'
    });

    // 热门品牌滑动
    new Swiper('.brands-swiper', {
        grabCursor: true,
        slidesPerView: 'auto',
        wrapperClass: 'brands-list',
        slideElement: 'li'
    });

    $genderItem.on('touchstart', function() {
        if (window.queryString.channel) {
            let index = $(this).data('id') + 1;

            window.location.search = 'channel=' + index;
        } else {
            let name = $(this).data('name').toLowerCase();

            window.location.href = `/${name}-brands/`;
        }
    });

    $brandItem.on('click', function() {
        let index = $(this).data('id');

        $('.brand-nav ul .active').removeClass('active');
        $(this).addClass('active');
        if (index === 0) {
            $recommandBrandWall.not('.hide').addClass('hide');
            $newBrandWall.not('.hide').addClass('hide');
            $brandList.removeClass('hide');
        } else if (index === 1) {
            $newBrandWall.removeClass('hide');
            $brandList.not('.hide').addClass('hide');
            $recommandBrandWall.not('.hide').addClass('hide');
        } else {
            $recommandBrandWall.removeClass('hide');
            $brandList.not('.hide').addClass('hide');
            $newBrandWall.not('.hide').addClass('hide');
        }
    });

    if (!isSearchPage) {
        setTimeout(getBrandList, 50);
    }
}());

// 搜索页面
if (isSearchPage) {
    $('.yoho-header').css({
        'z-index': 3,
        position: 'fixed',
        top: 0
    });

    // $homebuttom.css('top', '45px');
    // $homebuttom.css('position', 'fixed');
    // $navBtn.on('touchstart', function() {
    //     if ($homebuttom.hasClass('hide')) {
    //         $searchResult.css('margin-top', '0px');
    //         $newSearch.css('margin-top', '0px');
    //         $searchPage.css('margin-top', '0px');
    //     } else {
    //         $searchResult.css('margin-top', '45px');
    //         $newSearch.css('margin-top', '45px');
    //         $searchPage.css('margin-top', '45px');
    //     }
    // });

    bindWriteLocal($historySearch, false);
    bindWriteLocal($hotSearch, false);

    brandsData = $.parseJSON($('#brands-data').html());

    $keyword.on('input', function() {
        searchInput();
    });

    // 2016.1.13 产品(高扬)要求进入页面默认显示取消按钮
    $icon.css('color', '#444');
    $keyword.closest('.search-box').css('width', '13rem');
    $searchAction.show().find('.clear-text').hide();

    let clearTextHammer = new Hammer($('.clear-text')[0]);

    clearTextHammer.on('tap', function(e) {
        $searchResult.html('');
        $('#keyword').val('').trigger('input');
        e.srcEvent.preventDefault();
        e.srcEvent.stopPropagation();
    });

    $('form.search-box').on('submit', function() {
        return false;
    });
}

// 初始化历史搜索的内容
if (isSearchPage) {
    require('./brand-render')(function() {
        // 清除记录
        function removeHistory() {
            $.ajax({
                type: 'GET',
                url: '/brands/delBrandHistory',
                data: '',
                success: function() {},
                error: function() {}
            });
        }

        $netHistory = $('.net-history');
        let chHammer = new Hammer($clearHistory[0]);

        chHammer.on('tap', function() {
            if (isLocalStorageSupported()) {
                localStorage.removeItem('historys-brand');
            }
            $history.html('');
            $historySearch.hide();
            $clearHistory.hide();

            if ($('.net-search').length > 0) {
                removeHistory();
            }

            window.rePosFooter();
        });

        // 搜索页面
        (function() {
            let html = '',
                history,
                historys, i,
                localHistory,
                brand, data,
                time, netArr, dict, dictc, localArr,
                combinArr, key, date, temp;

            localArr = [];
            combinArr = [];
            netArr = [];

            $netHistory.find('li').each(function() {
                brand = $(this).find('a').attr('brandName');
                time = $(this).find('a').attr('collectTime');
                dict = {
                    brand: brand,
                    time: time
                }, dictc, dict; //eslint-disable-line
                netArr.push(dict);
            });


            if (localStorage) {
                if (isLocalStorageSupported()) {
                    historys = localStorage.getItem('historys-brand');
                }

                if (historys && historys.length > 0) {
                    historys = historys.split(ranToken);
                    for (i = historys.length; i > 0; i--) {
                        history = historys[i - 1];

                        if (history === '') {
                            continue;
                        }
                        localHistory = history.split(ranToken2);

                        brand = localHistory[0];
                        time = localHistory[1];

                        dict = {
                            brand: brand,
                            time: time
                        };

                        localArr.push(dict);

                    }
                }
            }

            if (localArr.length === 0 && netArr.length === 0) {
                $historySearch.addClass('hide');
                return;
            }


            date = {};
            temp = {};
            if (localArr.length > 0) {
                for (dictc in localArr) {
                    if (localArr.hasOwnProperty(dictc)) {
                        temp = localArr[dictc];
                        if (!date[temp.brand] || date[temp.brand] < temp.time) {
                            date[temp.brand] = temp.time;
                        }
                    }
                }
            }

            if (netArr.length > 0) {
                for (dict in netArr) {
                    if (netArr.hasOwnProperty(dict)) {
                        temp = netArr[dict];
                        if (!date[temp.brand] || date[temp.brand] < temp.time) {
                            date[temp.brand] = temp.time;
                        }
                    }
                }
            }

            data = {};
            for (key in date) {
                if (date.hasOwnProperty(key)) {
                    data = {
                        brand: key,
                        time: date[key]
                    };
                    combinArr.push(data);
                }
            }

            combinArr.sort(sequence);

            if (combinArr.length > 0) {
                for (i = combinArr.length - 1; i >= ((combinArr.length > 10) ? (combinArr.length - 10) : 0); i--) {

                    brand = combinArr[i].brand;
                    time = combinArr[i].time;

                    html += '<li><a brandName = "' + brand +
                        '">' + brand + '</li>';
                    $history.removeClass('hide');

                    $history.html(html);
                    $clearHistory.removeClass('hide');

                    $hotSearch.removeClass('hide');
                    window.rePosFooter();

                }
            } else {
                $history.addClass('hide');
            }
        }());
    });
}