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'
}


$(function(){
    //上传图片
    $('#uploadImg').on('change propertychange',function(){
        var file = $(this).get(0).files[0];
        if(!fileValidate(file)){
            return
        }
        var fd = new FormData();
        fd.append('img',file);
        request('POST' , api + '/mxworld/upArticle?_from=ajax' , fd).then(function(data){
            dialog({
                title:"  ",
                content:"上传成功",
                skin:"popup-ui"
            }).showModal();
        },function(e,t){
            console.log(e)
            console.log(t)
            dialog({
                title:"  ",
                content:"上传失败",
                skin:"popup-ui"
            }).showModal();
        })
        
    })

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

    //获取列表
    getList();
})



function request (type,url,data) {
    return new Promise((resolve,reject)=>{
        var xhr = new XMLHttpRequest()
        xhr.withCredentials = true
        xhr.open(type,url,true);  
        var fd = data || "";
        xhr.send(fd);
        xhr.onreadystatechange = () => {
            if( xhr.readyState == 4){
                if (xhr.status == 200){
                    var result = JSON.parse(xhr.responseText);
                    if (checkLogin(result)){
                        resolve(result)
                    }else{
                        reject(result,xhr.status)
                    }
                }else{
                    reject(xhr.responseText,xhr.status)
                }
            }
        }
    })
}

//获取列表
function getList () {
    request('GET' , api + '/mxworld/hotArticle?_from=ajax' , '').then(function(result){
        $('.data-wrap').append(worksListTpl({data:result.data}));
    },function(e,t){
        console.log(e)
        console.log(t);
    })
}

//支持
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 checkLogin (result) {
    if(result.code == -7){
        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 fileValidate(file) {
    var type = file.type;
    if(/image/.test(type)){
        return true;
    }else{
        dialog({
            title:"   ",
            content:"请上传图片类型文件",
            skin:"popup-ui"
        }).showModal();
        return false;
    }
}



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;
    }