<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/WEB-INF/jsp/common/taglibs.jspf"%>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<hejin:header title="用户管理"></hejin:header>
		<link rel="stylesheet" href="static/js/select2/select2.css">
		<link rel="stylesheet" href="static/js/select2/select2-bootstrap.css">
		<link rel="stylesheet" type="text/css" href="static/css/font/font-awesome.min.css">
		<!-- datetimepicker css -->
		<link rel="stylesheet" type="text/css" href="static/css/bootstrap/bootstrap-datetimepicker.min.css">
		<!-- fileupload ui css -->
		<link rel="stylesheet" type="text/css" href="static/css/bootstrap/jquery.fileupload-ui.css">
		<style type="text/css">
		.span {
			position: absolute;
			left: 50%;
			top: 50%;
			margin-top: 5px;
		}
		.help-inline{
		  color: #FF5151;
  		  border-color: #FF5151;
		}
		.success .validate-inline.ok:before,.success .help-inline.ok:before {
		  content: "\f00c";
		  font-size: 16px;
		  font-family: FontAwesome;
		  font-weight: normal;
		  font-style: normal;
		  display: inline-block;
		}
		</style>
	</head>
	<body>
		<!-- 菜单 -->
		<jsp:include page="../../menu.jsp"/>
		<!-- 当前用户选中的菜单 -->
		<input type="hidden" id="userSelectMenuId" value="${_current_menu}"/>
		<input type="hidden" id="currentUserPermissionDataId" value="${_current_menu_perms }"/>
		<!-- BEGIN 面包屑 -->
		<div class="container-fluid">
			<ol class="breadcrumb"><!-- BEGIN 面包屑 -->
				<li><a href="javascript:void(0);">系统管理</a></li>
				<li><a href="<%=path %>/system/user/userIndex.do">用户管理</a></li>
			</ol>
		</div>
		<!-- END 面包屑 -->
		<!-- BEGIN 条件 -->
		<form id="exportUserListId" method="post" name="exportUserDataList" action="<%=path%>/export/userDataList.do">
			<div class="container-fluid">
				<div class="row">
					<div class="col-sm-1">
	  					<span class="span">登录名称</span>
					</div>
					<div class="col-sm-2">
						<div class="form-group">
	 						<input type="text" class="form-control" id="loginName" name="loginName" placeholder="请输入登录名称">
	 					</div>
					</div>
					
					<div class="col-sm-1">
	  					<span class="span">用户名称</span>
					</div>
					<div class="col-sm-2">
						<div class="form-group">
	 						<input type="text" class="form-control" name="userName" id="userName" placeholder="请输入用户名称">
	 					</div>
					</div>
					<div class="col-sm-1">
						<span class="span">用户状态</span>
					</div>
					<div class="col-sm-2">
						<div class="form-group">
							<select id="status" name="status" class="form-control">
								<option value="" selected>--请选择--</option>
								<c:forEach items="${userStatusMap}" var="map">
									<c:if test="${map.key != 10}">
										<option value="${map.key}">
												${map.value}
										</option>
									</c:if>
								</c:forEach>
							</select>
						</div>
					</div>
					<div class="col-sm-1">
						<div class="form-group">
							<a class="btn btn-block btn-primary btn-query" id="queryUserInfo" data-target="#compose-modal"><i class="fa fa-pencil"></i>查询</a>
						</div>
					</div>
					<div class="col-sm-1">
						<div class="form-group">
							<a class="btn btn-block btn-primary btn-cancel" id="resetOnClick" data-target="#compose-modal"><i class="fa fa-pencil"></i>重置</a>
						</div>
					</div>
					<div class="col-sm-3"></div>
				</div>
			</div>
		</form>
		
		<!-- END 条件 -->
		<!-- BEGIN Tables -->
		<div class="container-fluid">
			<div class="row"><!-- BEGIN row-fluid -->
				<div class="col-sm-12"><!-- BEGIN col-sm-12 -->
					<div class="box">
                        <div class="box-header">
                        	<h3 class="box-title">用户列表</h3>
                            <div class="col-sm-9" style="float: right;margin-top: 10px;margin-right: 10px;margin-bottom: 5px;">
								<div class="btn-toolbar" style="float: right;">
									<shiro:hasPermission name="${_current_menu }:create">
										<div class="btn-group">
											<a class="btn btn-block btn-primary" id="addUserBtn" data-target="#compose-modal"><i class="fa fa-pencil"></i>新增</a>
										</div>
									</shiro:hasPermission>
									<shiro:hasPermission name="${_current_menu }:delete">
										<div class="btn-group">
											<a class="btn btn-block btn-primary" id="delUserBtn" data-target="#compose-modal"><i class="fa fa-pencil"></i>删除</a>
										</div>
									</shiro:hasPermission>
									<shiro:hasPermission name="${_current_menu }:update">
										<div class="btn-group">
											<a class="btn btn-block btn-primary" id="toEnableBtn" data-target="#compose-modal"><i class="fa fa-pencil"></i>启用</a>
										</div>
									</shiro:hasPermission>
									<shiro:hasPermission name="${_current_menu}:update">
										<div class="btn-group">
											<a class="btn btn-block btn-primary" id="onDisableBtn" data-target="#compose-modal"><i class="fa fa-pencil"></i>禁用</a>
										</div>
									</shiro:hasPermission>
								</div>
                        </div>
                    </div><!-- /.box-header -->
					<div class="box-body table-responsive">
                             <table class="table table-bordered table-striped" id="sample_editable_1">
				            	<thead>
				                	<tr>
				                		<th class="col-sm-1" style="width:55px;"><input id="allUserIds" name="allUserIds" type="checkbox">全选</th>
				                    	<th>用户名称</th>
				                        <th>登录名称</th>
				                        <th>用户状态</th>
				                        <th>注册时间</th>
				                      <%--  <th>操作</th>--%>
				                    </tr>
				                </thead>
				                <tbody>
				                </tbody>
				             </table>
			             </div>
		             </div>
             	</div><!-- END col-sm-12 -->
            </div><!-- END row-fluid -->
		</div>
		<!-- END Tables -->
		<!-- BEGIN MODAL -->
        <div class="modal fade" id="user-add-modal"></div>
        <!-- END Modal -->
        <!-- Reset Password -->
        <!-- COMPOSE MESSAGE MODAL -->
        <div class="modal fade" id="reset_compose-modal" tabindex="-1">
            <div class="modal-dialog" style="width: 500px;">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title"><i class="fa fa-envelope-o"></i>重置密码</h4>
                    </div>
                    <input name="reset_userId" id="reset_userId" type="hidden" class="form-control">
                    <div class="modal-body">
                        <div class="row form-group">
                        	<div class="col-sm-4">
                        		<label class="span">新密码</label>
                        	</div>
                            <div class="col-sm-7"> 
                                <input name="reset_password_one" id="reset_password_one" type="password" class="form-control" placeholder="请输入密码">
                            </div>
                        </div>
                        <div class="row form-group">
                            <div class="col-sm-4">
                        		<label class="span">确认新密码</label>
                        	</div>
                            <div class="col-sm-7"> 
                                <input name="reset_password_two" id="reset_password_two" type="password" class="form-control" placeholder="请输入确认密码">
                            	<span class="help-inline" id="reset_error"></span>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
					    <button type="button" class="btn btn-danger" id="reset_cancel"><i class="fa fa-times"></i>取消</button>
					    <button type="button" class="btn btn-primary pull-left" id="submitResetPassword"><i class="fa fa-envelope"></i>确定</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>
        <!-- 修改密码结束 -->
        
		<hejin:commonScript></hejin:commonScript>
		<script type="text/javascript" src="static/js/select2/select2.min.js"></script>
		<script type="text/javascript" src="static/js/select2/select2_locale_zh-CN.js"></script>
	    <!-- datetimepicker -->
	    <script type="text/javascript" src="static/js/bootstrap/bootstrap-datetimepicker.min.js"></script>
	    <script type="text/javascript" src="static/js/bootstrap/bootstrap-datetimepicker.zh-CN.js"></script>

	    <script type="text/javascript">
	    var tables;
	    var path = '<%= path%>';
		Date.prototype.format = function(format){
		     var o = {
		     "M+" : this.getMonth()+1, //month
		     "d+" : this.getDate(),    //day
		     "h+" : this.getHours(),   //hour
		     "m+" : this.getMinutes(), //minute
		     "s+" : this.getSeconds(), //second
		     "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
		     "S" : this.getMilliseconds() //millisecond
		     }
		     if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
		     (this.getFullYear()+"").substr(4 - RegExp.$1.length));
		     for(var k in o)if(new RegExp("("+ k +")").test(format))
		     format = format.replace(RegExp.$1,
		     RegExp.$1.length==1 ? o[k] :
		     ("00"+ o[k]).substr((""+ o[k]).length));
		     return format;
		};
    	// datatable js
       	$(function() {
        	/**
        	 *通过登录用户所选中的菜单获取对应菜单的所有操作权限
        	 */
     	   // datatable load data
     	   tables = $('#sample_editable_1').platformDataTable({
				"sAjaxSource" : 'system/user/loadUserList.do?'+ new Date().getTime(),
				"iDisplayStart" : 0,
				"iDisplayLength" : 10,//每页显示6条记录
				"bSort":false,//关闭排序
				"bAutoWidth":true, //列的宽度会根据table的宽度自适应 
				"aoColumns" : [ //列
				     {"sClass" : "center","mDataProp" : "","bSearchable" : false,
					"fnRender" : function(obj) {
						return '<input name="userIds" value="' + obj.aData.userId + '" type="checkbox" >';
						}
					},
					{"sClass" : "center", "mDataProp" : "userName"},
					{"sClass" : "center", "mDataProp" : "loginName"},
					{"sClass" : "center", "mDataProp" : "status","fnRender" : function (data) {
						if (data.aData.status == '10') {
							return  '正常';
						} else if (data.aData.status == '20') {
							return '未激活';
						} else if (data.aData.status == '50') {
							return '禁用';
						} else if (data.aData.status == '90') {
							return '删除';
						}
					}},
					{"sClass" : "center", "mDataProp" : "createDate", "fnRender" : function(obj) {
					 	var curTime = new Date(obj.aData.createDate);
						return curTime.format("yyyy-MM-dd hh:mm:ss");
					}}/*,
					{"sClass" : "center", "mDataProp" : "userId", "bSearchable" : false,
					 "fnRender" : function(obj) {
						var butt = '<a class="icon-key" style="margin-left: 30px;text-decoration:none;" href="#reset_compose-modal" data-toggle="modal" onclick=\"javascript:resetPassword(\''+obj.aData.userId+'\');\"></a>';
							butt += ' <a class="icon-pencil" style="margin-left: 20px;text-decoration:none;" href="<%=request.getContextPath()%>/system/user/loadEditUserData.do?userId='+obj.aData.userId+'"></a>';
						//将页面上所有的操作权限都放到该对象里面如果例如:{"add" : "操作链接", "view" : "操作链接", "update" : "操作链接"}
						//公共的js方法会通过用户对应的权限去里面取对应的值
						var userPerOpt = {
								//"update" : butt
						};
						return formatCurrentUserPermissionOption(userPerOpt);
				    }}*/
				]
			});
     	// 全选
           $("#allUserIds").click(function() {
               $("input[name='userIds']").prop("checked",$(this).is(":checked"));
           });
          // 新增
          $('#addUserBtn').click(function(){
               $("#user-add-modal").load("system/user/forwardAddUser.do");
               $("#user-add-modal").modal("show");
          });
          // 删除
          $("#delUserBtn").click(function(){
               if(!$("input[name='userIds']").is(":checked")){
                   platformAlert("alert-warning","请选择用户！",4000);
                   return false;
               }
               if(confirm("确定要删除用户吗？")){
                   var userIds = "";
                   $(":checkbox[name='userIds']:checked").each(function(i){
                       if(i != 0){
                           userIds += "&";
                       }
                       userIds += "userIds="+$(this).val();
                   });
                   $.ajax({
                       url : 'system/user/deleteUser.do',
                       type : 'post',
                       data: userIds,
                       dataType : 'json',
                       success : function(data) {
                           if(data == "0"){
                               platformAlert("alert-danger","删除用户失败!",4000);
                           }else{
                               drawTable(tables,[]);
                               $("#allUserIds").attr("checked",false);
                           }
                       },
                      error: function(){
                          platformAlert("alert-danger","删除用户失败!",4000);
                      }
                   });
                }else{
                    return false;
                }
          });
          // 启用
          $('#toEnableBtn').click(function(){
               if(!$("input[name='userIds']").is(":checked")){
                   platformAlert("alert-warning","请选择用户！",4000);
                   return false;
               }
            if(confirm("确定要启用用户吗？")){
               var userIds = "";
               $(":checkbox[name='userIds']:checked").each(function(i){
                   if(i != 0){
                       userIds += "&";
                   }
                   userIds += "userIds="+$(this).val();
               });
               $.ajax({
                      type: 'post',
                      url: "system/user/unlockUser.do",
                      data: userIds,
                      dataType: 'json',
                      success: function(data){
                           if(data == "0"){
                               platformAlert("alert-danger","启用用户失败!",4000);
                           }else{
                               drawTable(tables,[]);
                               $("#allUserIds").attr("checked",false);
                           }
                      },
                      error: function(){
                          platformAlert("alert-danger","启用用户失败!",4000);
                      }
                   });
            }else{
                return false;
            }
          });
          // 禁用
          $('#onDisableBtn').click(function(){
               if(!$("input[name='userIds']").is(":checked")){
                   platformAlert("alert-warning","请选择用户！",4000);
                   return false;
               }
               if(confirm("确定要禁用用户吗？")){
                   var userIds = "";
                   $(":checkbox[name='userIds']:checked").each(function(i){
                       if(i != 0){
                           userIds += "&";
                       }
                       userIds += "userIds="+$(this).val();
                   });
                   $.ajax({
                          type: 'post',
                          url: "system/user/lockUser.do",
                          data: userIds,
                          dataType: 'json',
                          success: function(data){
                               if(data == "0"){
                                   platformAlert("alert-danger","禁用用户失败!",4000);
                               }else{
                                   drawTable(tables,[]);
                                   $("#allUserIds").attr("checked",false);
                               }
                          },
                          error: function(){
                              platformAlert("alert-danger","禁用用户失败!",4000);
                          }
                       });
               }else{
                   return false;
               }
          });
           // 查询事件
           $('#queryUserInfo').click(function(){
               var data=[];//存放json类型的查询条件，可以放多个
               data.push({ "name": "loginName", "value": $('#loginName').val()},
                         { "name": "userName", "value": $('#userName').val()},
                         { "name": "status", "value": $('#status').val()}
                         );
               //Ajax重新load控件数据
               drawTable(tables,data);
			   tables.fnPageChange(0);
           });
           // 重置密码取消
           $('#reset_cancel').click(function(){
               $('#reset_userId').val("");
               $('#reset_password_one').val(""); 
               $('#reset_password_two').val("");
               $('#reset_error').text("");
               $("#reset_compose-modal").modal("hide");
           });
     	   // 重置事件
           $('#resetOnClick').click(function(){
        		$('#loginName').val('');
   				$('#userName').val('');
   				$('#userStatus').val('');
   				$('#companyName').val('');
   				$('#userType').val('');
   				$('#status').val('');
			});
     	   
           $('#submitResetPassword').click(function(){
        	   var userId = $('#reset_userId').val();
       		var password = $('#reset_password_one').val(); 
       		var passwordTwo = $('#reset_password_two').val();
       		if(password==''){
       			$('#reset_error').text("");
       			$('#reset_error').text("请输入新密码！");
       			return false;
       		}
       		if(passwordTwo==''){
       			$('#reset_error').text("");
       			$('#reset_error').text("请输入确认新密码！");
       			return false;
       		}
       		if(password!=passwordTwo){
       			$('#reset_error').text("");
       			$('#reset_error').text("两次密码输入不一致,请重新输入！");
       			return false;
       		}
       		//var aa=new RegExp("(?![a-z]+$|[0-9]+$)^[a-zA-Z0-9]{7,16}$");
       		if (password.length < 6 || password.length > 16){
       			$('#reset_error').text("");
       			$('#reset_error').text("密码长度为6-16个字符，且区分大小写");
       			return false;
       		}else{
       			$.ajax({
           			type : 'post',
       				url : 'system/user/adminResetUserPassword.do',
       				data: {userId:userId,password:password,passwordTwo:passwordTwo},
       				dataType : 'json',
       				success : function(data) {
       					if(data!=''){
       						if(data!='1'){
       							$('#reset_error').text("保存数据失败,请联系管理员！");
       						}else{
       							$('#reset_error').text("");
       							$("#reset_compose-modal").modal("hide");
       						}
       					}
       				}
       			});
       		}
           });
       	});
    	// 重置密码
    	function resetPassword(userId){
    		$('#reset_userId').val(userId);
    	}
	    // 查看事件
	    function onShowViewUserInfo(value) {
			$("#user-add-modal").load("system/user/loadShowViewUserData.do",{userId:value},function(mes){
				$("#user-add-modal").modal("show");
			});
	    }

		function redirect(){
			if($('#page').val() && $('#page').val()>=0){
				var tables = $('#sample_editable_1').dataTable();
				var oSettings = tables.fnSettings();
				var maxPage = oSettings.fnRecordsTotal() % oSettings._iDisplayLength == 0?
				oSettings.fnRecordsTotal() / oSettings._iDisplayLength :
				Math.floor(oSettings.fnRecordsTotal() / oSettings._iDisplayLength)+ 1;
				if($('#page').val() == 0){
					$('#page').val(1);
				}
				if($('#page').val() > maxPage){
					$('#page').val(maxPage);
				}
				var redirectpage = $('#page').val() - 1;
				tables.fnPageChange(redirectpage);
			}else{
				return;
			}
		}

		function onlyNum(){
			$('#page').val($("#page").val().replace(/\D/g, ''));
		}
    </script>
	</body>
</html>