$(function() {
    var rankTpl = __inline('../tpl/championRank.tmpl');
    var curList = [];
    var baseList = [];

    function getRank() {
        var url = "http://api.lolbox.duowan.com/api/v2/rank/championStat/";
        $.ajax({
            url: url,
            dataType: 'jsonp',
            success: function(resp) {
                var ret = resp.results;

                if(!ret || !ret.length) {
                    renderEmpty();
                    return;
                }

                curList = baseList = _.sortBy(ret, 'win_ratio').reverse();
                renderList(curList);
            }
        });
    }

    function renderList(data) {
        var dom = rankTpl({list: data});
        $("#rankListBody").html(dom);
    }

    function renderEmpty() {
        $('#rankListBody').html('<tr><td colspan="6" style="text-align:center;padding: 30px 0;">暂无数据，请稍后重试</td></tr>');
    }

    function initEvent() {
        //选择不同的位置
        $(".hero-rank").on("click", ".mod-tabs-trigger li", function(e) {
            if($(this).hasClass('selected')) {
                return;
            }
            $(this).addClass('selected').siblings().removeClass('selected');
            var type = $(this).attr("data-type");
            if(type == 'all') {
                curList = baseList;
            } else {
                curList = _.filter(baseList, function(item) {
                    return item.position == type;
                });
                curList = _.sortBy(curList, 'win_ratio').reverse();
            }
            renderList(curList);
        });

        //排序
        $(".hero-rank").on("click", "thead .sort", function() {
            var ratio = $(this).attr("data-ratio");
            if($(this).hasClass('sort--down')) {
                $(this).attr('class', 'sort sort--up');
                curList = _.sortBy(curList, ratio);
            } else {
                $(this).attr('class', 'sort sort--down');
                curList = _.sortBy(curList, ratio).reverse();
            }
            renderList(curList);
        });

        //搜索
        $(".hero-rank").on("input", "#searchKey", function() {
            var input = $(this).val();
            var searchList = [];
            searchList = _.filter(curList, function(item) {
                var cp = item.champion;
                if(cp.display_name && cp.display_name.match(input)) {
                    return item;
                } else if(cp.name && cp.name.match(input)) {
                    return item;
                } else if(cp.title && cp.title.match(input)) {
                    return item;
                }
            });
            renderList(searchList);
        });
    }

    function filterList(position) {
        
    }

    function init() {
        getRank();
        initEvent();
    }

    init();
})