<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>用户主页</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="full-screen" content="yes"/> <!--部分原生机子-->
<meta name="screen-orientation" content="portrait"/> <!--UC浏览器-->
<meta name="x5-fullscreen" content="true"/> <!--QQ浏览器-->
<meta name="360-fullscreen" content="true"/> <!--360浏览器-->

<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
  {!!Html::style('plugins/layui/css/layui.css')!!}
  {!!Html::style('plugins/layui/css/main.css')!!}
  <script>
(function(f,j){var i=document,d=window;var b=i.documentElement;var c;var h=i.querySelector('meta[name="viewport"]');var e="width=device-width,initial-scale=1,maximum-scale=1.0,user-scalable=no";if(h){h.setAttribute("content",e)}else{h=i.createElement("meta");h.setAttribute("name","viewport");h.setAttribute("content",e);if(b.firstElementChild){b.firstElementChild.appendChild(h)}else{var a=i.createElement("div");a.appendChild(h);i.write(a.innerHTML)}}function g(){var k=b.getBoundingClientRect().width;if(!j){j=540}if(k>j){k=j}var l=k*100/f;b.style.fontSize=l+"px"}g();d.addEventListener("resize",function(){clearTimeout(c);c=setTimeout(g,300)},false);d.addEventListener("pageshow",function(k){if(k.persisted){clearTimeout(c);c=setTimeout(g,300)}},false);if(i.readyState==="complete"){i.body.style.fontSize="16px"}else{i.addEventListener("DOMContentLoaded",function(k){i.body.style.fontSize="16px"},false)}})(750,750);
</script>
</head>
<body>
  <div id="userinfo" class="layui-row" style="margin-top: 200px;">
  <div class="layui-col-xs12 layui-col-sm12 layui-col-md12" style="text-align: center;">
    <div id="avatar" class="layui-block">
    </div>
    <div class="layui-block">
      <b id="username"></b>
    </div>
    <button id="start_game" class="layui-btn layui-btn-normal" style="margin-top: 20px;">匹配对手</button>
    <button id="out_game" class="layui-btn layui-btn-normal" style="margin-top: 20px; display: none;">取消匹配</button>
    <input type="hidden" id="uid" name="uid">
    <input type="hidden" id="duishou" name="duishou">
  </div>
</div>
<div id="game" class="layui-row" style="margin-top: 200px;display: none;">
  <div class="layui-col-xs4 layui-col-sm4 layui-col-md4">
    <div id="py1_avatar" class="layui-block">
    </div>
    <div class="layui-block">
      <b id="py1_username"></b>
      ( <b id="py1_score">0</b> )
    </div>
  </div>
  <div class="layui-col-xs4 layui-col-sm4 layui-col-md4">
    V S
  </div>
  <div class="layui-col-xs4 layui-col-sm4 layui-col-md4">
    <div id="py2_avatar" class="layui-block">
    </div>
    <div class="layui-block">
      <b id="py2_username"></b>
      ( <b id="py2_score">0</b> )
    </div>
  </div>
  <div id="question" class="layui-col-xs8 layui-col-sm8 layui-col-md8" style="margin-top: 50px;text-align: center;">
  </div>
</div>
<div class="g-doc">
    <div class="g-inner">
      <div class="login">
        
      </div>
      <div class="loading amt">
        <div class="loader">
          <div class="face">
            <div class="circle"></div>
          </div>
          <div class="face">
            <div class="circle"></div>
          </div>

        </div>
      </div>

      <div class="cov cov1 amt"><span class="userface" id="avatar"></span>
        <b id="username"></b>
        <span class="num" id="py1_score">940</span>
      </div>
      <div class="cov cov2 amt">
        <button id="start_game" class="layui-btn layui-btn-normal" style="margin-top: 20px;">匹配对手</button>
        <input type="hidden" id="uid" name="uid">
        <input type="hidden" id="duishou" name="duishou">
      </div>
      <div class="cov cov3 amt">vs</div>
      <div class="cov cov4 amt">
        <span class="userface" id="py2_avatar" ></span>
        <b id="py2_username"></b>
        <span class="num"  id="py2_score">720</span>
      </div>
      <div class="qs-item" >
        <span class="tit">西气东输是把哪里的天然气往华北输送</span>
        <ul class="list" id="question">
          <li class="item item1 on">四川</li>
          <li class="item item2">新疆</li>
          <li class="item item3">西藏</li>
        </ul>
        <div class="page">1/5</div>
      </div>
      <div class="result">
        <span class="icon top-icon success"></span>
        <span class="live">初级玩家</span>
        <span class="btn btn1">再来一局</span>
        <span class="btn btn2">查看等级</span>
      </div>

    </div>
    
  </div> 
{!!Html::script('plugins/layui/layui.js')!!}
<script>
var is_end = 0;
layui.use(['form','jquery'], function(){
  var form = layui.form;
  var $ = layui.$;
  var game_ready = false;
  var client_id = '';
  var room_id = '';
  var cur_question = 1;

  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });
  //获取用户信息
  $.get('/Home/User/Info',{},function(responsedata){
    if(responsedata.code == 10001){
        layer.msg(responsedata.msg, {
          time: 1000 //2秒关闭（如果不配置，默认是3秒）
        }, function(){
          window.location.href = 'index.html';
        }); 
    }
    console.log(responsedata)
    $("#username").html(responsedata.info.username);
    $("#avatar").html('<img src="' + responsedata.info.avatar + '" class="layui-circle">');
    $("#uid").val(responsedata.info.uid);
  },'json');

  //绑定通信
  // ws = new WebSocket("ws://www.dt.com:6390");
  ws = new WebSocket("ws://183.234.61.252:8282");
  // 服务端主动推送消息时会触发这里的onmessage
  ws.onmessage = function(e){
      // json数据转换成js对象
      var data = eval("("+e.data+")");
      var type = data.type || '';
      switch(type){
          // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
          case 'init':
              client_id = data.client_id;
              // 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
              $.post('/Home/User/Bind', {client_id: data.client_id}, function(responsedata){
                game_ready = true;
                layer.msg(responsedata.msg, {
                  time: 1000 //2秒关闭（如果不配置，默认是3秒）
                }); 
              }, 'json');
              break;
          case 'match':
              console.log(data);
              $(".g-doc .g-inner").addClass("doing");
              layer.msg("匹配成功，正在进入房间...", {
                time: 1000 //2秒关闭（如果不配置，默认是3秒）
              });
              //设置player值
              if(data.info.players[0]['uid'] == $("#uid").val()){
                $("#py1_avatar").html('<img src="' + data.info.players[0]['avatar'] + '" class="layui-circle">');
                $("#py1_username").html(data.info.players[0]['username'] + '（我）');
                $("#py2_avatar").html('<img src="' + data.info.players[1]['avatar'] + '" class="layui-circle">');
                $("#py2_username").html(data.info.players[1]['username']);
                $("#duishou").val(data.info.players[1]['uid']);
              }else{
                $("#py1_avatar").html('<img src="' + data.info.players[1]['avatar'] + '" class="layui-circle">');
                $("#py1_username").html(data.info.players[1]['username']+'（我）');
                $("#py2_avatar").html('<img src="' + data.info.players[0]['avatar'] + '" class="layui-circle">');
                $("#py2_username").html(data.info.players[0]['username']);
                $("#duishou").val(data.info.players[0]['uid']);
              }
              
              if(data.info.room_id){
                room_id = data.info.room_id;
                getQuestion(data.info.room_id, cur_question);
              }
              break;
          case 'answer':
              console.log(data);
              if(data.uid == $("#uid").val()){
                var score = parseInt($("#py1_score").html());
                if(data.is_true == 1){
                  $("#py1_score").html(score+1);
                  $(".cur_answer").removeClass("layui-btn-primary");
                }else{
                  $(".cur_answer").removeClass("layui-btn-primary");
                  $(".cur_answer").addClass("layui-btn-danger");
                }
              }else{
                if(data.is_true == 1){
                  var score = parseInt($("#py2_score").html());
                  $("#py2_score").html(score+1);
                }
              }
              if(data.next == 1){
                if(is_end == 1){
                  //结算
                  $(".g-doc .g-inner").addClass("end");
                  var py1_score = parseInt($("#py1_score").html());
                  var py2_score = parseInt($("#py2_score").html());
                  var url = 'quit.php';
                  if(py1_score > py2_score){
                    layer.msg('恭喜你获得胜利', {icon: 1, time: 2000}, function(){
                    });
                  }else if(py1_score == py2_score){
                    layer.msg('打成平手', {icon: 2, time: 2000}, function(){
                    });
                  }else{
                    layer.msg('您输了比赛', {icon: 5, time: 2000}, function(){
                    });
                  }
                  $.get(url, {room_id,room_id},function(){
                    layer.msg("您已退出对战", {
                      time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    }); 
                  });
                  //返回逻辑
                  is_end = 0;
                  cur_question = 1;
                  room_id = 0;
                   
                  $("#py1_score").html(0);
                  $("#py2_score").html(0);
                 
                  return false;
                }
                getQuestion(room_id, cur_question);
              }
              //设置player值
              break;
          // 当mvc框架调用GatewayClient发消息时直接alert出来
          default :
              alert(e.data);
      }
  };

  //开始匹配
  $("#start_game").click(function(){
    if(!game_ready){
      layer.msg("未链接服务器，请重新链接", {
        time: 1000 //2秒关闭（如果不配置，默认是3秒）
      }); 
      return;
    }
    var url = "/Home/Game/Join";
    $.post(url,{client_id:client_id},function(responsedata){
      layer.msg(responsedata.msg, {
        time: 1000 //2秒关闭（如果不配置，默认是3秒）
      }); 
      if(responsedata.code == 0){
       
        
          
      }
    },'json');
  });

  //开始匹配
  $("#out_game").click(function(){
    if(!game_ready){
      layer.msg("未链接服务器，请重新链接", {
        time: 1000 //2秒关闭（如果不配置，默认是3秒）
      }); 
      return;
    }
    var url = "/Home/Game/Out";
    $.post(url,{client_id:client_id},function(responsedata){
      layer.msg(responsedata.msg, {
        time: 1000 //2秒关闭（如果不配置，默认是3秒）
      }); 
      if(responsedata.code == 0){
        // $(".g-doc .doing").addClass("doing");
      }
    },'json');
  });

  //获取题目
  var getQuestion = function getQuestion(room_id, index) {
    var url = '/Home/Game/Question';
    $.get(url, {room_id:room_id, cur_question:index}, function(responsedata){
      if(responsedata.code == 0){
        var question = '<b>'+ responsedata.info.title +'</b><br/>';
        var answers = responsedata.info.answers
        for(var i in answers){
          question += '<button class="answer layui-btn layui-btn-primary" style="margin-top: 25px;" data-id="'+answers[i].id+'">'+answers[i].title+'</button><br>';
        }
        $("#question").html(question);
        //is_end = responsedata.info.is_end;
      }else{
        layer.msg(responsedata.msg, {
          time: 1000 //2秒关闭（如果不配置，默认是3秒）
        }); 
      }
    },'json');
  }

  $("#question").on('click', '.answer',function(){
    if($(".cur_answer").length > 0){
      return false;
    }
    var url = '/Home/Game/Answer';
    var answer = $(this).data("id");
    $(this).addClass("cur_answer");
    $.post(url, {answer:answer,cur_question:cur_question,room_id:room_id,client_id:client_id,is_end:is_end}, function(responsedata){
      console.log(responsedata);
    });
    cur_question = cur_question + 1;
  });

});
</script>
</body>
</html>