<!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_client_security'] ; ?></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>

  <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_client_security_create'] ; ?></button>
  </div>
  <div class="container">
    <!-- 新建安全组模态框 -->
    <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_client_security_create'] ; ?></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>
                <input style="width:48%" name="name" type="text" placeholder="<?php echo $_LANG['zjmf_client_security_name'] ; ?>" class="form-control" id="name">
                <input style="width:48%" name="description" type="text" placeholder="<?php echo $_LANG['zjmf_client_security_description'] ; ?>" class="form-control" id="remark">
                </form>
              </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 class="modal fade" id="addModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <span class="modal-title"><?php echo $_LANG['zjmf_client_security_rules_new'] ; ?></span>
            <button type="button" class="close" data-dismiss="modal" onclick="closeAddModal()">&times;</button>
          </div>

          <!-- 模态框主体 -->
          <div class="modal-body">
            <div class="modal_limit">
              <div class="modal_main">
                <form>
                  <input type="hidden" name="SecurityGroupId">
                  <?php if($host_type != 'host'){ ?>
                  <div class="form-group">
                    <label for="action"><?php echo $_LANG['zjmf_client_security_rules_action']; ?></label>
                    <div class="selectItem">
                      <div class="action">
                        <div class="filter-text">
                          <input class="filter-title" type="text" readonly placeholder="<?php echo $_LANG['zjmf_client_security_rules_select'] ; ?>" />
                          <i class="icon icon-filter-arrow"></i>
                        </div>
                        <select name="_action">
                          <option value="accept"><?php echo $_LANG['zjmf_client_security_rules_action_allow']; ?></option>
                          <option value="drop"><?php echo $_LANG['zjmf_client_security_rules_action_deny']; ?></option>
                        </select>
                      </div>
                    </div>
                  </div>
                  <?php } ?>
                  <div class="form-group">
                    <label for="direction"><?php echo $_LANG['zjmf_client_security_rules_direction'] ; ?></label>
                    <div class="selectItem">
                      <div class="direction">
                        <div class="filter-text">
                          <input class="filter-title" type="text" readonly placeholder="<?php echo $_LANG['zjmf_client_security_rules_select'] ; ?>" />
                          <i class="icon icon-filter-arrow"></i>
                        </div>
                        <select name="direction">
                          <option value="out"><?php echo $_LANG['zjmf_client_security_rules_out'] ; ?></option>
                          <option value="in"><?php echo $_LANG['zjmf_client_security_rules_in'] ; ?></option>
                        </select>
                      </div>
                    </div>
                  </div>
                  <div class="form-group">
                    <label for="protocol"><?php echo $_LANG['zjmf_client_nat_web_agree'] ; ?></label>
                    <div class="selectItem">
                      <div class="protocol">
                        <div class="filter-text">
                          <input class="filter-title" type="text" readonly placeholder="<?php echo $_LANG['zjmf_client_security_rules_select'] ; ?>" />
                          <i class="icon icon-filter-arrow"></i>
                        </div>
                        <select name="protocol">
						  <?php foreach($security_group_rule_protocols as $v){ ?>	
                          <option value="<?php echo $v['value']; ?>" data-port="<?php echo $v['port']; ?>"><?php echo $v['name']; ?></option>
						  <?php } ?>
                        </select>
                      </div>
                    </div>
                  </div>
                  <?php if($host_type == 'host'){ ?>
                  <div class="form-group">
                    <label for="portRange">
                      <span style="color:#f00">*</span>
                      <?php echo $_LANG['zjmf_client_security_rules_port'] ; ?></label>
                    <input required name="port" type="input" class="form-control" id="portRange" placeholder="<?php echo $_LANG['zjmf_client_security_rules_port_example'] ; ?>">
                    <div class="invalid-feedback" id="port-feedback"></div>
                  </div>
                  <?php }else{ ?>
                  <div class="form-group">
                    <label for="startPort">
                      <span style="color:#f00">*</span>
                      <?php echo $_LANG['zjmf_client_security_rules_port'] ; ?></label>
                      <div class="col-12 row">
                        <input required name="start_port" type="input" class="form-control col-5" id="startPort" placeholder="<?php echo $_LANG['zjmf_client_security_rules_start_port']; ?>">
                        <span class="col-1"></span>
                        <input required name="end_port" type="input" class="form-control col-5" id="endPort" placeholder="<?php echo $_LANG['zjmf_client_security_rules_end_port']; ?>">
                      </div>
                      <div class="invalid-feedback" id="port-feedback"></div>
                  </div>
                  <?php } ?>
                  <?php if($host_type == 'lightHost'){ ?>
                    <div class="form-group">
                    <label for="IP">
                      <span style="color:#f00">*</span>
                      <?php echo $_LANG['zjmf_client_security_rules_ip'] ; ?>
                    </label>
                    <div class="col-12 row">
                      <input required name="start_ip" type="input" class="form-control col-5" id="startIP" placeholder="<?php echo $_LANG['zjmf_client_security_rules_start_ip']; ?>">
                      <span class="col-1"></span>
                      <input required name="end_ip" type="input" class="form-control col-5" id="endIP" placeholder="<?php echo $_LANG['zjmf_client_security_rules_end_ip']; ?>">
                    </div>
                    <div class="invalid-feedback" id="IP-feedback"></div>
                  </div>
                  <div class="form-group">
                    <label for="priority">
                      <span style="color:#f00">*</span>
                      <?php echo $_LANG['zjmf_client_security_rules_priority']; ?>
                    </label>
                    <input required name="priority" type="input" class="form-control" id="priority" placeholder="<?php echo $_LANG['zjmf_client_security_rules_priority_placeholder']; ?>">
                    <div class="invalid-feedback" id="priority-feedback"></div>
                  </div>
                  <?php }else{ ?>
                  <div class="form-group">
                    <label for="IP">
                      <span style="color:#f00">*</span>
                      <?php echo $_LANG['zjmf_client_security_rules_ip'] ; ?>
                    </label>
                    <input required name="ip" type="input" class="form-control" id="IP" placeholder="<?php echo $_LANG['zjmf_client_security_rules_ip_example'] ; ?>">
                    <div class="invalid-feedback" id="IP-feedback"></div>
                  </div>
                  <?php } ?>
                  <div class="form-group">
                    <label for="description"><?php echo $_LANG['zjmf_client_security_rules_desc'] ; ?></label>
                    <textarea name="description" class="form-control" rows="5" id="description"></textarea>
                  </div>
                </form>
              </div>
              <div class="footer">
                <button type="button" class="btn confirm-btn createSecurityRule" 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_client_nat_acl_name_placeholder'] ; ?></th>
        <th><?php echo $_LANG['zjmf_client_security_rules_desc'] ; ?></th>
        <th style="width:285px"><?php echo $_LANG['zjmf_client_nat_web_operation'] ; ?></th>
      </tr>
    </thead>
    <tbody>
		<?php foreach($securityGroups as $v){
			$checked="";
			foreach($v['host'] as $host){
			if($host['id']==$hostid) $checked="（{$_LANG['zjmf_client_security_rules_check_host']}）";
			}
			?>
		<tr>
        <td><?php echo $v['name'].$checked; ?></td>
        <td><?php echo $v['description']; ?></td>
			<td style="width:300px">
				<?php if($checked){ ?>
				<button type="button" class="btn btn-link trView" data-id="<?php echo $v['id']; ?>"><?php echo $_LANG['zjmf_client_security_rules_see'] ; ?></button>
			    <button type="button" class="btn btn-link" data-toggle="modal" data-target="#addModal" data-id="<?php echo $v['id']; ?>" onclick="addId($(this))"><?php echo $_LANG['zjmf_client_security_rules_new'] ; ?></button>
				<?php }else{ ?>				
				<button type="button" class="btn btn-link apply" data-id="<?php echo $v['id']; ?>"><?php echo $_LANG['zjmf_client_security_rules_link'] ; ?></button>
				<button type="button" class="btn btn-link trView" data-id="<?php echo $v['id']; ?>"><?php echo $_LANG['zjmf_client_security_rules_see'] ; ?></button>
			    <button type="button" class="btn btn-link" data-toggle="modal" data-target="#addModal" data-id="<?php echo $v['id']; ?>" onclick="addId($(this))"><?php echo $_LANG['zjmf_client_security_rules_new'] ; ?></button>
				<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");
        }
      }
    });
    

    // 安全组行内 查看按钮
    /*$('.trView').on('click', function () {
      $(this).parent().parent().next('.expandLine').toggle();
    });*/

    // 安全组行内 应用按钮
    $('.apply').on('click', function () {
      if($(this).data('disabled') == 'true'){
          return;
      }
      apply_btn = $(this)
      var id = $(this).data("id")
      Swal.fire({
        position: 'top',
        title: "<?php echo $_LANG['zjmf_client_security_rules_link_confirm'] ; ?>",
        type: 'question',
        showCancelButton: true,
        confirmButtonColor: '#6e9aff',
        cancelButtonColor: '#d33',
        confirmButtonText: "<?php echo $_LANG['zjmf_client_security_rules_link_confirm_y'] ; ?>",
        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=safe",
              data:{"func":"linkSecurityGroup","SecurityGroupId":id},
              success:function(data){
                  if(data.status==200){
                      Swal.fire({
                        position: 'top',
                        title: "<?php echo $_LANG['zjmf_check_security_link_success'] ; ?>",
                        type: 'success',
                        confirmButtonColor: '#6e9aff',
                      }).then((isConfirm) => window.location.reload());
                  }else{
                      apply_btn.html("<?php echo $_LANG['zjmf_client_security_rules_link'] ; ?>")
                      apply_btn.data('disabled', 'false')
                      Swal.fire("<?php echo $_LANG['zjmf_check_security_link_error'] ; ?>", data.msg, "error");
                  }
                  
              }
          })
        }
      })
    });

    // 安全组行内 删除按钮
    $('.deleteGroup').on('click', function () {
      if($(this).data('disabled') == 'true'){
          return;
      }
      delete_group_btn = $(this)
      var id = $(this).data("id")
      Swal.fire({
        position: 'top',
        title: "<?php echo $_LANG['zjmf_client_security_rules_del_info']; ?>",
        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_group_btn.html($('#loading-circle').html());
          delete_group_btn.data('disabled', 'true')
          ajax({
              type:"post",
			  url:"clientarea.php?action=productdetails&id="+getUrlParam('id')+"&ac=safe",
              data:{"func":"delSecurityGroup","SecurityGroupId":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"))
    }

    // 点击查看控制显隐
    $(document).on('click','.trView', function () {
        var id = $(this).data("id");
        if($("#view_"+id).length>0){
            $("#view_"+id).remove()
        }else{
            var _this = $(this)
            ajax({
                type:"post",
                url:"clientarea.php?action=productdetails&id="+getUrlParam('id')+"&ac=safe",
                data:{"func":"showSecurityRules","SecurityGroupId":id},
                success:function(data){
                    if(host_type == 'hyperv'){
                      var _html = '<tr class="expandLine" id="view_'+id+'"><td colspan="3"><table class="layui-table"><thead><tr><th><?php echo $_LANG["zjmf_client_security_rules_description"]; ?></th><th><?php echo $_LANG['zjmf_client_security_rules_action']; ?></th><th><?php echo $_LANG["zjmf_client_security_rules_direction"];?></th><th><?php echo $_LANG["zjmf_client_nat_web_agree"];?></th><th><?php echo $_LANG["zjmf_client_security_rules_port"];?></th><th><?php echo $_LANG["zjmf_client_security_rules_ip"];?></th><th style="width:110px"><?php echo $_LANG["zjmf_client_nat_web_operation"];?></th></tr>'
                      $.each(data.list,function(i,v){
                          _html += '<tr style="text-indent: 18px;"><td>'+v.description+'</td><td>'+ (v.action == 'accept' ? '<?php echo $_LANG['zjmf_client_security_rules_action_allow']; ?>' : '<?php echo $_LANG['zjmf_client_security_rules_action_deny']; ?>') +'</td><td>'+ (v.direction == 'in' ? '<?php echo $_LANG['zjmf_client_security_rules_in'];?>' : '<?php echo $_LANG['zjmf_client_security_rules_out'];?>') +'</td><td>'+v.protocol+'</td><td>'+ (v.start_port == v.end_port ? v.start_port : v.start_port+'-'+v.end_port ) +'</td><td>'+v.ip+'</td><td><button type="button" data-id="'+v.id+'" data-group="'+id+'" class="btn btn-link deleteStrategy redtxt"><?php echo $_LANG["zjmf_client_nat_web_del"];?></button></td></tr>'
                      })
                    }else if(host_type == 'lightHost'){
                      var _html = '<tr class="expandLine" id="view_'+id+'"><td colspan="3"><table class="layui-table"><thead><tr><th><?php echo $_LANG["zjmf_client_security_rules_description"]; ?></th><th><?php echo $_LANG['zjmf_client_security_rules_action']; ?></th><th><?php echo $_LANG["zjmf_client_security_rules_direction"];?></th><?php echo $_LANG["zjmf_client_nat_web_agree"];?><th><?php echo $_LANG["zjmf_client_security_rules_port"];?></th><th><?php echo $_LANG["zjmf_client_security_rules_ip"];?></th><th>优先级</th><th style="width:110px"><?php echo $_LANG["zjmf_client_nat_web_operation"];?></th></tr>'
                      $.each(data.list,function(i,v){
                          _html += '<tr style="text-indent: 18px;"><td>'+v.description+'</td><td>'+ (v.action == 'accept' ? '<?php echo $_LANG['zjmf_client_security_rules_action_allow']; ?>' : '<?php echo $_LANG['zjmf_client_security_rules_action_deny']; ?>') +'</td><td>'+ (v.direction == 'in' ? '<?php echo $_LANG['zjmf_client_security_rules_in'];?>' : '<?php echo $_LANG['zjmf_client_security_rules_out'];?>') +'</td><td>'+v.protocol+'</td><td>'+(v.start_port == v.end_port ? v.start_port : v.start_port+'-'+v.end_port )+'</td><td>'+v.start_ip+'-'+v.end_ip+'</td><td>'+v.priority+'</td><td><button type="button" data-id="'+v.id+'" data-group="'+id+'" class="btn btn-link deleteStrategy redtxt"><?php echo $_LANG["zjmf_client_nat_web_del"];?></button></td></tr>'
                      })
                    }else{
                      var _html = '<tr class="expandLine" id="view_'+id+'"><td colspan="3"><table class="layui-table"><thead><tr><th style="min-width: 160px;"><?php echo $_LANG["zjmf_client_security_rules_description"]; ?></th><th style="min-width: 90px;"><?php echo $_LANG["zjmf_client_security_rules_direction"];?></th><th><?php echo $_LANG["zjmf_client_nat_web_agree"];?></th><th style="min-width: 120px;"><?php echo $_LANG["zjmf_client_security_rules_port"];?></th><th><?php echo $_LANG["zjmf_client_security_rules_ip"];?></th><th style="width:110px"><?php echo $_LANG["zjmf_client_nat_web_operation"];?></th></tr>'
                      $.each(data.list,function(i,v){
                          _html += '<tr style="text-indent: 18px;"><td>'+v.description+'</td><td>'+ (v.direction == 'in' ? "<?php echo $_LANG['zjmf_client_security_rules_in'];?>" : "<?php echo $_LANG['zjmf_client_security_rules_out'];?>") +'</td><td>'+v.protocol+'</td><td>'+v.port+'</td><td>'+v.ip+'</td><td><button type="button" data-id="'+v.id+'" data-group="'+id+'" class="btn btn-link deleteStrategy redtxt"><?php echo $_LANG["zjmf_client_nat_web_del"];?></button></td></tr>'
                      })
                    }
                    _html += '</thead></table></td></tr>'
                    _this.parents("tr").after(_html)
                    _this.parent().parent().next('.expandLine').toggle()
                }
            })
        }
    })

    $('.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=safe",
            data:$("#myModal").find("form").serialize() + "&func=createSecurityGroup",
            success:function(data){
                $(".createSecurityGroup").html("<?php echo $_LANG['zjmf_client_nat_web_confirm']; ?>")
                $(".createSecurityGroup").data('submit','')
                if(data.status==200){
                    $("#myModal").modal('hide')
                    Swal.fire({
                      position: 'top',
                      title: "<?php echo $_LANG['zjmf_check_security_success']; ?>",
                      type: 'success',
                      confirmButtonColor: '#6e9aff',
                    }).then((isConfirm) => window.location.reload());
                }else{
                    Swal.fire("<?php echo $_LANG['zjmf_check_security_error']; ?>", data.msg, "error");
                }
            },
            error:function(){
              $(".createSecurityGroup").html("<?php echo $_LANG['zjmf_client_nat_web_confirm']; ?>")
              $(".createSecurityGroup").data('submit','')
            }
        })
      }
    });

  $('.createSecurityRule').on('click', function () {
      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 IPfeedback = document.getElementById("IP-feedback"); // 输入框的验证提示
      const portRange = document.getElementById("portRange"); // 输入框的值
      const portFeedback = document.getElementById("port-feedback"); // 输入框的验证提示
      const priorityFeedback = document.getElementById("priority-feedback"); // 输入框的验证提示

      //不能为空
      function testRange (num) {
      if (/^[0-9]\d*$/.test(num) && parseInt(num) <= 65535 && parseInt(num) > 0) {
          return true
        } else {
          return false
        }
      }
      let result = false
      if(portRange){
        let arr = portRange.value.split(',')
        let isError = 0
        arr.forEach(e => {
          const val = e.split('-')
          if (val.length == 1 && testRange(val[0])) {
            // callback()
            isError++
          } else if (val.length == 2 && val[1] >= val[0] && testRange(val[1]) && testRange(val[0])) {
            // callback()
            isError++
          } else {
            result = false
          }
        })
        if (isError == arr.length) {
          result = true
        }
        if (portRange.value === ""||!result) {
          portFeedback.innerHTML = "<?php echo $_LANG['zjmf_client_security_rules_port_check']; ?>";
          portRange.classList.remove("is-valid"); //清除合法状态
          portRange.classList.add("is-invalid"); //添加非法状态
          return true
        } else {
          portRange.classList.remove("is-invalid");
          portRange.classList.add("is-valid");
          portFeedback.innerHTML = "";
        }
      }
      if(startPort && endPort){
        let start_port_error = false
        let end_port_error = false
        if(startPort.value<1 || startPort.value>65535){
          start_port_error = true
        }
        if(endPort.value<1 || endPort.value>65535){
          end_port_error = true
        }
        if(startPort.value > endPort.value){
          start_port_error = true
          end_port_error = true
        }
        if(start_port_error || end_port_error){
          portFeedback.innerHTML = "<?php echo $_LANG['zjmf_client_security_rules_port_check']; ?>";
          if(start_port_error){
            addError(startPort)
          }else{
            removeError(startPort)
          }
          if(end_port_error){
            addError(endPort)
          }else{
            removeError(endPort)
          }
          return true
        }else{
          removeError(startPort)
          removeError(endPort)
          portFeedback.innerHTML = "";
        }
      }
      //ip
      let ipTest = false
      if(IP){
        const val = IP.value.split('/')
        if (/^((25[0-5]|2[0-4]\d|[01]?\d\d?)($|(?!\.$)\.)){4}$/.test(val[0]) && val.length == 1) {
          ipTest = true
        } else if (/^((25[0-5]|2[0-4]\d|[01]?\d\d?)($|(?!\.$)\.)){4}$/.test(val[0]) && val.length == 2 && parseInt(val[1]) <= 65535 && parseInt(val[1]) >= 0) {
          ipTest = true
        } else {
          ipTest = false
        }
        if (IP.value === ""&&!ipTest) {
          IPfeedback.innerHTML = "<?php echo $_LANG['zjmf_client_security_rules_ip_check']; ?>";
          IP.classList.remove("is-valid"); //清除合法状态
          IP.classList.add("is-invalid"); //添加非法状态
          return true
        } else {
          //清除错误提示，改成成功提示
          IP.classList.remove("is-invalid");
          IP.classList.add("is-valid");
          IPfeedback.innerHTML = "";
        }
      }
      if(startIP && endIP){
        let start_ip_error = false
        let end_ip_error = false
        if (!/^((25[0-5]|2[0-4]\d|[01]?\d\d?)($|(?!\.$)\.)){4}$/.test(startIP.value)){
          start_ip_error = true
        }
        if (!/^((25[0-5]|2[0-4]\d|[01]?\d\d?)($|(?!\.$)\.)){4}$/.test(endIP.value)){
          end_ip_error = true
        }
        if(!start_ip_error && !end_ip_error){
          if(startIP.value.replace('.', '') > endIP.value.replace('.', '')){
            start_ip_error = true
            end_ip_error = true
          }
        }
        if(start_ip_error || end_ip_error){
          IPfeedback.innerHTML = "<?php echo $_LANG['zjmf_client_security_rules_ip_check']; ?>";
          if(start_ip_error){
            addError(startIP)
          }else{
            removeError(startIP)
          }
          if(end_ip_error){
            addError(endIP)
          }else{
            removeError(endIP)
          }
          return true
        }else{
          removeError(startIP)
          removeError(endIP)
          IPfeedback.innerHTML = "";
        }
      }
      if(priority){
        if(priority.value<1 || priority.value>1000){
          priorityFeedback.innerHTML = "<?php echo $_LANG['zjmf_client_security_rules_priority_check']; ?>";
          addError(priority)
          return true;
        }else{
          priorityFeedback.innerHTML = "";
          removeError(priority)
        }
      }

    if(!$(this).data('submit')){
      $(this).data('submit', 'submit')
      ajax({
          type:"post",
          url:"clientarea.php?action=productdetails&id="+getUrlParam('id')+"&ac=safe",
          data:$("#addModal").find("form").serialize() + "&func=createSecurityRule",
          success:function(data){
              $(".createSecurityRule").data('submit','')
              if(data.status==200){
                  $("#addModal").modal('hide')
                  Swal.fire({
                    position: 'top',
                    title: "<?php echo $_LANG['zjmf_check_security_success']; ?>",
                    type: 'success',
                    confirmButtonColor: '#6e9aff',
                  }).then((isConfirm) => window.location.reload());
              }else{
                  Swal.fire("<?php echo $_LANG['zjmf_check_security_error']; ?>", data.msg, "error");
              }
          },
          error:function(){
            $(".createSecurityRule").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>
</body>

</html>