/* **************************************版本V1.0************************************** */
//全局变量
var audio = null,
    player_title_txt = $('#player-title'),   //播放器标题
    player_pic_url = document.getElementById("player-pic-url"), //播放器封面
    player_pic_err = 'http://q2.qlogo.cn/headimg_dl?bs=17404785&dst_uin=17404785&dst_uin=17404785&;dst_uin=17404785&spec=100&url_enc=0&referer=bu_interface&term_type=PC',    //没有pic时显示
    autoplay = true,    //自动播放
    isRotate = true,    //封面旋转
    player_mp3_err = '歌曲由于收费或者版权原因，无法播放！',
    player_lyric_txt = $('.player-lyric-txt'),  //歌词容器
    player_time = $('.player-time');  //时间容器

//打开播放器
var player_show = function () {
    if ($('#tool-state').attr('value')=='1'){
        $('#tool-state').click();   //切换成播放器
    }
    player_loadMusic();
};

//播放
var player_loadMusic = function () {
    try {
        if ($('[lid="'+rem.player_lid+'"][mold="list-music'+rem.player_list+'"]').length>0){
            //正常就播放
            player_pic(rem.player_jq);   //获取歌曲封面
            player_title(rem.player_jq);    //歌曲歌曲标题
            player_music(rem.player_jq);    //歌曲歌曲标题
            player_Lyric(rem.player_jq);    //获取歌曲歌词
        }else{
            //不正常就单曲循环
            audio.currentTime = 0;
        }
    }catch (e) {
        //错误处理
        console.log('播放列表更换处理...');
    }
};

//音频进度条调控功能实现
$(".player-progress").mousedown(function(ev){
    var posX = ev.clientX;
    var targetLeft = $(this).offset().left;
    var percentage = (posX - targetLeft)/140 * 100;
    audio.currentTime = audio.duration * percentage / 100;
});

var player_progress = function () {
    if (audio.buffered.length == 1) {
        // only one range
        if (audio.buffered.start(0) == 0) {
            // The one range starts at the beginning and ends at
            // the end of the video, so the whole thing is loaded
            var buffered = audio.buffered.end(0);
            var percentage = buffered/audio.duration * 100;
            $(".player-progress-value").css("width",percentage + "%");
        }
    }
};

//上一首
$(".player-control").on("click",".player-backward", function(e) {
    rem.player_lid = parseInt(rem.player_lid)-parseInt(1);
    rem.player_jq = $('[lid="'+rem.player_lid+'"][mold="list-music'+rem.player_list+'"]');
    if (rem.player_list==2){
        if (rem.player_lid<1) rem.player_lid = $('.player-list2').find("a").length;
    }else{
        if (rem.player_lid<1) rem.player_lid = $('#music-list-data').find("tr").length;
    }
    player_loadMusic();
});

//下一首
$(".player-control").on("click",".player-forward", function(e) {
    rem.player_lid = parseInt(rem.player_lid)+parseInt(1);
    rem.player_jq = $('[lid="'+rem.player_lid+'"][mold="list-music'+rem.player_list+'"]');
    if (rem.player_list==2){
        if (rem.player_lid>$('.player-list2').find("a").length) rem.player_lid=1;
    }else{
        if (rem.player_lid>$('#music-list-data').find("tr").length) rem.player_lid=1;
    }
    player_loadMusic();
});

//暂停/播放
$(".player-control").on("click",".player-play", function(e) {
    if (audio!==null){
        if($('.player-play').html()=='<i class="ion-pause"></i>'){
            player_pause();
        }else{
            player_play();
        }
    }
});

//开始播放
var player_play = function () {
    audio.play();
    if (isRotate) {
        $("#player-music #player-pic img").css("animation","9.8s linear 0s normal none infinite rotate");
        $("#player-music #player-pic img").css("animation-play-state","running");
    }
    $('#player-play').html('<i class="ion-pause"></i>');
};

//暂停播放
var player_pause = function () {
    audio.pause();
    $("#player-music #player-pic img").css("animation-play-state","paused");
    $('#player-play').html('<i class="ion-ios-play"></i>');
};

// 开始播放
var player_canplay = function(){
    if (autoplay == true) player_play();
};

//暂停播放
var player_ended = function () {
    audio.currentTime = 0;
    player_pause();
};

//更新歌词等信息...
var playerTime = function(){
    if (audio!==null){
        if (audio.currentTime==audio.duration){
            $('.player-forward').click();
        }
        var lyric_txt=document.getElementById("player-lyric-txt");
        var duration = audio.duration;
        var curTime = audio.currentTime;
        var percentage = curTime/duration * 100;
        $(".player-progress-value").css("width",percentage + "%");
        player_time.text(format(audio.currentTime));
        var id_num=parseInt(audio.currentTime);
        var lyric_p=$('[name="lyric_li"]');
        for(var i=0;i<lyric_p.length;i++){
            lyric_p[i].index=i;
        }
        if(document.getElementById("lyric"+id_num)){
            var obj=document.getElementById("lyric"+id_num);
            for(var i=0;i<obj.index;i++)
            {
                lyric_p[i].className="played";
            }
            for(var j=obj.index;j<lyric_p.length;j++)
            {
                lyric_p[j].className="";
            }
            obj.className="active";
            lyric_txt.style.top=lyric_txt.offsetHeight/3-obj.offsetTop+"px";
        }
    }
};

//获取歌曲封面
var player_pic = function (index) {
    if (index.attr('pic')!='null'){
        player_pic_url.src = index.attr('pic');
    }else{
        $.ajax({
            type: 'POST',
            url: music_api,
            data: "types=pic&id=" + index.attr('pic_id') + "&source=" + index.attr('source'),
            dataType : "jsonp",
            success: function(jsonData){
                if(jsonData.url !== "") {
                    player_pic_url.src = jsonData.url;
                    $('.tool-switcher').css('background','url("'+jsonData.url+'")');
                }else{
                    player_pic_url.src = player_pic_err;
                    $('.tool-switcher').css('background','url("https://desk-fd.zol-img.com.cn/t_s1366x768c5/g5/M00/09/02/ChMkJ1ah6XqIFvFFAAa5bop774sAAHjswApOYsABrmG421.jpg")');
                }
                return true;
            },
            error: function(data) {
                binyui.TipShow('获取封面失败，服务器内部错误，请联系管理员修复！', {
                    msgTimer: 5,
                    msgColor: '#fa0714',
                    msgAxis: 'centerTop',
                    xNum: '10%',
                    yNum: '10%',
                    zIndex: '99999'
                });
            }   // error
        }); //ajax
    }
};

//获取播放器标题
var player_title = function(index){
    if (rem.player_list==2){
        player_title_txt.html(index.children('div').eq(1).text()+' - '+index.children('div').eq(0).text());
    }else{
        player_title_txt.html(index.parents()[1].firstChild.parentNode.cells[1].innerText+' - '+index.parents()[1].firstChild.parentNode.cells[2].innerText);
    }
};

//获取歌曲外链
var player_music = function(index){
    $.ajax({
        type: 'POST',
        url: music_api,
        data: "types=url&id=" + index.attr('id') + "&source=" + index.attr('source'),
        dataType : "jsonp",
        success: function(jsonData){
            // 解决网易云音乐部分歌曲无法播放问题
            if(index.attr('source') == "netease") {
                if(jsonData.url === "") {
                    jsonData.url = 'err';
                } else {
                    jsonData.url = jsonData.url.replace(/m7c.music./g, "m7.music.");
                    jsonData.url = jsonData.url.replace(/m8c.music./g, "m8.music.");
                }
            } else if(index.attr('source') == "baidu") {    // 解决百度音乐防盗链
                jsonData.url = jsonData.url.replace(/http:\/\/zhangmenshiting.qianqian.com/g, "https://gss0.bdstatic.com/y0s1hSulBw92lNKgpU_Z2jR7b2w6buu");
            }
            if(jsonData.url === "") {
                jsonData.url = 'err';
            }else{
                updateMusic(jsonData.url);
            }
        },
        error: function(data) {
            binyui.TipShow('获取歌曲失败，服务器内部错误，请联系管理员修复！', {
                msgTimer: 5,
                msgColor: '#fa0714',
                msgAxis: 'centerTop',
                xNum: '10%',
                yNum: '10%',
                zIndex: '99999'
            });
        }   // error
    });
};

//更新src
var updateMusic = function(url){
    $('audio').remove();   //移除之前的audio
    if (url=='err' || typeof(url)==undefined){    //处理错误
        binyui.TipShow(player_mp3_err, {
            msgTimer: 5,
            msgColor: '#fa0714',
            msgAxis: 'centerTop',
            xNum: '10%',
            yNum: '10%',
            zIndex: '99999'
        });
        player_lyric_txt.html('<li>暂无歌词！</li>');
        $('.tool-switcher').css('background','url("https://desk-fd.zol-img.com.cn/t_s1366x768c5/g5/M00/09/02/ChMkJ1ah6XqIFvFFAAa5bop774sAAHjswApOYsABrmG421.jpg")');
        player_title_txt.html('歌名 - 歌手');
        $('.player-forward').click();
    }else{
        var newaudio = $('<audio>').html('<source src="'+url+'">').appendTo('#player-music');
        audio = newaudio[0];
        audio.addEventListener('progress', player_progress, false);
        audio.addEventListener('canplay', player_canplay, false);
        audio.addEventListener('ended', player_ended, false);
        audio.addEventListener('timeupdate', playerTime, false);
    }
};

//获取歌词
var player_Lyric = function(index){
    player_lyric_txt.html('<li>歌词加载中...</li>');
    $.ajax({
        type: 'POST',
        url: music_api,
        data: "types=lyric&id=" + index.attr('lyric_id') + "&source=" + index.attr('source'),
        dataType : "jsonp",
        success: function(jsonData){
            if (jsonData.lyric) {
                var lyricObj = jsonData.lyric;
                var temp = lyricObj.split("[");
                var html = "";
                for (var i = 0; i < temp.length; i++) {
                    var arr = temp[i].split("]");
                    var text = (arr[1]);
                    var time = arr[0].split(",");
                    var temp2 = time[0].split(".");
                    var temp3 = temp2[0].split(":");
                    var s = temp3[1];//秒
                    var m = temp3[0];//分
                    var s_sum = parseInt(m * 60) + parseInt(s);
                    if (text) {
                        html += "<li name='lyric_li' id='lyric" + s_sum + "'>" + text + "</li>";
                    }
                }
                player_lyric_txt.html(html);
            }else{
                player_lyric_txt.html('<li>该歌曲没有歌词！</li>');
            }
        },
        error: function(data) {
            player_lyric_txt.html('<li>获取歌词失败！</li>');
        }
    });//ajax
};

function format(time)
{
    var time=parseInt(time);
    var m=parseInt(time/60);
    var s=parseInt(time%60);
    m=zero(m);
    s=zero(s);
    function zero(num)
    {
        if(num<10)
        {
            num="0"+num;
        }
        return num;
    }
    return m+":"+s;
}

$(audio).trigger("loadedmetadata");

//打开列表
$(".player-control").on("click",".player-music-list", function(e) {
    if ($('#player-music').attr('value')=='1'){
        $('#player-music').attr('value','0');
        $('#player-list').show(800);
        $('#player-lyric').hide(800);
    }else{
        $('#player-music').attr('value','1');
        $('#player-list').hide(800);
        $('#player-lyric').show(800);
    }
});

//加载用户歌单
var load_album = function () {
    $('.player-list2').html('<a class="list-group-item text-center" id="player-list-load"><i class="fa fa-refresh fa-spin"></i></a>'); //清空列表
    $.ajax({
        type: 'POST',
        url: music_api,
        data: "types=userlist&uid=" + music_id,
        dataType : "jsonp",
        success: function(json){
            if (json.code!='400'){
                if (json.playlist.length === 0 || typeof(json.playlist.length) === undefined){
                    $('.player-list2').html('<a class="list-group-item text-center">空荡荡的，似乎缺点什么。</a>'); //清空列表
                }else{
                    var tempList;
                    for (var i = 0; i < json.playlist.length; i++){
                        // 获取歌单信息
                        tempList = {
                            id: json.playlist[i].id,    // 列表的网易云 id
                            name: json.playlist[i].name,   // 列表名字
                            playCount: json.playlist[i].playCount,   //播放次数
                            cover: json.playlist[i].coverImgUrl  + "?param=200y200",   // 列表封面
                            creatorID: json.playlist[i].creator.userId,   // 列表创建者id
                            creatorName: json.playlist[i].creator.nickname,   // 列表创建者名字
                            creatorAvatar: json.playlist[i].creator.avatarUrl,   // 列表创建者头像
                            item: []
                        };
                        var html = '<a id="'+tempList.id+'" class="list-group-item list-music1"><span class="pull-right"><i class="glyphicon glyphicon-chevron-right"></i></span><div>'+tempList.name+'</div></a>';
                        $('.player-list2').append(html);
                    }
                    $('#player-list-load').remove();
                }
            }
        },
        error:function (data) {
            alert('获取用户信息失败！错误代码：1！');
        }
    });//ajax
};
load_album();

//加载歌曲
$(".player-list2").on("click",".list-music1", function(e) {
    $('#player-arrow-swap').html('<a title="返回歌单" class="player-music-list2" id="player-music-list2"><i class="ion-arrow-left-a"></i></a>');
    $('.player-list2').html('<a class="list-group-item text-center" id="player-list-load"><i class="fa fa-refresh fa-spin"></i></a>'); //清空列表
    $.ajax({
        type: 'POST',
        url: music_api,
        data: "types=playlist&id=" + $(this).attr('id'),
        dataType : "jsonp",
        success: function(jsonData){
            var tempList=[];
            if(typeof jsonData.playlist.tracks !== undefined || jsonData.playlist.tracks.length !== 0) {
                // 存储歌单中的音乐信息
                for (var i = 0; i < jsonData.playlist.tracks.length; i++) {
                    tempList =  {
                        id: jsonData.playlist.tracks[i].id,  // 音乐ID
                        name: jsonData.playlist.tracks[i].name,  // 音乐名字
                        artist: jsonData.playlist.tracks[i].ar[0].name, // 艺术家名字
                        album: jsonData.playlist.tracks[i].al.name,    // 专辑名字
                        source: "netease",     // 音乐来源
                        url_id: jsonData.playlist.tracks[i].id,  // 链接ID
                        pic_id: null,  // 封面ID
                        lyric_id: jsonData.playlist.tracks[i].id,  // 歌词ID
                        pic: jsonData.playlist.tracks[i].al.picUrl + "?param=300y300",    // 专辑图片
                        url: null   // mp3链接
                    };
                    var html = '<a lid="'+(i+1)+'" id="'+tempList.id+'" name="play" source="'+tempList.source+'" pic_id="'+tempList.pic_id+'" lyric_id="'+tempList.lyric_id+'" pic="'+tempList.pic+'" mold="list-music2"  class="list-group-item list-music2" style="padding:5px 5px;"><div class="pull-right">'+tempList.artist+'</div><div>'+tempList.name+'</div></a>';
                    $('.player-list2').append(html);
                }
                $('#player-list-load').remove();
            }else{
                $('.player-list2').html('<a class="list-group-item text-center">空荡荡的，似乎缺点什么。</a>'); //清空列表
            }
        },
        error:function (data) {
            alert('获取歌曲列表失败，服务器内部错误！错误代码：1！');
        }
    });//ajax
});

//返回歌单
$(".player-control").on("click",".player-music-list2", function(e) {
    $('#player-arrow-swap').html('<a title="列表/歌词" class="player-music-list" id="player-music-list"><i class="ion-navicon-round"></i></a>');
    load_album();
});

//开始播放2
$(".player-list2").on("click","a", function(e) {
    rem.player_lid = $(this).attr('lid');
    if ($('[lid="'+rem.player_lid+'"]').attr('name')=='play'){  //播放
        rem.player_list = 2;
        rem.player_jq = $('[lid="'+rem.player_lid+'"][mold="list-music2"]');
        player_show();
    }
});