<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="ko">
<head>
	<title>사용자관리</title>
	<%@ include file="/WEB-INF/jsp/adm/include/topLinkTag.jsp" %>
</head>
<body>
<h1>ICOMSYS ADMIN</h1>

<div class="skip_navigation">
	<ul>
		<li>
			<a href="#Content" class="go_content">본문 바로가기</a>
		</li>
		<li>
			<a href="#Gnb">메뉴 바로가기</a>
		</li>
	</ul>
</div>

<header id="header">
	<%@ include file="/WEB-INF/jsp/adm/include/header.jsp" %>
</header>

<c:import url="/adm/menu/getLnbMenu.do" />

<script type="text/javascript">
$(document).ready(function() {
	$("#selectCustName").on('change', function() {
		$('#custName').val($("#selectCustName option:selected").val());
	});

	fncRetrieveUserList();
 	$("#testTb1").DataTable().on( 'select.dt', function ( e, dt, type, indexes ) {
		var rowData = $("#testTb1").DataTable().row( indexes ).data();
		$("#mdUserId").val(rowData.userId);
		$("#mdUserName").val(rowData.userName);
		$("#mdSelectCustName").val(rowData.custCode);
		$("#mdSelectAuthName").val(rowData.authCode);
		$("#mdUseFlag").val(rowData.useFlag);
		$("#mdEMail").val(rowData.eMail);
		$("#mdMobileNo").val(rowData.mobileNo);
		$("#mdSystemUserId").val(rowData.systemUserId);
		
		$('#mdSelectCustName').niceSelect('update');
		$('#mdSelectAuthName').niceSelect('update');
		$('#mdUseFlag').niceSelect('update');
	});
 	
 	$("a.close").on('click', function(){
		// 수정 Modal
 		$("#mdUserId").val('');
		$("#mdUserName").val('');
		$("#mdMobileNo").val('');
		$("#mdEMail").val('');
		$("#mdSelectCustName").val('');
		$("#mdSelectAuthName").val('');
		$("#mdUseFlag").val('N');
		$("#mdSystemUserId").val('');

		$('#mdSelectCustName').niceSelect('update');
		$('#mdSelectAuthName').niceSelect('update');
		$('#mdUseFlag').niceSelect('update');
		
		// 등록 Modal
		$("#mdNewUserId").val('');
		$("#mdNewUserName").val('');
		$("#mdNewMobileNo").val('');
		$("#mdNewEMail").val('');
		$("#mdNewSelectCustName").val('');
		$("#mdNewSelectAuthName").val('');
		$("#mdNewUseFlag").val('N');
		$("#password").val('');
		$("#password2").val('');

		$('#mdNewSelectCustName').niceSelect('update');
		$('#mdNewSelectAuthName').niceSelect('update');
		$('#mdNewUseFlag').niceSelect('update');
 	})
//  	$(".modal .list").attr("style")
});

function fncUserIdKeyPress(e){
	if (event.keyCode == 13) {
		checkAreadyId();
	} else {
		$("#checkedId").val('')
	}
}

function fncKeyPress(e){
	if (event.keyCode == 13) {
		fncRetrieveUserList();
	}
}

function fncRetrieveUserList(){
	if($('#custName').val()=='' || $('#custName').val() == 'undefined'){
		swalAlert("info", '고객사명은 필수 항목입니다.');
		return false;
	}
	
	var param = "siteCode="+$("#custName").val();
	param += "&searchCondition=" + $("#searchCondition option:selected").val();
	param += "&searchKeyword=" + $("#searchKeyword").val();

	$.ajax({
		type : "post",
		async : false,
		datatype : "text",
		url : "<c:url value='/adm/egov/user/retrieveUserList.do'/>",
		data : param,
		success : function(data) {
			fncDrawUserList(data.nMap);
		}
	});
}

function fncDrawUserList(data){
	var cnt = 0;
	 $("#testTb1").dataTable({
		"autoWidth": false,
		"paging": true,
		"pagingType" : "full_numbers",
		"ordering": true,
		"info": false,
		"filter": false,
		"lengthChange": true,
		"dom": 'rt<"bottom"fip><"clear">',
		"pageLength" : '10',
		"data": data,
		"destroy": true,
		"select": true,
		"columns" : [
			{data: "systemUserId"},
			{data: "rownum"},
			{data: "custName"},
			{data: "userId"},
			{data: "userName"},
			{data: "eMail"},
			{data: "mobileNo"},
			{data: "useFlag"},
			{data: "registDate"},
		],
		"columnDefs": [ {
				orderable: false,
				targets:   0,
				render: function ( data, type, row ) {
					cnt++;
				   	apdStr = '<div class="chk_box">';
					apdStr += '	<input type="checkbox" name="checkbox" value="'+data+'" >';
					apdStr += '	<label for="chk01"></label>';
					apdStr += '</div>';
					return apdStr;
				}
			},
			{
				orderable: false,
				targets: 6,
	        	render : function(data) {
	        		if(data=='' || data=='undefined'){
	        			data = '';
	        		}else if(data.length==11){
	        			data = data.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
	        		}else if(data.length==8){
	        			data = data.replace(/(\d{4})(\d{4})/, '$1-$2');
	        		}else{
	        			if(data.indexOf('02')==0){
	        				data = data.replace(/(\d{2})(\d{4})(\d{4})/, '$1-$2-$3');
	        			} else {
	        				data = data.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
	        			}
	        		}
					return data;
	        	}
			},
			{
				orderable: false,
				targets: 8,
	        	render : function(data) {
	        		return moment(data).format('YYYY-MM-DD HH:mm:ss');
	        	}
        	}
       	],
		createdRow: function (row, data, index) {
			$(row).addClass("modalLoad");
			$(row).attr("rel", "reg_edit_modal");
		},
		drawCallback: function( settings ) {
			// scripts.js : 조회list modal 연결
			modalUi();
		}
	});
	$('.sel_box select').niceSelect();
}

function checkAreadyId(){
	if($('#mdNewUserId').val() == '' || $('#mdNewUserId').val() == 'undefined'){
		swalAlert("info", '중복 조회 할 ID를 입력해 주세요.');
		return false;
	}
	if( fnCheckNotKorean($('#mdNewUserId').val()) ) {
		var param = "checkId=" + $('#mdNewUserId').val();
		
		$.ajax({
			type : "post",
			async : false,
			datatype : "text",
			url : "<c:url value='/adm/egov/user/EgovIdDplctCnfirm.do'/>",
			data : param,
			success : function(data) {
				if(data.usedCnt == "0"){
					swal('Success', data.checkId + '는 사용할 수 있는 ID 입니다.', {
						icon: "success",
						buttons:"확인"
					});
					$("#checkedId").val(data.usedCnt);
				} else {
					swalAlert("info", data.checkId + '는 사용할 수 없는 ID 입니다.');
					$("#checkedId").val(data.usedCnt);
				}
			},
			error : function(data) {
				swalAlert('error');
			}
		});
	} else {		
		swalAlert("info", '한글은 사용할 수 없습니다.');
		return false;	
	}
}

function fnCheckNotKorean(koreanStr){                  
    for(var i=0;i<koreanStr.length;i++){
        var koreanChar = koreanStr.charCodeAt(i);
        if( !( 0xAC00 <= koreanChar && koreanChar <= 0xD7A3 ) && !( 0x3131 <= koreanChar && koreanChar <= 0x318E ) ) { 
        }else{
            //hangul finding....
            return false;
        }
    }
    return true;
}

function cudUserInfo(jobCudType){
	var param = "&jobCudType="+jobCudType; 
	
	if( jobCudType == 'insert'){
		if($("#checkedId").val()=="0") {
			if($("#mdNewUserId").val()==""||$("#mdNewUserId").val()=="undefined"
				|| $("#mdNewUserName").val()==""||$("#mdNewUserName").val()=="undefined"
				|| $("#mdNewSelectCustName").val()==""||$("#mdNewSelectCustName").val()=="undefined"
				|| $("#mdNewSelectAuthName").val()==""||$("#mdNewSelectAuthName").val()=="undefined"
				|| $("#password").val()==""||$("#password").val()=="undefined"
				|| $("#password2").val()==""||$("#password2").val()=="undefined" ) {
				
				swalAlert('info', '필수 항목을 확인 후 진행해 주세요.');
				
				return false;
			}

			let check = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/;

			if(!check.test($("#password").val()) && $("#password").val().length < 10) {
				swalAlert('info', '비밀번호는 10자 이상 또는 영문,숫자,특수기호 포함 8자 이상이어야 합니다.');
				return false;
			} else if($("#password").val() != $("#password2").val() ){
				swalAlert('info', '비밀번호를 확인해 주세요.');
				return false;
			}
			
			param += "&userId="+$("#mdNewUserId").val();
			param += "&userName="+$("#mdNewUserName").val();
			param += "&mobileNo="+$("#mdNewMobileNo").val();
			param += "&eMail="+$("#mdNewEMail").val();
			param += "&useFlag="+$("#mdNewUseFlag").val();
			param += "&siteCode="+$("#mdNewSelectCustName").val();
			param += "&authCode="+$("#mdNewSelectAuthName").val();
			param += "&password="+$("#password").val();
			
		} else if ( $("#checkedId").val()==""||$("#checkedId").val()=="undefined" ){
			swalAlert('info', '먼저 ID 중복 확인을 실행하십시오');
			return false;
		} else {
			swalAlert('info', '사용할 수 없는 ID 입니다.');
			return false;
		}
	} else {
		if($("#mdUserName").val()==""||$("#mdUserName").val()=="undefined" ) {
			swalAlert('info', '필수 항목을 확인 후 진행해 주세요.');
			return false;
		}
		param += "&userId="+$("#mdUserId").val();
		param += "&userName="+$("#mdUserName").val();
		param += "&mobileNo="+$("#mdMobileNo").val();
		param += "&eMail="+$("#mdEMail").val();
		param += "&useFlag="+$("#mdUseFlag").val();
		param += "&siteCode="+$("#mdSelectCustName").val();
		param += "&authCode="+$("#mdSelectAuthName").val();
		param += "&systemUserId="+$("#mdSystemUserId").val();
	}
		
	$.ajax({
		type : "post",
		async : false,
		datatype : "text",
		url : "<c:url value='/adm/egov/user/EgovUserSelectUpdt.do'/>",
		data : param,
		success : function(data) {
			if(data.nMap.resultCode == "fail.common.login"){
				swalAlert("info", '로그인한 후에 진행해 주세요.');
			} else if(data.nMap.resultCode == "success.common.update" || data.nMap.resultCode == "success.common.insert") {
				swalAlert('success', '저장');
				$('a.close').trigger('click');
				fncRetrieveUserList(data.nMap);
			} else {
				swalAlert('error');
			}
		},
		error : function(data) {
			swalAlert('error');
		}
	});
}

function fncDeleteUser(){
	var table = $('#testTb1').DataTable();
	var param = table.$('input').serialize();
	
	$.ajax({
		type : "post",
		async : false,
		datatype : "text",
		url : "<c:url value='/adm/egov/user/EgovUserDelete.do'/>",
		data : param,
		success : function(data) {
			if(data.nMap.resultCode == "fail.common.login"){
				swalAlert("info", '로그인한 후에 진행해 주세요.');
			} else if(data.nMap.resultCode == "success.common.delete") {
				swalAlert('success', '삭제');
				$('a.close').trigger('click');
				fncRetrieveUserList(data.nMap);
			} else {
				swalAlert('error');
			}
		},
		error : function(data) {
			swalAlert('error');
		}
	});
}

</script>
<section id="Content" class="system_management">
	<div class="location">
		<ul>
			<li class="home"><a href="#">HOME</a></li>
			<li><a href="#">시스템관리</a></li>
			<li><a href="#">사용자관리</a></li>
		</ul>
	</div>
	<div class="sub_cont menu06_02">
		<div class="cont_box">
			<div class="box_title">
				<div class="fl">
					<h2 class="mt12">사용자 조회</h2>
				</div>
				<div class="fr">
				<c:choose>
					<c:when test="${'SYS_ADMIN'==LoginVO.authCode}">
							<dl class="customer fl">
								<dt class="fl">
									고객사 :
								</dt>
								<dd class="fl">
									<div class="sel_box">
										<input name="custName" id="custName"  type="hidden"/>
										<select class="top" id="selectCustName" name="selectCustName" title="검색조건-고객사" >
											<option value="">고객사 선택</option>
											<c:forEach var="siteInfo" items="${siteLists}" varStatus="status">
												<option value="<c:out value="${siteInfo.custCode}"/>"><c:out value="${siteInfo.custName}"/></option>
											</c:forEach>
										</select>
									</div>
								</dd>
							</dl>
					</c:when>
					<c:otherwise>
						<input name="custName" id="custName"  type="hidden" value="${LoginVO.siteCode}"/>
					</c:otherwise>
				</c:choose>
					<div class="btn_wrap fl">
						<a href="#" class="btn" id="btnSend" onclick="fncRetrieveUserList(); return false;">조회</a>
					</div>
				</div>
			</div>
			<div class="tbl">
				<table class="search">
					<colgroup>
						<col width="130px">
						<col width="42%">
						<col width="130px">
						<col width="42%">
					</colgroup>
					<tbody>
					<tr>
						<th>조회조건</th>
						<td>
							<div class="sel_box">
								<select id="searchCondition" class="wide">
<!--									 <option value="">조회조건 선택</option> -->
									<option value="0">ID</option>
									<option value="1">이름</option>
								</select>
							</div>
						</td>
						<th class="tl">조회 명</th>
						<td class="tl">
							<div class="ipt_box">
								<input type="text" placeholder="조회명을 입력해주세요." id="searchKeyword" name="code" class=""  onkeypress="return fncKeyPress();">
							</div>
						</td>
					</tr>
					</tbody>
				</table>
			</div>
		</div>
		<div class="cont_box">
			<div class="box_title">
				<div class="fl">
					<h2 class="mt12">사용자 리스트</h2>
				</div>
				<div class="btn_wrap fr">
					<a href="#" class="btn grey" onclick="fncDeleteUser(); return false;">삭제</a>
					<a href="#" rel="reg_modal" class="btn line modalLoad">신규등록</a>
				</div>
			</div>
			<div class="tbl">
				<table id="testTb1" class="click">
					<colgroup>
						<col width="60px">
						<col width="70px">
						<col width="300px">
						<col width="*">
						<col width="*">
						<col width="250px">
						<col width="250px">
						<col width="150px">
						<col width="250px">
					</colgroup>
					<thead>
					<tr>
						<th>
							<div class="chk_box">
								<input type="checkbox" name="all" id="chk00"  value="">
								<label for="chk00"></label>
							</div>
						</th>
						<th>NO</th>
						<th>고객사</th>
						<th>아이디</th>
						<th>사용자 이름</th>
						 <th>이메일</th>
						 <th>전화번호</th>
						<th>사용여부</th>
						<th>등록일시</th>
					</tr>
					</thead>
					<tbody>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</section>
<!--  modal :: 사용자 수정 팝업  -->
<div class="modal" id="reg_edit_modal">
	<div class="modal_header">
		<h3>사용자 관리 수정</h3>
		<input type="hidden" id="mdSystemUserId" id="mdSystemUserId">
	</div>
	<div class="modal_body">
		<div class="modal_cont">
			<dl>
				<dt><h4><em class="important">사용자 ID</em></h4></dt>
				<dd>
					<div class="ipt_box">
						<input type="text" name="required" id="mdUserId" disabled>
					</div>
					<div>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">이름</em></h4></dt>
				<dd>
					<div class="ipt_box">
						<input type="text" name="required" id="mdUserName">
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">고객사</em></h4></dt>
				<dd>
					<div class="sel_box">
						<select class="wide" id="mdSelectCustName" name="mdSelectCustName" title="검색조건-고객사" >
							<c:forEach var="siteInfo" items="${siteLists}" varStatus="status">
								<option value="<c:out value="${siteInfo.custCode}"/>"><c:out value="${siteInfo.custName}"/></option>
							</c:forEach>
						</select>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">권한</em></h4></dt>
				<dd>
					<div class="sel_box">
						<select class="wide" id="mdSelectAuthName" name="mdSelectAuthName" title="검색조건-권한" >
							<c:choose>
								<c:when test="${'VIDEO_SITE_ADMIN'==LoginVO.authCode}">
									<option value="VIDEO_SITE_USER" label="영상상담 Site 사용자"/>
								</c:when>
								<c:otherwise>
									<option value="SYS_ADMIN">시스템관리자</option>
									<c:forEach var="authInfo" items="${authLists}" varStatus="status">
										<option value="<c:out value="${authInfo.code}"/>"><c:out value="${authInfo.codeNm}"/></option>
									</c:forEach>
								</c:otherwise>
							</c:choose>
						</select>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">사용여부</em></h4></dt>
				<dd>
					<div class="sel_box">
						<select id="mdUseFlag" class="wide">
							<option value="N">미사용</option>
							<option value="Y">사용</option>
						</select>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="">이메일 주소</em></h4></dt>
				<dd>
					<div class="ipt_box">
						<input type="text" id="mdEMail">
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="">핸드폰 번호</em></h4></dt>
				<dd>
					<div class="ipt_box">
						<input type="text" id="mdMobileNo">
					</div>
				</dd>
			</dl>
		</div>
	</div>
	<div class="modal_footer">
		<div class="btn_wrap fr">
			<a href="#" class="btn" onclick="cudUserInfo('update'); return false;">저장</a>
		</div>
	</div>
	<div class="modal_controller">
		<a href="#" class="close">close</a>
	</div>
</div>
<!--  modal :: 사용자 서비스 수정 팝업 end -->
<!--  modal :: 사용자 등록 팝업  -->
<div class="modal" id="reg_modal">
	<div class="modal_header">
		<h3>사용자 관리 등록</h3>
	</div>
	<div class="modal_body">
		<div class="modal_cont">
			<dl>
				<dt><h4><em class="important">사용자 ID</em></h4></dt>
				<dd>
					<div class="ipt_box listen">
						<input type="text" name="required" id="mdNewUserId" onkeypress="return fncUserIdKeyPress(event);" style="width: 326px;">
						<input type="hidden" id="checkedId">
						<a href="#" class="btn" onclick="checkAreadyId(); return false;" style="height: 36px;">중복검색</a>
					</div>
					<div>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">비밀번호</em></h4></dt>
				<dd>
					<div class="ipt_box listen">
						<input type="password" name="required" id="password">
					</div>
					<div>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">비밀번호 확인</em></h4></dt>
				<dd>
					<div class="ipt_box listen">
						<input type="password" name="required" id="password2">
					</div>
					<div>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">이름</em></h4></dt>
				<dd>
					<div class="ipt_box">
						<input type="text" name="required" id="mdNewUserName">
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">고객사</em></h4></dt>
				<dd>
					<div class="sel_box">
						<select class="wide" id="mdNewSelectCustName" name="mdNewSelectCustName" title="검색조건-고객사" >
							<option value="">고객사 선택</option>
							<c:forEach var="siteInfo" items="${siteLists}" varStatus="status">
								<option value="<c:out value="${siteInfo.custCode}"/>"><c:out value="${siteInfo.custName}"/></option>
							</c:forEach>
						</select>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">권한</em></h4></dt>
				<dd>
					<div class="sel_box">
						<select class="wide" id="mdNewSelectAuthName" name="mdNewSelectAuthName" title="검색조건-권한" >
							<option value="">권한 선택</option>
							<c:choose>
								<c:when test="${'VIDEO_SITE_ADMIN'==LoginVO.authCode}">
									<option value="VIDEO_SITE_USER" label="영상상담 Site 사용자"/>
								</c:when>
								<c:otherwise>
									<option value="SYS_ADMIN">시스템관리자</option>
									<c:forEach var="authInfo" items="${authLists}" varStatus="status">
										<option value="<c:out value="${authInfo.code}"/>"><c:out value="${authInfo.codeNm}"/></option>
									</c:forEach>
								</c:otherwise>
							</c:choose>
						</select>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="important">사용여부</em></h4></dt>
				<dd>
					<div class="sel_box">
						<select id="mdNewUseFlag" class="wide">
							<option value="N">미사용</option>
							<option value="Y">사용</option>
						</select>
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="">이메일 주소</em></h4></dt>
				<dd>
					<div class="ipt_box">
						<input type="text" id="mdNewEMail">
					</div>
				</dd>
			</dl>
			<dl>
				<dt><h4><em class="">핸드폰 번호</em></h4></dt>
				<dd>
					<div class="ipt_box">
						<input type="text" id="mdNewMobileNo">
					</div>
				</dd>
			</dl>
		</div>
	</div>
	<div class="modal_footer">
		<div class="btn_wrap fr">
			<a href="#" class="btn" onclick="cudUserInfo('insert'); return false;">저장</a>
		</div>
	</div>
	<div class="modal_controller">
		<a href="#" class="close">close</a>
	</div>
</div>
<!--  modal :: 사용자 서비스 등록 팝업 end -->
</body>
</html>