var AutoLoad = require('autoload')
var _ = require('underscore')

class pageGameStore {
    constructor() {
        this.pageNum = 3

        this.$searchName = $('#pcGameName')
        this.$selectItems = $('.search-item')

        this.$navBar = $('.ku-dgame')

        this.$navs = $('.ku-game-nav li')

        this.$searchBtn = $('.btn-search')

        this.pcStoreTpl = __inline('../../tpl/pcGameStore.tmpl')
        this.init()
    }
    init() {
        var self = this

        this.changetab('.ku-nav', '.ku-item')
            .changetab('.ku-dgame', '.ku-game-item')
            .changetab('.ku-mgame', '.ku-mgame-item')
            .changeSelect().afterInput()

        var _index = location.href.indexOf('#')
        if (_index > 0) {
            var type = location.href.slice(_index + 1)

            var $item = type != '' && $(`.ku-dgame li[data-order=${type}]`).length > 0 ? $(`.ku-dgame li[data-order=${type}]`) : $('.ku-dgame li').eq(0)

            $item.click()
        } else {
            $('.ku-dgame li').eq(0).click()
        }

        $(".ku-game-wrap").on('click', '.btn-saixuan', function () {
            var $this = $(this);
            var $em = $this.find('em');
            $this.parent().next().slideToggle(300);
            if ($em.hasClass('down')) {
                $em.removeClass('down').addClass('up');
            } else {
                $em.removeClass('up').addClass('down');
            }
        })

        this.$searchBtn.click(function () {
            if (self.$searchName.val() != '') {
                self.getData()
            }
        })

        this.autoload = new AutoLoad('.ku-game-wrap', this.appendData.bind(this))
    }

    changetab(parent, showbox) {
        var self = this
        $(parent).on("click", "li", function () {


            var $this = $(this);
            var index = $this.index();

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

            $(this).addClass("active").siblings().removeClass("active");
            $(showbox).eq(index).show().siblings(showbox).hide();

            self.getData()
            return false;
        })

        return this
    }
    changeSelect() {
        var self = this
        this.$selectItems.on('click', 'li', function () {
            $(this).addClass('active').siblings().removeClass('active')

            self.getData()
        })

        return this
    }
    afterInput() {
        this.$searchName.on('input', this.getData.bind(this))

        return this
    }
    //重置筛选条件
    resetSelect() {
        this.$searchName.val('')
        this.$selectItems.each(function (index, ele) {
            var $ele = $(ele),
                $selects = $ele.find('li')

            $selects.removeClass('active').eq(0).addClass('active')
        })

        return this
    }

    getSearch() {
        var obj = {}
        //搜索关键字
        var searchName = this.$searchName.val()
        if (searchName != '') {
            obj.keyword = searchName
        }
        //筛选条件
        this.$selectItems.each(function (index, ele) {
            var $ele = $(ele),
                $selectItem = $ele.find('li.active'),
                _index = $selectItem.index()

            if (_index > 0) {
                if ($selectItem[0].hasAttribute('data-company')) {
                    obj[`option${index + 1}`] = $selectItem.text()
                } else {
                    obj[`option${index + 1}`] = Math.pow(2, _index - 1)
                }
            }
        })
        if (Object.keys(obj).length > 0) {
            this.$navBar.addClass('hide')
            obj.hasSearch = true
        } else {
            this.$navBar.removeClass('hide')
        }

        //排列规则
        obj.order = this.$navs.filter('.active').attr('data-order')

        return obj
    }

    getData() {
        var self = this
        var searchObj = this.getSearch()
        if (searchObj.order == 'create_time' || searchObj.hasSearch) {
            $.ajax({
                url: 'http://ku.newgame.duowan.com/index.php?&r=api/ajaxGameList&type=jsonp',
                data: Object.assign({ pageSize: 40, page: 1 }, this.getSearch()),
                dataType: 'jsonp',
                success: function (data) {
                    if (data.data.list instanceof Array) {
                        self.renderData(data.data.list, 'new')
                        self.pageNum = 3
                    } else {
                        self.autoload.turnOff()
                    }
                    self.autoload.done()
                },
                err: function (err) {
                    console.log(err)
                }
            })
        } else {
            $.ajax({
                url: `http://ku.newgame.duowan.com/index.php?&r=api/ajaxGameRank&type=jsonp`,
                data: { mode: 'hot', page: 1 },
                dataType: 'jsonp',
                success: function (data) {
                    if (data.data.list instanceof Array) {
                        self.renderData(data.data.list, 'hot')
                        self.pageNum = 3
                    } else {
                        self.autoload.turnOff()
                    }
                    self.autoload.done()
                },
                err: function (err) {
                    console.log(err)
                }
            })
        }


        return this
    }

    appendData() {
        var self = this
        var searchObj = this.getSearch()

        if (searchObj.order == 'create_time' || searchObj.hasSearch) {
            $.ajax({
                url: 'http://ku.newgame.duowan.com/index.php?&r=api/ajaxGameList&type=jsonp',
                data: Object.assign({ pageSize: 20, page: self.pageNum }, this.getSearch()),
                dataType: 'jsonp',
                success: function (data) {
                    if (self.pageNum > data.data.totalPage) return;

                    if (data.data.list instanceof Array && data.data.list.length > 0) {
                        self.renderData(data.data.list, 'new', 2)
                        self.pageNum++
                    } else {
                        self.autoload.turnOff()
                    }
                    self.autoload.done()
                },
                err: function (err) {
                    console.log(err)
                }
            })
        } else {
            $.ajax({
                url: `http://ku.newgame.duowan.com/index.php?&r=api/ajaxGameRank&type=jsonp`,
                data: { mode: 'hot', page: this.pageNum },
                dataType: 'jsonp',
                success: function (data) {
                    if (data.data.list instanceof Array) {
                        self.renderData(data.data.list, 'hot', 2)
                        self.pageNum++
                    } else {
                        self.autoload.turnOff()
                    }
                    self.autoload.done()
                },
                err: function (err) {
                    console.log(err)
                }
            })
        }
        return this
    }
    renderData(list, tab, type) {
        type = type || 1

        var $wrap = $('.ku-game-item').filter(':visible').children('ul')
        var $newEles = $(this.pcStoreTpl({
            games: list,
            tab: tab
        }))
        if (type == 1) {
            this.autoload.turnOn()
            $wrap.html($newEles)
        } else {
            $wrap.append($newEles)
        }

    }

}

$(() => {
    new pageGameStore()
})
