<div class="uk-layui-form">
	<form class="layui-form uk-form" action="/admin/user/save.html">
	  <div class="layui-form-item">
	    <label class="layui-form-label">用户名：</label>
	    <div class="layui-input-inline">
	      <input type="text" name="username" required lay-verify="required_username" placeholder="请输入用户名" autocomplete="off" class="layui-input">
	    </div>
	    <div class="layui-form-mid layui-word-aux">用户登录的账号</div>
	  </div>
	  <div class="layui-form-item">
	    <label class="layui-form-label">姓名：</label>
	    <div class="layui-input-inline">
	      <input type="text" name="uname" required lay-verify="required_name" placeholder="请输入用户姓名" autocomplete="off" class="layui-input">
	    </div>
	  </div>
	  <div class="layui-form-item">
	    <label class="layui-form-label">电子邮件：</label>
	    <div class="layui-input-inline">
	      <input type="email" name="email" placeholder="请输入电子邮件地址" autocomplete="off" class="layui-input">
	    </div>
	  </div>
	  <div class="layui-form-item">
	    <label class="layui-form-label">密码：</label>
	    <div class="layui-input-inline">
	      <input type="password" id="password" name="password" required lay-verify="required|pass" placeholder="请输入登录密码" autocomplete="off" class="layui-input">
	    </div>
	    <div class="layui-form-mid layui-word-aux" style="padding-top: 5px;padding-bottom: 0px">
	    	<input type="password" id="repassword" name="repassword" required lay-verify="repass" placeholder="请再次输入密码" autocomplete="off" class="layui-input">
	    </div>
	  </div>
	  <div class="layui-form-item">
	    <label class="layui-form-label">手机号：</label>
	    <div class="layui-input-inline">
	      <input type="mobile" name="mobile"  placeholder="请输入手机号码" autocomplete="off" class="layui-input">
	    </div>
	  </div>

		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">组织机构：</label>
				<div class="layui-input-inline" style="position: relative;">
					<input type="hidden" id="parent" name="parent" value="<#if currentOrgan??>${currentOrgan.id}<#else>0</#if>">
					<input type="text" name="parentname" id="parentname" required value="<#if currentOrgan??>${currentOrgan.name}<#else>组织机构</#if>" lay-verify="requiredTwo" autocomplete="off" readOnly="readonly" onClick="showMenu();"
						   class="layui-input">
					<i class="layui-icon" style="position: absolute;right: 3px;top: 6px;font-size: 25px;${systemConfig.color!'color:#0096C4;'}" onClick="showMenu()">&#xe631;</i>
					<div id="menuContent" style="display:none; position: absolute;z-index:10000;width: 218px;" class="ukefu-ztree">
						<ul id="organTree" class="ztree" style="width:208px;"></ul>
					</div>
				</div>
			</div>
		</div>

	  <div class="layui-form-item">
	    <label class="layui-form-label">管理员：</label>
	    <div class="layui-input-inline">
	      <input type="checkbox" name="admin" lay-skin="switch" lay-filter="admincheckbox" value="1" lay-text="是|否">
	    </div>
        <div class="layui-form-mid layui-word-aux" style="padding: 0 0; line-height: 20px">管理员具备访问和修改所有系统资源的权限，同时也设定为多媒体坐席</div>
	  </div>
	  <div class="layui-form-item"  id="agentDiv">
	    <label class="layui-form-label">多媒体坐席：</label>
	    <div class="layui-input-inline">
	      <input type="checkbox" name="agent" lay-skin="switch" value="1" lay-filter="agent" lay-text="开启|关闭">
	    </div>
	  </div>
	  <#if models?seq_contains("callcenter")>
<!--	  <div class="layui-form-item" id="callcenterDiv">-->
<!--	    <label class="layui-form-label">呼叫中心坐席：</label>-->
<!--	    <div class="layui-input-inline">-->
<!--	      <input type="checkbox" name="callcenter" lay-skin="switch"  value="1" lay-filter="callcenter" lay-text="开启|关闭">-->
<!--			</div>-->
<!--			<div class="layui-form-mid layui-word-aux" id="sipAccountDiv">-->
<!--				<input type="text" id="sipAccount" name="sipaccount" lay-verify="sip"  placeholder="请输入SIP地址" autocomplete="off" class="layui-input">-->
<!--	    </div>-->
<!--	  </div>-->

		<div class="layui-form-item"  id="callcenter">
			<label class="layui-form-label">呼叫中心坐席：</label>
			<div class="layui-input-inline" style="margin-left:0px;">
				<input type="checkbox" name="callcenter" lay-skin="switch"  lay-filter="callcenter" value="1" lay-text="开启|关闭">
			</div>
		</div>
		<div class="layui-form-item" id="bindext_tip">
			<label class="layui-form-label">呼叫中心：</label>
			<div class="layui-input-inline">
				<select name="pbxhostid" lay-filter="hostid" id="callcenterhostid" lay-verify="callcenterhost" >
					<option value="">请选择呼叫中心</option>
				</select>
			</div>
			<div class="layui-form-mid" style="padding-top:5px !important;" id="extenttions">
				<select name="extensionid"  lay-verify="callcenterext" id="callcenterExtid">
					<option value="">请选择分机</option>
				</select>
			</div>
		</div>
	  </#if>
	  <div class="layui-form-button">
	    <div class="layui-button-block">
	      <button class="layui-btn" lay-submit lay-filter="sys-user-create">提交</button>
		  <button class="layui-btn" lay-submit lay-filter="sys-user-create-follow">提交并创建下一个</button>
	      <button type="reset" class="layui-btn layui-btn-warm">重置</button>
	    </div>
	  </div>
	</form>
</div>

<script>

layui.use('form', function(){
  var form = layui.form();
  form.render(); //更新全部
  form.verify({
	  repass: function(value){
	    if(value != $('#password').val()){
	      return '两次输入的密码不一致，请确认';
	    }
	  },
      sip: function(value) {
		if($("input[name=callcenter]:checked").length > 0 && value === ''){
            return 'SIP地址不能为空，请确认';
		}
      },
	  required_username: function (value) {
		  if (value.length > 50){
			  return "用户名不能超过50字";
		  }
	  },
	  required_name: function (value) {
		  if (value.length > 100){
			  return "用户姓名不能超过100字";
		  }
	  },
	  callcenterhost:function (value) {
		  if($("input[name=callcenter]:checked").length > 0 && value === ''){
			  return '呼叫中心不能为空，请确认';
		  }
	  },
	  callcenterext:function (value) {
		  if($("input[name=callcenter]:checked").length > 0 && value === ''){
			  return '分机不能为空，请确认';
		  }
	  }
	});

    // 当账号为管理员类型时，强制设定为坐席！
    form.on('switch(admincheckbox)', function(data){
        if(data.elem.checked){
            // 坐席的按钮
            if($('#agentDiv > div > div > em').text() == "关闭"){
                // 之前未开启
                document.querySelector('#agentDiv > div > div > i').click();
            }
            // 设置为禁用
            $("#agentDiv > div > input[name=agent]").attr('disabled', 'disabled');
        } else {
            // 取消禁用
            $("#agentDiv > div > input[name=agent]").removeAttr('disabled');
        }
    });

	$('#bindext_tip').hide();

	form.on('switch(callcenter)', function(data){
		if(data.elem.checked){
			$('#bindext_tip').show();
			restApiRequest({
				silent: true,
				path: 'callcenter',
				data: {
					ops: "my-pbxlist"
				}
			}).then(function(result){
				if(result.rc == 0){
					$("#callcenterhostid").html('<option value="">请选择呼叫中心</option>');
					if(result.data.length > 0){
						for (var i=0 ; i<result.data.length ; i++) {
							$("#callcenterhostid").append('<option value="' + result.data[i].id + '">' + result.data[i].name + '</option>')
						};
						form.render("select");
					}
				}
			}, function(err){
				handleRestApiFail(err);
			});
		}else{
			$('#bindext_tip').hide();
		}
	});

	form.on('select(hostid)', function(data){
		restApiRequest({
			silent: true,
			path: 'callcenter',
			data: {
				ops: "ext-dd-vacant",
				id:data.value
			}
		}).then(function(result){
			if(result.rc == 0){
				if(result.data.length > 0){
					$("#callcenterExtid").html('<option value="">请选择分机</option>');
					for (var i=0 ; i<result.data.length ; i++) {
						$("#callcenterExtid").append('<option value="' + result.data[i].id + '">' + result.data[i].extension + '</option>')
					};
					form.render("select");
				}
			}
		}, function(err){
			handleRestApiFail(err);
		});
	});

	// 根据“多媒体坐席”显示“呼叫中心坐席”状态
  	// form.on('switch(agent)', function(data){
    //     $("input[name=callcenter]").prop("checked", false);
    //     form.render('checkbox','callcenter');
	// 	if(data.elem.checked){
	// 		$('#callcenterDiv').show();
	// 	}else{
	// 		$('#callcenterDiv').hide();
	// 	}
    //     $('#sipAccount').val("");
    //     $('#sipAccountDiv').hide();
	// });

  	// 根据“呼叫中心坐席”状态 显示呼叫地址输入框
  	// form.on('switch(callcenter)', function(data){
    //     $('#sipAccount').val("");
	// 	if(data.elem.checked){
	// 		$('#sipAccountDiv').show();
	// 	}else{
	// 		$('#sipAccountDiv').hide();
	// 	}
	// });

  	form.on('submit(sys-user-create)', function (data) {
		data.field['ops'] = 'create';
		restApiRequest({
			silent: true,
			path: 'user',
			data: data.field
		}).then(function(result){
			if(result.rc == 0){
                processUserAddOrUpdateResult(result.data, function () {
                    // close win
                    // 关闭form
                    $("span.layui-layer-setwin > a.layui-layer-close1").click();
                    // 刷新页面
                    document.getElementById("admin").contentWindow.location = '/admin/user/index.html';
                });
			}
		}, function(err){
            handleRestApiFail(err);
		});
		return false;
	});

	// 保存成功后，继续留在当前页面，重制并创建下一个
	form.on('submit(sys-user-create-follow)', function (data) {
        data.field['ops'] = 'create';
        restApiRequest({
            silent: true,
            path: 'user',
            data: data.field
        }).then(function(result){
            if(result.rc == 0){
                processUserAddOrUpdateResult(result.data, function () {
                    // 清空部分参数
                    $('input[name="username"]').val("");
                    $('input[name="uname"]').val("");
                    $('input[name="mobile"]').val("");
                    $('input[name="email"]').val("");
					$('input[name="callcenter"]').attr('checked',false);
					$('#bindext_tip').hide();
					$("#callcenterExtid").html('<option value="">请选择分机</option>');
					form.render('checkbox')
                });
            }
        }, function(err){
            handleRestApiFail(err);
        });
		return false;
	})
});

</script>

<SCRIPT type="text/javascript">
	var setting = {
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onClick: onClick,
			beforeClick: beforeClick
		}
	};

	function beforeClick(treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("organTree")
		nodes = zTree.getSelectedNodes();
		var allow = true , lastnode ;
		for (var i=0, l=nodes.length; i<l; i++) {
			lastnode = nodes[i].type ;
			if(nodes[i].organ && (nodes.length >= 1 && (event.ctrlKey || event.shiftKey))){
				allow = false ; break ;
			}
		}
		if(lastnode != treeNode.type && (event.ctrlKey || event.shiftKey)){
			allow = false ;
		}

		if (allow == false) {
			top.layer.alert("组织机构不能点选多个上级机构，也不能同时选择地区和机构", {icon: 3});
			return false;
		} else {
			return true;

		}
	}

	function onClick(e, treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("organTree"),
				nodes = zTree.getSelectedNodes(),
				v = "" , value = "";
		nodes.sort(function compare(a,b){return a.id-b.id;});
		for (var i=0, l=nodes.length; i<l; i++) {
			v += nodes[i].name + ",";
			if(value != ""){
				value = value + "," ;
			}
			value = nodes[i].id ;
		}
		if (v.length > 0 ) v = v.substring(0, v.length-1);
		if(treeNode.type == "area"){
			$("#parentname").attr("value", v);
			$("#parent").attr("value", "0");
			$("#area").attr("value", value);
		}else{
			$("#parentname").attr("value", v);
			$("#parent").attr("value", value);
			$("#area").attr("value", "");
		}
		if (!event.ctrlKey && !event.shiftKey) {
			hideMenu() ;
		}
	}


	var zNodes =[
			// { id:'0', pId:'00', name:"组织机构", open:true , organ : true, type : "organ"}
			<#if organList??>
	<#list organList as organ>
	{ id:'${organ.id!''}', pId:'${organ.parent!'0'}', name:"${organ.name!''}", open:true , organ : true , type : "organ",  icon:"/images/dept.png" },
	</#list>
	</#if>
	];
	$(document).ready(function(){
		var ztree = $.fn.zTree.init($("#organTree"), setting, zNodes);
	<#if organData??>
		var node = ztree.getNodeByParam('id', '${organData.parent!''}');//获取id为1的点
		ztree.selectNode(node);//选择点
		if(node){
			$("#parentname").attr("value", node.name);
		}
	<#if organData.area??>
		<#list organData.area?split(",") as area>
		var areanode_${area_index} = ztree.getNodeByParam('id', '${area}');//获取id为1的点
		ztree.selectNode(areanode_${area_index} , true );//选择点
	</#list>
		</#if>

		</#if>
	});
	function showMenu() {
		$("#menuContent").css({left:"0px", top:"38px"}).show();

		$("body").bind("mousedown", onBodyDown);
	}
	function hideMenu() {
		$("#menuContent").hide();
		$("body").unbind("mousedown", onBodyDown);
	}
	function onBodyDown(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
			hideMenu();
		}
	}

</SCRIPT>
