common={
 	data:{
 		baseurl:"http://183.234.61.252:8090/",
 		getUserInfo:"Home/User/Info",
 		WebSocket:"ws://183.234.61.252:8282",
 		bdSocket:"Home/User/Bind",
 		Join:"Home/User/Join",
 		Answer:"Home/Game/Answer",
 		Join:"Home/Game/Join",
 		uid:"",
 	},userInfo:{

 	},GET: function (name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
     },getUserInfo:function(fn){
     	var _this=this;
     	   $.ajax({
             type: "GET",
             url: this.data.baseurl+this.data.getUserInfo,
             data: {user_id:this.data.uid , mt:this.data.mt },
             dataType: "json",
             success: function(data){
                   fn&&fn(data); 
               }
         });
 	},bdSocket:function(fn){
 		var _this=this;
     	   $.ajax({
             type: "POST",
             url: this.data.baseurl+this.data.bdSocket,
             data: {client_id:this.data.client_id    },
             dataType: "json",
             success: function(data){
                   fn&&fn(data); 
               }
         });
 	},Join:function(fn){
 		var _this=this;
     	   $.ajax({
             type: "GET",
             url: this.data.baseurl+this.data.Join,
             dataType: "json",
             success: function(data){
                   fn&&fn(data); 

               }
         });
 	},Answer:function(fn){
 		var _this=this;
     	   $.ajax({
             type: "POST",
             url: this.data.baseurl+this.data.Answer,
             data:{question_id:_this.data.question_id,option_id:_this.data.option_id},
             dataType: "json",
             success: function(data){
                   fn&&fn(data); 
               }
         });
 	},player_join:function(data){
 		var _this=this;
 		// if(responsedata.info.user){
 		// 	$("#username").html(responsedata.info.user.name);
   // 			$("#avatar").html('<img src="' + responsedata.info.user.avatar + '" class="layui-circle">');	
 		// }

 		// if(data.info.user.user_id){
   //          $("#py1_avatar").html('<img src="' + data.info.user.avatar+ '" class="layui-circle">');
   //          $("#py1_username").html(data.info.user.name + '（我）');
   //      }
   	this.tips(data.info.user.name+"加入了房间")
        if(data.info.user.user_id!=this.userInfo.user_id){
        	 $("#py2_avatar").html('<img src="' + data.info.user.avatar+ '" class="layui-circle">');
            $("#py2_username").html(data.info.user.name);
            _this.userInfo.playerId=data.info.user.user_id;
     }
 		 
 	},round_end:function(data){
 		var _this=this;
 		// if(data.info.anwser==_this.data.option_id){
 		// 	$(".cur_answer").addClass("cur_true");
   //        }
          
          for (var i = 0; i < data.info.players_answer.length; i++) {
          	if(data.info.players_answer[i].user_id==_this.userInfo.playerId){
          		//对方的答案id
          		_this.data.player_answerId=data.info.players_answer[i].option_id;
          	}
          }
          $("#question .item").each(function(){
          	if($(this).attr("data-option_id")==data.info.anwser){
          		$(this).addClass("cur_true");
          	}
          	if($(this).attr("data-option_id")!=data.info.anwser&&$(this).hasClass("cur_answer")){
          		
          		$(this).addClass("cur_error");
          	}
          	
          	if($(this).attr("data-option_id")==_this.data.player_answerId&&$(this).attr("data-option_id")==data.info.anwser){
          		//对方答案
          		$(this).addClass("player_true");
          	}
          	if($(this).attr("data-option_id")==_this.data.player_answerId&&$(this).attr("data-option_id")!=data.info.anwser){
          		//对方答案
          		$(this).addClass("player_error");
          	}
           
          })

          
 	},onSocket:function(e){
 		var data=JSON.parse(e.data);
 			var _this=this;
 		var type=data.type;
 		switch(type){
 			case 'init':
 			 _this.data.client_id=data.client_id;
 			_this.bdSocket(function(res){
 				_this.data.isReady=1;
 				console.log(res.msg);
 			});
 			    break;
          case 'player_join':
          _this.player_join(data);
          break;
          case 'question':
          _this.loadQuestion(data);
          break;
          case 'round_end':
          _this.round_end(data);
          console.log("答题结束");
          break;
          case "answer":
          if(_this.userInfo.user_id==data.user_id){
          	_this.increment($("#py1_score"),data.score);
          }else if(_this.userInfo.playerId==data.user_id){
          	_this.increment($("#py2_score"),data.score);
          }
          break;
          case 'game_end':
          $(".g-doc .g-inner").addClass("end");
          $("#Jvs").hide();
          console.log("游戏结束");
          break;
          


 		}
 	 	//_this.data.question_id
 	},startGame:function(){
 		if(this.data.isReady=="1")
 		this.Join(function(res){
 			$(".welcome").hide();
   		   $(".gstart").show();
 			common.tips(res.msg);
 		});
 		else this.tips("登录失败");
 	},initSocket:function(){
 		var _this=this;
 		  var ws = new WebSocket(this.data.WebSocket);
 		 	  ws.onmessage=function(e){
 		 	  	_this.onSocket(e);
 		 	  }

 	},loadQuestion(responsedata) {
        console.log(responsedata);
       
    var _this=this;
        _this.data.isAnswer=false;
        _this.data.question_id= responsedata.info.question.question_id;
        $("#Jqtitle").html(responsedata.info.question.title );
        var question="";
        var answers = responsedata.info.options
        for(var i in answers){
          question += '<li class="btn-2 item item'+i+' answer layui-btn layui-btn-primary"   data-option_id="'+answers[i].option_id+'">'+answers[i].title+'</li>';
        }
        $("#question").html(question);
        $("#Jpage").html(responsedata.info.questions_count+"/5");
        
           $(".g-doc .g-inner").addClass("doing");
       // is_end = responsedata.info.question.is_end;
         this.daoshu();
      	$("#question .item").on("touchend",function(){
 			var l = $("#question .item.cur_answer").length;
 			if(l>0)return;
 			$(this).addClass("cur_answer");
 			_this.data.option_id=$(this).attr("data-option_id");
 			if(!_this.data.isAnswer){
 				_this.data.isAnswer=true;
	 			_this.Answer(function(){
	 			});
 			}
 			
 		})
  },listen:function(){
 		var _this=this;
 		$(".rulebtn").on("touchend",function(){
 				$(".popwind,.popbg").fadeIn(200);
 		})
 		$(".close").on("touchend",function(){
 				$(".popwind,.popbg").fadeOut(200);
 		})
 		$("#start_game").on("touchend",function(){
 			 _this.startGame();
 		})
 		$("#Jagain").on("touchend",function(){
 			 window.location.href=window.location.href;
 		})
 		
 		
 	},increment:function(obj,num){
 		 var text=obj.text();
		obj.prop('Counter',text).animate({
			Counter: num
		},{
				duration: 1500,
				easing: 'swing',
				step: function (now){  
					$(this).text(Math.ceil(now));
				}
			});
	 
 	},daoshu:function(argument) {
 			var _this=this;
	    clearInterval(this.data.ts);
	    this.data.sum = 9;
	     this.data.angle = 0;
	   	var leftContent  = document.querySelector(".left-content");
		var rightContent  = document.querySelector(".right-content");
		var textCircle   = document.querySelector(".text-circle");
	    leftContent.setAttribute('style', 'transform: rotate(0deg)');
	    rightContent.setAttribute('style', 'transform: rotate(0deg)');
	    this.data.ts = setInterval(function() {
	        if (_this.data.sum >= 0) textCircle.innerHTML = _this.data.sum;
	        _this.data.sum = _this.data.sum - 1;
	        $("#Jvs .con").show();
	        $("#Jvs .tit").html("抢答中");
	        _this.data.angle += 36;
	        if (_this.data.angle <= 360) {
	            if (_this.data.angle > 180) {
	                rightContent.setAttribute('style', 'transform: rotate(' + (_this.data.angle - 180) + 'deg)')
	            } else {
	                leftContent.setAttribute('style', 'transform: rotate(' + _this.data.angle + 'deg)')
	            }
	        }
	        
	        if(_this.data.sum<3){

	        	$(".text-circle").addClass("rubberBand");
	        	$(".text-circle").addClass("animated");
	        	setTimeout(function(){
	        		$(".text-circle").removeClass("rubberBand");
	        		$(".text-circle").removeClass("animated");
	        	},900)
	        }
	        
	        if (_this.data.sum < -1) {
	        	if(!_this.data.isAnswer)
	           	_this.Answer();
	            _this.data.sum = 9;
	            _this.data.angle = 0;
	            leftContent.setAttribute('style', 'transform: rotate(0deg)');
	            rightContent.setAttribute('style', 'transform: rotate(0deg)')
	        }
	    }, 1000)
}, tips: function (text, time) {
                //弹窗工具
                time = time ? time : 1500;
                var para = document.createElement("p"); //创建新的<p> 元素
                para.innerHTML = text;
                para.setAttribute("class", "poptis");
                document.body.appendChild(para);
                para.style.marginLeft = -para.offsetWidth / 2+"px";
                setTimeout(function () {
                    document.body.removeChild(para);
                }, time);

    },init:function(){
 		var _this=this;
 		this.listen();
 		var ycy =this.GET("ycy");
 		if(ycy){
 			var b64 = new Base64();
	 		ycy=b64.decode(ycy);
	 		ycy=decodeURIComponent(ycy);
	 		ycy= JSON.parse(ycy); 
	 		this.data.uid=ycy.uid;
	 		this.data.mt=ycy.mt;	
 		}
 		if( this.GET("user_id")){
 			this.data.uid=this.GET("user_id");
	 		this.data.mt=this.GET("mt");
 		}
 		this.getUserInfo(function(res){
 			_this.userInfo=res.info;
 			$("#py1_username").html(res.info.name);
   			$("#py1_avatar").html('<img src="' + res.info.avatar + '" class="layui-circle">');
 			_this.initSocket();

 		})
 		
 		
 	}
 }
 window.common=common;
