Vue.config.devtools = true;
var v = new Vue({
	el:".index-box",
	data:{
        cata:[
            {name:"直播详情",active:1,id:1},
            {name:"互动",active:0,id:2},
            {name:"云展厅",active:0,id:3},
        ],
		websock: null,
        memToken: '',
		memCard: '',
		liveId: '',
        liveInfo: {},
        endTime:{day:0,hour:0,minute:0,second:0},
        content: '',
        loading: false,
        cid: -1,
        finished: false,
        contentList: [],
        yzt: [],
        liveLlayer: null,
        memberInfo: {
            isPurchased: 0,
            isRemind: 0,
            joinMembers: 0,
            remindMemberNum: 0
        },
        memNicknames: [],
        isLogin: 0,
        memToken: '',
        memHeadImg: '',
        userJf:-1,
        learnTime: 0,
	},
    created:function (){
	    var that = this;
        if($.cookie("memToken")){
            that.memToken = $.cookie("memToken");
            that.isLogin=1;
        }
        if($.cookie("memHeadImg")){
            that.memHeadImg = $.cookie("memHeadImg");
        }
	    that.liveId = $("#liveId").val();
	    that.getDetailData();
        that.findUserBaseInfo();
        that.commentList();
        this.findUserIntegral();
	},
	mounted: function (){
		window.addEventListener("scroll", this.scrollBottom, true);
        this.initWebSocket();
	},
	methods:{
        findUserIntegral (){
            var that = this;
            $.ajax({
                type : 'POST',
                url : serverHttp+"/user/findUserIntegral",
                data : {
                    memToken:that.memToken
                },
                success : function(data) {
                    if (data.code == 200) {
                        that.userJf = data.data;
                    }
                },
                error : function(data) {
                }
            });
        },
        toPay(){
            if(!checkLogin()){
                goLogin();
                return false;
            }
            var that = this;
            if(!that.parseRule()){
                return false;
            }
            var check = true;
            that.liveInfo.questions.forEach((item,index)=>{
                if(!item.answerContent){
                    check = false;
                }
            });
            if(!check){
                alert("请完善相关信息");
                return false;
            }
            toPay(2, that.liveInfo.lvId);
        },
        addFreeBuyApi(){
            if(!checkLogin()){
                goLogin();
                return false;
            }
            var that = this;
            if(!that.parseRule()){
                return false;
            }
            $.ajax({
                type : 'POST',
                url : serverHttp+"/pay/addFreeBuyApi",
                data : {
                    memToken:that.memToken,
                    orderType: 2,
                    objId: that.liveId,
                    ispackage: 1,
                    paySource: 3,
                    fromMemCard: ''
                },
                success : function(data) {
                    if (data.code == 200) {
                        that.liveInfo.isPurchased = 1;
                        that.toPlay();
                    }else if(data.code == 10008){
                        //去登录
                        goLogin();
                    }else{
                        alert(data.data.message);
                    }
                },
                error : function(data) {
                }
            });
        },
        parseRule(){
            var that = this;
            if(that.liveInfo.smrzFlag==1 && that.memberInfo.smrzFlag==0){
                window.location.href=serverHttp+"/user/certificationSm?from=H5&memToken=";
                return false;
            }else if(that.liveInfo.ysrzFlag==1 && that.memberInfo.ysrzFlag==0){
                window.location.href=serverHttp+"/user/certificationYs?from=H5&memToken=";
                return false;
            }else if(that.liveInfo.questionFlag==1 && that.liveInfo.isQuestionAnswer!=1){
                $(".info-collect").show();
                return false;
            }
            return true;
        },
		inputChange(e,obj){
	        obj.answerContent=e.target.value;
		},
        gotoRcmd(obj) {
            gotoRcmdPub(obj.zqFlag,obj.rcmdType,obj.rcmdObjId,obj.rcmdUrl);
        },
		saveQuestionAnswer(){
			var that = this;
			var check = true;
			for (var item of that.liveInfo.questions) {
                if (item.answerContent == undefined || item.answerContent == null || item.answerContent === '') {
                    check = false;
                    break;
                }
            }
			if(!check){
				alert("请完善相关信息");
				return false;
			}
			$.ajax({
                type : 'POST',
                url : serverHttp+"/live/saveQuestionAnswer",
                data : {
                    liveId:that.liveId,
                    memToken:that.memToken,
                    questions: JSON.stringify(that.liveInfo.questions)
                },
                success : function(data) {
                		if(data.code == 200){
                			$(".info-collect").hide();
                			that.liveInfo.isQuestionAnswer=1;
                    }
                },
                error : function(data) {
                }
            });
		},
        addVideoPlayRecorde() {
            var that = this;
            $.ajax({
                type: 'POST',
                url: serverHttp + "/course/addVideoPlayRecorde",
                async: false,
                data: {
                    playTime: -1,
                    totalLearnTime: that.learnTime * 1000,
                    objType: 2,
                    objId: that.liveId,
                    memToken: that.memToken
                },
                success: function (data) {
                    if (data.code == 200) {
                        // that.currentTime = 0;
                        // that.learnTime = 0;
                    }
                },
            });
        },
		infoByMember(){
			var that = this;
            $.ajax({
                type : 'POST',
                url : serverHttp+"/live/infoByMember",
                data : {
                    memToken:that.memToken,
                    liveId: that.liveId
                },
                success : function(data) {
                		if(data.code == 200){
                			that.liveInfo.joinMembers = data.data.joinMembers;
                			that.liveInfo.isPurchased = data.data.isPurchased;
                			that.liveInfo.isRemind = data.data.isRemind;
                			that.liveInfo.remindMemberNum = data.data.remindMemberNum;
                			that.liveInfo.isQuestionAnswer = data.data.isQuestionAnswer;
                    }
                },
                error : function(data) {
                }
            });
        },
		findUserBaseInfo(){
            if(!checkLogin()){
                return false;
            }
            var that = this;
            $.ajax({
                type : 'POST',
                url : serverHttp+"/user/findUserBaseInfo",
                data : {
                    memToken:that.memToken
                },
                success : function(data) {
                    that.memberInfo=data.data;
                },
                error : function(data) {
                }
            });
        },
		toPlay(){
			var that = this;
			if(that.liveInfo.isPurchased != 1){
				return false;
			}
			if(that.liveInfo.livePlayUrl && that.liveInfo.liveStatus == 1){
				if(!that.liveLlayer){
					var w = $(window).width();
					var h = Math.floor(w * 9/16);

                    that.liveLlayer =  new TcPlayer('livePlay', {
						"m3u8": that.liveInfo.livePlayUrl,
						"flv": that.liveInfo.livePlayUrlFlv, //增加了一个 flv 的播放地址，用于PC平台的播放 请替换成实际可用的播放地址
						"autoplay" : false,      //iOS 下 safari 浏览器，以及大部分移动端浏览器是不开放视频自动播放这个能力的
						"width" :  w,//视频的显示宽度，请尽量使用视频分辨率宽度
						"height": h,//视频的显示高度，请尽量使用视频分辨率高度
						"poster" : that.liveInfo.liveCoverImg,
						"listener": function (msg) {
		                    if(msg.type == 'error') {
		                        console.log(msg, '播放报错');
		                        // 可以尝试5次拉流
		                        if (that.liveLlayer) {
		                            timer = setTimeout(() => {
		                            that.liveLlayer.load();
		                                console.log('重试拉流');
		                            }, 5000);
		                            setInterval(() => {
		                                clearTimeout(timer);
		                            }, 120000);
		                        }
		                    } else if (msg.type == 'play'){
		                        console.log(msg, '拉流成功');
		                        // 清楚拉流的定时器
		                        clearTimeout(timer);
		                    }

		                }
					});
				}
				console.log('play---------------------------->>>>play');
                that.liveLlayer.play();
                that.startTiming();
			}
		},
        startTiming() {
            var that = this;
            that.timer = setInterval(function () {
                that.learnTime = that.learnTime + 1;
                // console.log(that.learnTime);
                if (that.learnTime % 30 == 0) {
                    //1分钟的倍数
                    that.addVideoPlayRecorde();
                }
            }, 1000)
        },
        scrollBottom() {
            const that = this;
            if(that.cata[1].active==1){
            		// 滚动到页面顶部时
                const scrollTop = document.getElementById('contentList').scrollTop
                if (scrollTop == 0 && !that.finished) {
                    that.commentList();
                }
            }
        },
        commentList () {
            var that = this;
            if (that.loading) {
                return ;
            }
            that.loading = true;
            if(that.start == 1){
                that.contentList = []
            }
            $.ajax({
                type : 'POST',
                url : serverHttp+"/live/commentList",
                data : {
                    cId: that.cid,
                    liveId: that.liveId
                },
                success : function(res) {
                    that.loading = false;
                    if (res.code == 200) {
                        if(that.cid == -1){
                            that.contentList = res.data.reverse();
                        }else{
                            that.contentList = res.data.concat(that.contentList);
                        }
                        that.cid = that.contentList[0].cid;
                        if(that.cata[1].active==1){
                        		document.getElementById('contentList').scrollTop = 2;
                        }
                    }else if (res.code == 10005) {
                        that.finished = true;
                    }
                }
            });
        },
        addLiveComment(){
            if(!checkLogin()){
                goLogin();
                return false;
            }
            var that = this;
            if(!that.content || !that.content.trim()){
                alert("请输入您的观点");
                return false;
            }
            $.ajax({
                type : 'POST',
                url : serverHttp+"/live/addLiveComment",
                data : {
                    memToken:that.memToken,
                    liveId: that.liveId,
                    content: that.content
                },
                success : function(data) {
                    if (data.code == 200) {
                        that.websocketsend(that.content);
                        that.content="";
                    }else if(data.code == 10008){
                        //去登录
                        goLogin();
                    }else{
                        alert(data.data.message);
                    }
                },
                error : function(data) {
                }
            });
        },
        addRemind(){
            if(!checkLogin()){
                goLogin();
                return false;
            }
            var that = this;
            $.ajax({
                type : 'POST',
                url : serverHttp+"/live/addRemind",
                data : {
                    memToken:that.memToken,
                    liveId: that.liveId
                },
                success : function(data) {
                    if (data.code == 200) {
                        if(data.data.code != -1){
                            that.liveInfo.isRemind = 1;
                            that.liveInfo.remindMemberNum=data.data.remindMemberNum;
                        }else{
                            alert(data.data.errMsg);
                        }
                        if(that.memberInfo.subscribe != 1){
                            $("#gzfwh").show();
                        }
                        if(that.liveInfo.price == 0 && that.liveInfo.point==0){
                            //如果是免费课程，订阅成功后添加购买记录
                            //that.addFreeBuyApi();
                        }
                    }else if(data.code == 10008){
                        //去登录
                        goLogin();
                    }else{

                    }
                },
                error : function(data) {
                }
            });
        },
        chooseTab(i){
            const that = this;
            for (var item of that.cata) {
                if (item.active == 1) {
                    item.active = 0
                }
            }
            that.cata[i].active = 1;
        },
        getDetailData(){
            var that = this;
            $.ajax({
                type : 'POST',
                url : serverHttp+"/live/getDetailData",
                data : {
                    memToken:that.memToken,
                    liveId: that.liveId
                },
                success : function(data) {
                    if (data.code == 200) {
                        that.liveInfo = data.data;
                        $("meta[name='sharetitle']").attr("content",that.liveInfo.shareTitle);
                        $("meta[name='sharedesc']").attr("content",that.liveInfo.shareDesc);
                        $("meta[name='sharepic']").attr("content",that.liveInfo.sharePic);
                        // $("meta[name='shareurl']").attr("content",that.liveInfo.shareUrl);

                        if(that.liveInfo.liveStatus == 0){
                            that.countDown();
                        }else if(that.liveInfo.liveStatus==1 || that.liveInfo.liveStatus==3){
                            timer = setTimeout(() => {
                                that.toPlay();
	                        }, 1000);
                        }
                        that.infoByMember();
                    }
                },
                error : function(data) {
                }
            });
        },
		initWebSocket(){ //初始化weosocket
            var that = this;
			if (!that.memCard) {
			    return false;
			}
            var wsUrl = serverHttpWss+"/live/oneToMany/"+$("#liveId").val()+"/"+this.memCard;
            that.websock = new WebSocket(wsUrl);
            that.websock.onmessage = that.websocketonmessage;
            that.websock.onopen = that.websocketonopen;
            that.websock.onerror = that.websocketonerror;
            that.websock.onclose = that.websocketclose;
            setTimeout(function () {
                that.showName();
            }, 1000);
		},
		websocketonopen(){ //连接建立之后执行send方法发送数据
			console.log('websocket开启');
		},
		websocketonerror(){//连接建立失败重连
            console.log('websocketonerror');
			this.initWebSocket();
		},
		websocketonmessage(e){ //数据接收
            console.log('websocketonmessage');
            var that = this;
			const jx = JSON.parse(e.data);
			console.log(jx);
			if(jx.type == 0){
			    //谁来了
				console.log(jx.memNickname);
				that.memNicknames.unshift(jx.memNickname);
			}else if(jx.type == 1){
			    //评论
				console.log(jx);
                that.inserComment(jx);
			}else if(jx.type == 2){
			    //更改直播状态
				console.log(jx);
                that.liveInfo.liveStatus =jx.liveStatus;
                if(that.liveInfo.liveStatus == 1){
                    $(".vcp-player").show();
                    setTimeout(()=>{
                        that.toPlay();
                    },500)
                }else{
                    $(".vcp-player").hide();
                }
			}else if(jx.type == 3){
				console.log(jx);
				changeJoinMembers(jx.joinMembers);
			}else if(jx.type == 4){
				console.log(jx);
				buildHtml(jx.awardWinnerList,1);
			}else if(jx.type == 5){
				console.log(jx);
				barrage(jx.barrage);
			}else if(jx.type == 6){
				console.log(jx);
				sendDrawALotteryActivity();
			}else if(jx.type == 7){
				console.log(jx);
				for (var item of jx.users) {
                    that.memNicknames.unshift(item);
				}
			}else if(jx.type == 8){
                console.log(jx);
                $("#tuisongQrpath").find(".wjs").attr("src", jx.imgPath);
                $("#tuisongQrpath").show();
            }
		},
		websocketsend(Data){//数据发送
            console.log("websocketsend");
			this.websock.send(Data);
		},
		websocketclose(e){  //关闭
			console.log('断开连接',e);
		},
        countDown(){
            var that = this;
            var timer = setInterval(function(){
                if (that.liveInfo.liveBeginSySecond > 0) {
                    var sys_second = that.liveInfo.liveBeginSySecond-1;
                    that.liveInfo.liveBeginSySecond = sys_second;
                    that.endTime.day = Math.floor((sys_second / 3600) / 24);
                    that.endTime.hour = Math.floor((sys_second / 3600) % 24);
                    that.endTime.minute = Math.floor((sys_second / 60) % 60);
                    that.endTime.second = Math.floor(sys_second % 60);
                } else {
                    clearInterval(timer);
                }
            }, 1000);
        },
        inserComment(data){
            data.mem.oprTime = "刚刚";
            data.mem.content = data.mem.msg;
            this.contentList.push(data.mem);
        },
        showName() {
            var that = this;
            if(that.liveInfo.liveStatus>1){
                return false;
            }
            if (that.memNicknames.length > 0) {
                var name = that.memNicknames[that.memNicknames.length - 1];
                that.memNicknames.pop();
                $(".comeIn").html("<span>" + name + "</span>" + " 来了");
                $(".comeIn").stop();
                $(".comeIn").fadeIn(500);
                setTimeout(function () {
                    $(".comeIn").fadeOut(400);
                    setTimeout(function () {
                        that.showName();
                    }, 1000);
                }, 500)
            } else {
                setTimeout(function () {
                    that.showName();
                }, 1000);
            }
        },
	}
})
