<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo $_LANG['zjmf_ssh_key']; ?></title>
  <link rel="stylesheet" href="modules/servers/zjmfcloud/templates/server_innerpage/css/embed/bootstrap.min.css">
  <link rel="stylesheet" href="modules/servers/zjmfcloud/templates/server_innerpage/css/embed/layui.css">
  <link rel="stylesheet" href="modules/servers/zjmfcloud/templates/server_innerpage/css/embed/selectFilter.css">
  <link rel="stylesheet" href="modules/servers/zjmfcloud/templates/server_innerpage/css/embed/02SecurityGroup.css">
  <!-- <link rel="stylesheet" href="modules/servers/zjmfcloud/templates/server_innerpage/css/global.css"> -->

  <script src="modules/servers/zjmfcloud/templates/server_innerpage/lib/embed/jquery.min.js"></script>
  <script src="modules/servers/zjmfcloud/templates/server_innerpage/lib/embed/bootstrap.min.js"></script>
  <script src="modules/servers/zjmfcloud/templates/server_innerpage/lib/embed/sweetAlert2.min.js"></script>
  <script src="modules/servers/zjmfcloud/templates/server_innerpage/lib/embed/fileSaver.min.js"></script>
  <style type="text/css">
    .invalid-feedback{
      display: block;
    }
  </style>
</head>

<body>
  <div class="securityGroup_btn">
    <button type="button" class="layui-btn purple" data-toggle="modal" data-target="#myModal"><?php echo $_LANG['zjmf_create_ssh_key']; ?></button>
  </div>
  <div class="container ssh-key">
    <!-- 新建ssh模态框 -->
    <div class="modal fade" id="myModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <span class="modal-title"><?php echo $_LANG['zjmf_create_ssh_key']; ?></span>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
          </div>

          <!-- 模态框主体 -->
          <div class="modal-body">
            <div class="modal_limit">
              <div class="modal_main">
                <form class="ssh-form">
                  <p>
                    <label for="type" class="way">
                      <span class="l-txt"><?php echo $_LANG['zjmf_create_ssh_key_type']; ?></span>
                      <span class="radio"><input name="type" type="radio" value="0" class="form-way" onchange="changeWay(0)"
                        ><?php echo $_LANG['zjmf_create_new_ssh_key']; ?></span>
                      <span class="radio"><input name="type" type="radio" value="1" class="form-way" onchange="changeWay(1)"
                      ><?php echo $_LANG['zjmf_import_ssh_key_public_key']; ?></span>
                    </label>
                  </p>
                  <p>
                    <label for="name">
                      <span  class="l-txt"><?php echo $_LANG['zjmf_ssh_key_name']; ?></span>
                      <input type="text" placeholder="<?php echo $_LANG['zjmf_ssh_key_name']; ?>" name="name" class="input">
                    </label>
                  </p>
                  <p>
                    <label for="public_key" id="pubilc-key">
                      <span  class="l-txt">
                          <?php echo $_LANG['zjmf_ssh_key_public_key']; ?>
                          <span title="<?php echo $_LANG['zjmf_ssh_key_public_key_support_tip']; ?>" class="tip">?</span>
                      </span>
                      <textarea rows="5" placeholder="<?php echo $_LANG['zjmf_ssh_key_public_key_placeholder']; ?>" name="public_key" class="input"></textarea>
                    </label>
                  </p>
                  <p>
                      <span class="tip" style="background-color: #fdf6ec;
                            color: #e6a23c;
                            display: inline-block;
                            padding: 10px;">
                          <?php echo $_LANG['zjmf_ssh_key_create_confirm']; ?>
                      </span>
                  </p>
              </div>
              <div class="footer">
                <button type="button" class="btn confirm-btn createSecurityGroup" data-dismiss="modal" style="margin-left:10px"><?php echo $_LANG['zjmf_client_nat_web_confirm']; ?></button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <table class="layui-table">
    <thead>
      <tr>
        <th><?php echo $_LANG['zjmf_ssh_key_name']; ?></th>
        <th style="width:285px"><?php echo $_LANG['zjmf_client_nat_web_operation']; ?></th>
      </tr>
    </thead>
    <tbody>
        <?php foreach($sshKeyList as $v){ ?>
        <tr>
            <td><?php echo $v['name'];if($v['bind']){ echo $_LANG['zjmf_ssh_key_bind_current_host']; } ?></td>
            <td style="width:285px">
              <?php if(!$v['bind']){ ?>
            	 <button type="button" class="btn btn-link apply" data-id="<?php echo $v['id']; ?>"><?php echo $_LANG['zjmf_ssh_key_bind']; ?></button>
              <?php } ?>
              <?php if($v['can_delete']){ ?>
            	<button type="button" class="btn btn-link deleteGroup redtxt" data-id="<?php echo $v['id']; ?>"><?php echo $_LANG['zjmf_client_nat_web_del']; ?></button>
              <?php } ?>
            </td>
        </tr>
        <?php } ?>
    </tbody>
  </table>
  <div style="display: none" id="loading-circle">
    <div class="loading_limit">
      <div class="loading_inner">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>
    </div>
  </div>
  <script src="modules/servers/zjmfcloud/templates/server_innerpage/lib/embed/layui.js"></script>
  <script src="modules/servers/zjmfcloud/templates/server_innerpage/lib/embed/selectFilter.js"></script>
  <script>
    
  
    var host_type = '<?php echo $host_type; ?>';

  	function getUrlParam(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
		var r = window.location.search.substr(1).match(reg);  //匹配目标参数
		if (r != null) return decodeURI(r[2]); return null; //返回参数值
	}
    // 初始化下拉选择
    // $('.direction').selectFilter({
    //   callBack: function (val) {
    //     console.log(val + '是返回的值')
    //   }
    // });
    // $('.action').selectFilter({
    //   callBack: function (val) {
    //     // console.log(val + '是返回的值')
    //   }
    // });
    // $('.protocol').selectFilter({
    //   callBack: function (val) {
    //     let port = $("select[name='protocol']").find('option:selected').data('port')
    //     if(port){
    //       if(port == '1-65535'){
    //         $('#portRange').val('1-65535')
    //         $('#startPort').val('1')
    //         $('#endPort').val('65535')
    //       }else{
    //         $('#portRange').val(port)
    //         $('#startPort').val(port)
    //         $('#endPort').val(port)
    //       }
    //       $('#portRange').attr("disabled",true);
    //       $('#startPort').attr("disabled",true);
    //       $('#endPort').attr("disabled",true);
    //     }else{
    //       $('#portRange').val('')
    //       $('#startPort').val('')
    //       $('#endPort').val('')
    //       $('#portRange').removeAttr("disabled");
    //       $('#startPort').removeAttr("disabled");
    //       $('#endPort').removeAttr("disabled");
    //     }
    //   }
    // });

    // ssh 绑定
    $('.apply').on('click', function () {
      apply_btn = $(this)
      var id = $(this).data("id")
      Swal.fire({
        position: 'top',
        title: "<?php echo $_LANG['zjmf_confirm_bind_this_ssh_key']; ?>",
        type: 'question',
        showCancelButton: true,
        confirmButtonColor: '#6e9aff',
        cancelButtonColor: '#d33',
        confirmButtonText: "<?php echo $_LANG['zjmf_client_nat_web_confirm']; ?>",
        cancelButtonText: "<?php echo $_LANG['zjmf_layer_cancel']; ?>"
      }).then((result) => {
        if (result.value) {
          apply_btn.html($('#loading-circle').html());
          apply_btn.data('disabled', 'true')
          ajax({
              type:"post",
			  url:"clientarea.php?action=productdetails&id="+getUrlParam('id')+"&ac=ssh_key",
              data:{"func":"bindSSHKey","ssh_key_id":id},
              success:function(data){
                  if(data.status==200){
                      Swal.fire({
                        position: 'top',
                        title: "<?php echo $_LANG['zjmf_bind_success']; ?>",
                        type: 'success',
                        confirmButtonColor: '#6e9aff',
                      }).then((isConfirm) => window.location.reload());
                  }else{
                       apply_btn.html("<?php echo $_LANG['zjmf_ssh_key_bind']; ?>")
                      apply_btn.data('disabled', 'false')
                      Swal.fire("<?php echo $_LANG['zjmf_bind_fail']; ?>", data.msg, "error");
                  }
                  
              }
          })
        }
      })
    });

    // 安全组行内 删除按钮
    $('.deleteGroup').on('click', function () {
      delete_group_btn = $(this)
      var id = $(this).data("id")
      Swal.fire({
        position: 'top',
        title: "<?php echo $_LANG['zjmf_confirm_delete_ssh_key']; ?>",
        type: 'question',
        showCancelButton: true,
        confirmButtonColor: '#6e9aff',
        cancelButtonColor: '#d33',
        confirmButtonText: "<?php echo $_LANG['zjmf_client_nat_web_confirm']; ?>",
        cancelButtonText: "<?php echo $_LANG['zjmf_layer_cancel']; ?>"
      }).then((result) => {
        if (result.value) {
          delete_group_btn.html($('#loading-circle').html());
          delete_group_btn.data('disabled', 'true')
          ajax({
              type:"post",
			  url:"clientarea.php?action=productdetails&id="+getUrlParam('id')+"&ac=ssh_key",
              data:{"func":"deleteSSHKey","ssh_key_id":id},
              success:function(data){
                  if(data.status==200){
                      Swal.fire({
                        position: 'top',
                        title: "<?php echo $_LANG['zjmf_check_security_delete_success']; ?>",
                        type: 'success',
                        confirmButtonColor: '#6e9aff',
                      }).then((isConfirm) => window.location.reload());
                  }else{
                      delete_group_btn.html("<?php echo $_LANG['zjmf_client_nat_web_del']; ?>");
                      delete_group_btn.data('disabled', 'false')
                      Swal.fire("<?php echo $_LANG['zjmf_check_security_delete_error']; ?>", data.msg, "error");
                  }
              }
          })
        }
      })
    });

    // 策略删除
    $(document).on('click', '.deleteStrategy', function () {
      if($(this).data('disabled') == 'true'){
          return;
      }
      delete_rule_btn = $(this)
      var id = $(this).data("id")
      var group = $(this).data('group')
      Swal.fire({
        position: 'top',
        title: "<?php echo $_LANG['zjmf_client_security_rules_del_info_qos']; ?>",
        type: 'question',
        showCancelButton: true,
        confirmButtonColor: '#6e9aff',
        cancelButtonColor: '#d33',
        confirmButtonText: "<?php echo $_LANG['zjmf_client_nat_web_del_confirm']; ?>",
        cancelButtonText: "<?php echo $_LANG['zjmf_layer_cancel']; ?>"
      }).then((result) => {
        if (result.value) {
          delete_rule_btn.html($('#loading-circle').html());
          delete_rule_btn.data('disabled', 'true');
          ajax({
              type:"post",
              url:"clientarea.php?action=productdetails&id="+getUrlParam('id')+"&ac=safe",
              data:{"func":"delSecurityRule","SecurityRuleId":id,"group":group},
              success:function(data){
                  if(data.status==200){
                      Swal.fire({
                        position: 'top',
                        title: "<?php echo $_LANG['zjmf_check_security_delete_success']; ?>",
                        type: 'success',
                        confirmButtonColor: '#6e9aff',
                      }).then((isConfirm) => window.location.reload());
                  }else{
                      delete_rule_btn.html("<?php echo $_LANG['zjmf_client_nat_web_del']; ?>")
                      delete_rule_btn.data('disabled', 'false')
                      Swal.fire("<?php echo $_LANG['zjmf_check_security_delete_error']; ?>", data.msg, "error");
                  }
                  
              }
          })
        }
      })
    });

    // 新增策略表单验证
    function checkForm() {
      
    }

    // 关闭模态框
    function closeAddModal() {
      const IP = document.getElementById("IP"); // 输入框的值
      const startIP = document.getElementById("startIP"); // 输入框的值
      const endIP = document.getElementById("endIP"); // 输入框的值
      const startPort = document.getElementById("startPort"); // 输入框的值
      const endPort = document.getElementById("endPort"); // 输入框的值
      const priority = document.getElementById("priority"); // 输入框的值
      const description = document.getElementById("description");

      removeValid(IP);
      removeValid(startIP);
      removeValid(endIP);
      removeValid(startPort);
      removeValid(endPort);
      removeValid(priority);

      if(IP) IP.value = ''
      if(startIP) startIP.value = ''
      if(endIP) endIP.value = ''
      if(startPort) startPort.value = ''
      if(endPort) endPort.value = ''
      if(priority) priority.value = ''
      description.value = ''
      
      $('.invalid-feedback').html('')
    }

    function addId(_this){
      $("#addModal").find("input[name='SecurityGroupId']").val(_this.data("id"))
    }

    $('.createSecurityGroup').on('click', function () {
      if(!$(this).data('submit')){
        $(this).html($('#loading-circle').html());
        $(this).data('submit', 'submit')
        ajax({
            type:"post",
			url:"clientarea.php?action=productdetails&id="+getUrlParam('id')+"&ac=ssh_key",
            data:$("#myModal").find("form").serialize() + "&func=createSSHKey",
            success:function(data){
                $(".createSecurityGroup").html("<?php echo $_LANG['zjmf_client_nat_web_confirm']; ?>")
                $(".createSecurityGroup").data('submit','')
                if(data.status==200){
                    $("#myModal").modal('hide')
                    // 下载ssh密钥
                
                    if (data.data.key) {
                      const str = new Blob([data.data.key], {
                        type: 'text/plain;charset=utf-8'
                      })
                      saveAs(str, $("#myModal").find("form").serialize().split('&').find(item => item.includes('name')).split('=')[1] + '.pem')
                    }
                    Swal.fire({
                      position: 'top',
                      title: '<?php echo $_LANG['zjmf_create_ssh_key_success']; ?>',
                      type: 'success',
                      confirmButtonColor: '#6e9aff',
                    }).then((isConfirm) => {
                      window.location.reload()
                    });
                }else{
                    Swal.fire("<?php echo $_LANG['zjmf_create_ssh_key_fail']; ?>", data.msg, "error");
                }
            },
            error:function(){
              $(".createSecurityGroup").html("<?php echo $_LANG['zjmf_client_nat_web_confirm']; ?>")
              $(".createSecurityGroup").data('submit','')
            }
        })
      }
    });

  function addError(obj){
    if(!obj) return;
    obj.classList.remove("is-valid"); //清除合法状态
    obj.classList.add("is-invalid"); //添加非法状态
  }

  function removeError(obj){
    if(!obj) return;
    obj.classList.remove("is-invalid");
    obj.classList.add("is-valid");
  }

  function removeValid(obj){
    if(!obj) return;
    obj.classList.remove("is-invalid");
    obj.classList.remove("is-valid");
  }

  function ajax(options){
      //创建一个ajax对象
      var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft,XMLHTTP");
      //数据的处理 {a:1,b:2} a=1&b=2;
      if(typeof(options.data)!='string'){
          var str = "";
          for(var key in options.data){
              str+="&"+key+"="+options.data[key];
          }
          str = str.slice(1)
      }else{
          var str = options.data;
      }
      console.log(str);
      options.dataType=options.dataType||'json';
      if(options.type == "get"){
          var url = options.url+"?"+str;
          xhr.open("get",url);
          // xhr.setRequestHeader("Authorization","JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaW5mbyI6eyJpZCI6MjM0LCJ1c2VybmFtZSI6Ilx1NGUwZFx1ODk4MVx1NjRjZFx1NGY1Y1x1OGZkOVx1NGUyYVx1OGQyNlx1NjIzNyJ9LCJpc3MiOiJ3d3cuaWRjU21hcnQuY29tIiwiYXVkIjoid3d3LmlkY1NtYXJ0LmNvbSIsImlwIjoiMjIyLjE4Mi41Ny4yMjMiLCJpYXQiOjE2MDM3MDg0ODMsIm5iZiI6MTYwMzcwODQ4MywiZXhwIjoxNjAzNzE1NjgzfQ.wfNwLHkBb_lMA7CQgOTcbfhxeEAZJ02a7RRWWENiOVs");
          xhr.send();
      }else if(options.type == "post"){
          xhr.open("post",options.url);
          xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
          // xhr.setRequestHeader("Authorization","JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaW5mbyI6eyJpZCI6MjM0LCJ1c2VybmFtZSI6Ilx1NGUwZFx1ODk4MVx1NjRjZFx1NGY1Y1x1OGZkOVx1NGUyYVx1OGQyNlx1NjIzNyJ9LCJpc3MiOiJ3d3cuaWRjU21hcnQuY29tIiwiYXVkIjoid3d3LmlkY1NtYXJ0LmNvbSIsImlwIjoiMjIyLjE4Mi41Ny4yMjMiLCJpYXQiOjE2MDM3MDg0ODMsIm5iZiI6MTYwMzcwODQ4MywiZXhwIjoxNjAzNzE1NjgzfQ.wfNwLHkBb_lMA7CQgOTcbfhxeEAZJ02a7RRWWENiOVs");
          xhr.send(str)
      }
      //监听
      xhr.onreadystatechange = function(){
          //当请求成功的时候
          if(xhr.readyState == 4 && xhr.status == 200){
              var d = xhr.responseText;
              d = JSON.parse(d);
              //将请求的数据传递给成功回调函数
              options.success&&options.success(d,xhr.responseXML)
          }else if(xhr.status != 200){
              //当失败的时候将服务器的状态传递给失败的回调函数
              options.error&&options.error(xhr.status);
          }
      }
  }
  </script>
  
  <script>
    $('.way input[value="0"]').attr('checked', true)
    let curWay = 0
    $('#pubilc-key').hide()
    function changeWay (e) {
      curWay = e
      if (curWay === 0) {
        $('#pubilc-key').hide()
      } else {
        $('#pubilc-key').show()
      }
    }
  </script>
</body>

</html>