var worksListTpl = __inline('../../tpl/works-list.tmpl');   //列表模板
var dialog = require('dialog');

var api = 'http://sy.duowan.cn'

var env = getParam('env')
if(env == 'dev') {
    api = 'http://test.sy.duowan.cn'
}else if(env == 'new') {
    api = 'http://new.sy.duowan.com'
}else {
    api = 'http://sy.duowan.cn'
}

//当前列表信息
var dataType = {
    time : {
        selector: '#time',
        page : 1 ,
        type : 1
    },
    hot : {
        selector : '#hot',
        page : 1,
        type : 2
    }
}

var isloading = false;     //请求数据中
   
$(function(){
    //初始化获取数据
    $('.data-wrap').eq(0).show()
    getList(dataType.time.type , dataType.time.page , function(data){
        renderList(data,'#time');
        dataType.time.page++;
    })

    //绑定滚动加载数据
    $(window).on('scroll',load)

    //切换tab
    $('.first').on('click', function () {
        $('.load-more').show()
        $('.list-tab').removeClass('current');
        $(this).addClass('current');
        var index = $('.first').index($(this));
        $('.data-wrap').hide();
        $('.data-wrap').eq(index).show();
        load();
    })

    //我的作品
    $('.mine').on('click',function(){
        $('.list-tab').removeClass('current');
        $('.data-wrap').hide();
        $('#mine').show();
        $('.mine').addClass('current');
        getMine();
        $('.load-more').hide()
    })

    //投票支持
    $('.data-wrap').on('click','.g-support',function(){
        var id = $(this).attr('data');
        var $vote = $(this).parent('.desc-wrap').find('.vote-num')
        support(id,$vote);
        
    })


})



//滚动获取数据
function load () {
    if (isloading) {
        return;
    }
    var index = $('.first').index($('.first.current'));
    var $win = $(window),
        $contanier = $('.data-wrap').eq(index),
        screenHeight = $win.height(),
        offsetBottom = $contanier.offset().top + $contanier.height()
    
    if ( screenHeight + $win.scrollTop() >= offsetBottom ) {
        
        var type = $('.first.current').attr('type')
        if (type) {
            
             getData(dataType[type])
        }
       
    }


}


//滚动获取数据
function getData (type) {
    isloading = true;
    getList(type.type , type.page , function (data) {
        if(data.length != 0){     //有数据再渲染
            renderList(data , type.selector);
            if( type.type == 1){
                dataType.time.page++
            }
            if( type.type == 2){
                dataType.hot.page++
            }
        }
       
    })

}



/**
 * 
 * @param {1/2} type 数据类型  1按时间   2按人气  
 * @param {*} page 
 * @param {*} cb 
 */
function getList (type,page,cb) {
    $.ajax({
        url:`${api}/mxworld/piclist?pageSize=6&_from=ajax&page=${page}&order_type=${type}`,
        dataType:'jsonp',
        success:function (result) {
            checkLogin(result)
            isloading = false;
            if( result.data.length < 6){
                $('.load-more').hide();
                cb(result.data)
            }else{
                cb(result.data)
            }
        },
        error:function(x,e,t){
            console.log(x);
            console.log(e);
            console.log(t);
        }
    })
}



//获取我的作品
function getMine () {
    $.ajax({
        url: api + "/mxworld/myArticle?_from=ajax",
        dataType:"jsonp",
        success:function(result){
            checkLogin(result);
            renderList(result.data , '#mine')
        },
        error:function(x,e,t){
            console.log(x)
            console.log(e)
            console.log(t)
        }
    })
}


//渲染列表
function renderList (data,ele) {
    $(ele).append(worksListTpl({data}))
}


//是否登录
function checkLogin (result) {
    if(result.code == -7){
        console.log(result)
        debugger;
        dialog({
            title:"   ",
            content:"你未登录qq<br/>稍后为你跳转登录",
            skin:"popup-ui"
        }).showModal();
        var url = decodeURIComponent(result.data);
        var str = url.match(/\b(http.*)?(\?.*)?(\&.*)\b/)
        var redirectUrl = str[1] + '?redirect_url=' + location.href + str[3]
        $.ajax({
            url:redirectUrl,
            dataType:'jsonp',
            jsonp:"callback",
            success:function(result){
                setTimeout(function(){
                    location.href = result.data.oauth_url
                },3000)
            }
        })
        return false
    }
    if(result.code != 0 ){
        console.log(result.msg);
        return false
    }
    return true
}


//支持
function support (id , ele) {
    $.ajax({
        url: api + "/mxworld/vote?_from=ajax&article_id="+id,
        dataType:"jsonp",
        success:function(result){
            if (checkLogin(result)){
                dialog({
                    title:"   ",
                    content:"投票成功",
                    skin:"popup-ui"
                }).showModal();
                var voteNum = ele.text()
                ele.text(parseInt(voteNum)+1);
            } else{
                dialog({
                    title:"   ",
                    content:result.msg,
                    skin:"popup-ui"
                }).showModal();
            }
        },
        error:function(x,e,t) {
            console.log(x)
            console.log(e)
            console.log(t)
        }
    })
}


function getParam(name) {
        //先获取#后面的参数
        var str = document.location.hash.substr(2);
        var value = getParam2(name, str);
        if (value == null) {
            str = document.location.search.substr(1);
            value = getParam2(name, str);
        }

        return value;
    };

    function getParam2(name, str) {
        //获取参数name的值
        var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");

        //再获取?后面的参数
        r = str.match(reg);
        if (r != null) {
            try {
                return decodeURIComponent(r[2]);
            } catch (e) {
                // console.log(e + "r[2]:" + r[2]);
                return null;
            }
        }
        return null;
    }