<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/view/include/tags.jspf"%>

<section class="content-header">
	<tg:menuInfoTag />
</section>

<section class="content">
	<div class="row">
		<div class="col-xs-12">
			<div class="box box-success">
				<div class="box-header">
					<h3 class="box-title"><i class='material-icons' style='font-size:16px;'>play_arrow</i>&nbsp;검색조건</h3>
				</div>
				<div class="box-body">
					<form name="searchForm">
						<div class="row">
							<div class="col-md-3 col-xs-12" style="margin-bottom: 10px;">
								<div class="input-group">
									<span class="input-group-addon">사용자구분</span>
									<select id="userTyCdLike" name="userTyCdLike" class="form-control selectpicker">
										<option value="">전체</option>
										<option value="U">일반회원</option>
										<option value="J">기업회원</option>
										<option value="M">관리자</option>
									</select>
								</div>
							</div>
							<div class="col-md-3 col-xs-12" style="margin-bottom: 10px;">
	                            <div class="input-group">
	                               	<span class="input-group-addon">사용자 ID</span>
	                               	<input type="text" id="userLoginIdLike" class="form-control" placeholder="사용자ID 입력" maxlength="30">
	                            </div>
							</div>
							<div class="col-md-3 col-xs-12" style="margin-bottom: 10px;">
                             	<div class="input-group">
                                	<span class="input-group-addon">사용자명</span>
                                	<input type="text" id="userNmLike" class="form-control" placeholder="사용자명 입력" maxlength="30">
                             	</div>
                            </div>
							<div class="col-md-3 col-xs-12" style="margin-bottom: 10px;">
								<div class="input-group">
									<span class="input-group-addon">사용상태</span>
									<tg:cdDtl type="select" cd="userStCd" name="userStCd" styleClass="form-control selectpicker" headerText="전체" id="userStCd" labelYn="N"/>
								</div>
							</div>
						</div>
					</form>
				</div>  
				<div class="box-footer">
					<div class="btn-group pull-right">
						<button type="button" class="btn btn-outline-primary" id="searchBtn">검색</button>
						<button type="button" class="btn btn-outline-primary" id="resetBtn">리셋</button>
					</div>
				</div>
			</div>
		</div>
		<div class="col-xs-12">
			<div class="box box-primary">
				<div class="box-body">
					<table id="datatable" class="table table-bordered table-striped" style="width:100%; table-layout:fixed;"></table>
				</div>
			</div>
		</div>
	</div>

	<div class="modal fade userRole-modal" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<h2>권한변경</h2>
				</div>
				<div class="modal-body">
					<form id="userRoleForm" name="userRoleForm" class="form-horizontal form-label-left">
						<input type="hidden" id="userId" name="userId" />
						<div class="form-group">
							<label class="control-label col-md-3 col-sm-3 col-xs-12">사용자ID *</label>
							<div class="col-md-8 col-sm-8 col-xs-12">
								<input type="text" id="userLoginId" name="userLoginId" class="form-control col-md-7 col-xs-12" readonly>
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-md-3 col-sm-3 col-xs-12">사용자명 *</label>
							<div class="col-md-8 col-sm-8 col-xs-12">
								<input type="text" id="userNm" name="userNm" class="form-control col-md-7 col-xs-12" readonly>
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-md-3 col-sm-3 col-xs-12">사용자권한 *</label>
							<div class="col-md-8 col-sm-8 col-xs-12">
								<select id="roleAuth" name="roleAuth" class="form-control selectpicker">
									<option value="ROLE_MANAGER">최고 관리자</option>
									<option value="ROLE_COMPANY">기업 사용자</option>
									<option value="ROLE_USER">일반 사용자</option>
								</select>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-outline-primary" onclick="saveBtn()">변경</button>
					<button type="button" class="btn btn-outline-primary" data-dismiss="modal">닫기</button>
				</div>
			</div>
		</div>
	</div>

	<div class="modal fade userDetail-modal" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<div class="modal-header">
					<h2>사용자 상세보기</h2>
				</div>
				<div class="modal-body">
					<form id="userDetailForm" name="userDetailForm" class="form-horizontal form-label-left">
						<table class="board_write">
							<tbody>
							<tr>
								<th>사용자 ID</th>
								<td><div id="userLoginIdDetail"></div></td>
								<th>사용자명</th>
								<td><div id="userNmDetail"></div></td>
							</tr>
							<tr>
								<th>성별</th>
								<td><div id="gender"></div></td>
								<th>생년월일</th>
								<td><div id="birth"></div></td>
							</tr>
							<tr>
								<th>연락처</th>
								<td><div id="phone"></div></td>
								<th>이메일</th>
								<td><div id="email"></div></td>
							</tr>
							<tr>
								<th>등록일</th>
								<td><div id="regDt"></div></td>
								<th>사용상태</th>
								<td><div id="userStCdNm"></div></td>
							</tr>
							<tr class="userOutRsn">
								<th>탈퇴사유</th>
								<td colspan="3"><div id="userOutRsn"></div></td>
							</tr>
							</tbody>
						</table>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-outline-primary" data-dismiss="modal">닫기</button>
				</div>
			</div>
		</div>
	</div>

</section>

<script>
	var datatable;
	var userRoleDatatable;
	$(document).ready(function() {
		
		//모달창이동
		$('.modal-content').draggable({
			handle: ".modal-header"
		});
		
		//placeholder 브라우저호환
		$('input').placeholder();

		datatable = $("#datatable").DataTable({
			"searching" : false
			,"paging": true
			,"bPaginate": true
			,"responsive": true
			,"language": lang_kor
			,"ajax" : {
				"url" : "<c:url value='/system/user/list.json' />"
				,"method" : "post"
				,"data" : function(d) {
					if ($('#userTyCdLike').val() != "") {d.userTyCd = $('#userTyCdLike').val();}
					if ($('#userLoginIdLike').val() != "") {d.userLoginIdLike = $('#userLoginIdLike').val();}
					if ($('#userNmLike').val() != "") {d.userNmLike = $('#userNmLike').val();	}
					if ($('#userStCd').val() != "") {d.userStCd = $('#userStCd').val();	}
				}
			},"processing": true
			,"serverSide": true 
			,"order" : [[5, 'desc']]
			,"columns": [
				{ "name" : "USER_TY_CD", "title" : "사용자 구분", "render" : function(data, type, row) {
					var html = "";
					if(row["userTyCd"] == "U") { html += "일반회원"; } else if(row["userTyCd"] == "J") { html += "기업회원"; } else if(row["userTyCd"] == "M") { html += "관리자"; }
					return html;
				}, "className" : "dt-head-center"} ,
				{ "name" : "USER_LOGIN_ID", "title" : "사용자 ID", "data" : "userLoginId", "className" : "dt-head-center dt-body-left"} ,
				{ "name" : "USER_NM", "title" : "사용자명", "data" : "userNm", "className" : "dt-head-center dt-body-left"} ,
				{ "name" : "BIRTH", "title" : "생년월일", "render" :
					function(data, type, row) {
						return str_to_date(row["birth"], '-');
					}, "className" : "dt-head-center dt-body-left"} ,
				{ "name" : "USER_ST_CD_NM", "title" : "사용상태", "data" : "userStCdNm", "className" : "dt-head-center dt-body-left"},
				{ "name" : "REG_DT", "title" : "등록일", "render" : 
					function (data, type, row) {
					return new Date(row["regDt"]).format("yyyy-MM-dd HH:mm:ss");  
				}, "className" : "dt-head-center dt-body-center"},
				{ "render" : 
					function (data, type, row) {
						var html = "";
						html += "<button type='button' class='btn btn-sm btn-outline-primary' onclick='goDetailUser(\""+row["userId"]+"\")'>상세</button>&nbsp;";
						if(row["userSt"] != 9) {
							html += "<button type='button' class='btn btn-sm btn-outline-primary' onclick='autUser(\"" + row["userId"] + "\")'>권한변경</button>&nbsp;";
						}
						html += "<button type='button' class='btn btn-sm btn-outline-primary";
						if(row["failCnt"] < 5) {
							html += "disabled' data-toggle='tooltip' title='로그인 실패카운터 5 미만 입니다.' '><i class='material-icons'>lock_open</i>&nbsp;"+row["failCnt"]+"</button>";
						}else {
							html += "' data-toggle='tooltip' title='로그인 제한 풀기' onclick='initFailCntUpdate(\""+row["userId"]+"\")'><i class='material-icons'>lock</i>&nbsp;"+row["failCnt"]+"</button>";
						}
						return html;  
					},
				    "title":"기능", "className": "dt-head-center dt-body-center", "orderable" : false,
				}	
			]
			,"scrollX": "100%"
			,"scrollXInner": "850px"
			,"columnDefs": [
				{"targets": [0], width: "100px"}
				,{"targets": [1], width: "100px"}
				,{"targets": [2], width: "100px"}
				,{"targets": [3], width: "100px"}
				,{"targets": [4], width: "100px"}
				,{"targets": [5], width: "150px"}
				,{"targets": [6], width: "150px"}
			]
			,"fnRowCallback": function(nRow, aData, iDisplayIndex) {
				$(nRow).on('click', function() {
					getSearchCondition(document.searchForm);
				});
			}	
		});
		setSearchCondition(document.searchForm);
	});
	
	$("#searchBtn").click(function() {
		datatable.ajax.reload();
	});
	
	$("#userStCd").change(function() {
		datatable.ajax.reload();
	});
	
	$("#resetBtn").click(function() {
		$('#userTyCdLike').val("");
		$('#userTyCdLike').selectpicker("refresh");
		$('#userLoginIdLike').val("");
		$('#userNmLike').val("");
		$('#userStCd').val("");
		$('#userStCd').selectpicker("refresh");
		datatable.ajax.reload();
	});
	
	function goDetailUser(id){
		$.ajax({
			url : "<c:url value='/system/user/detailUser.json' />" ,
			type : "POST" ,
			data : {"userId": id} ,
			dataType : "json" , 
			success : function(res) {
				var data = res.data;
				if(res.result == "success"){
					$("#userLoginIdDetail").html(data.userLoginId);
					$("#userNmDetail").html(data.userNm);
					$("#birth").html(str_to_date(data.birth, '-'));
					switch(data.gender){
						case "f":
							$("#gender").html("여자");
							break;
						case "m":
							$("#gender").html("남자");
							break;
						default:
							break;
					}
					$("#email").html(data.email);
					$("#phone").html(checkTelNum(data.phone));
					$("#regDt").html(new Date(data.regDt).format("yyyy-MM-dd"));

					switch(data.userStCd){
						case "1":
							$("#userStCdNm").html("사용중");
							$(".userOutRsn").hide();
							break;
						case "8":
							$("#userStCdNm").html("사용정지");
							$(".userOutRsn").hide();
							break;
						case "9":
							$("#userStCdNm").html("탈퇴");
							$(".userOutRsn").html(data.userOutRsn);
							$(".userOutRsn").show();
							break;
						default:
							break;
					}
					$('div.userDetail-modal').modal("show");
				} else {
					alert(res.message);
				}
			}
		})

	}
	
	function delUser(id){
		getSearchCondition(document.searchForm);
		if(confirm("해당 사용자를 삭제하시겠습니까?")){
			$.ajax({
				url : "<c:url value='/system/user/delete.json' />" ,
				type : "POST" ,
				data : {"userId": id} ,
				dataType : "json" , 
				success : function(res) {
					if(res.result == "success"){
						alert("삭제되었습니다");
						datatable.ajax.reload();
					}else {
						alert(res.message);
					}
				}
			})
		}
	}

	function autUser(userId) {
		$.ajax({
			url: "<c:url value='/system/user/detailUser.json' />",
			type: "POST",
			data: { userId : userId },
			dataType: "json",
			success: function (res) {
				if (res.result == "success") {
					var data = res.data;
					$("#userId").val(data.userId);
					$("#userSt").val(data.userSt);
					$("#userLoginId").val(data.userLoginId);
					$("#userNm").val(data.userNm);
					$("#roleAuth").val(data.roleAuth);
					$("#roleAuth").selectpicker("refresh");

					$('div.userRole-modal').modal("show");
				} else {
					alert(res.message);
				}
			}
		})
	}

	function saveBtn(){
		if(confirm("권한을 변경하시겠습니까?")) {
			$.ajax({
				url: "<c:url value='/system/userRole/update.json' />",
				type: "POST",
				data: {
					"userId" : $("#userId").val(),
					"roleAuth" : $("#roleAuth").val()
				},
				dataType: "json",
				success: function (res) {
					if (res.result == "success") {
						alert("권한이 변경되었습니다.");
						$('.userRole-modal').modal("hide");
						datatable.ajax.reload();
					} else {
						alert(res.message);
					}
				}
			})
		}
	}

	function initFailCntUpdate(id){
		getSearchCondition(document.searchForm);
		if(confirm("해당 사용자 로그인 실패 카운터를 초기화 하시겠습니까?")){
			$.ajax({
				url : "<c:url value='/system/user/initFailCnt.json' />" ,
				type : "POST" ,
				data : {"userId": id} ,
				dataType : "json" , 
				success : function(res) {
					if(res.result == "success"){
						alert("로그인 실패 카운터가 초기화 되었습니다");
						datatable.ajax.reload();
					}else {
						alert(res.message);
					}
				}
			})
		}
	}
	
</script>