<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : SystemAlarmForm.html
 * @desc    : 시스템알람관리 화면 Page
 *=============================================================
 * Wivismall
 * Copyright(C) 2019 TSIT, All rights reserved.
 *=============================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  ==================================
 * 1.0  2020.05.19   yujung      최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<div class="main-title">
		</div>

		<div class="panelStyle2">
			<form id="searchForm" name="searchForm" action="#" th:action="@{'/system/alarm/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
				<table class="frmStyle" aria-describedby="검색조건">
					<colgroup>
						<col style="width:80px;"/>
						<col style="width:500px;"/>
						<col/>
					</colgroup>
					<tbody>
						<tr>
							<th class="dashR">알람제목</th>
							<td class="dashR">
								<input type="text" name="alarmTitle" class="w300"/>
							</td>
						</tr>
					</tbody>
				</table>
				<div class="panelBtnB">
					<input type="button" value="초기화" class="btn btn-gray btn-lg" id="btnReset" onclick="$('#searchForm')[0].reset();"/>
					<input type="button" value="조회" class="btn btn-base btn-lg" id="btnSearch" onclick="fnSearch();"/>
				</div>
			</form>
		</div>
		
		<div class="panelStyle2">
			<table class="frmStyle">
				<colgroup>
					<col style="width:60%;"/>
					<col/>
				</colgroup>
				<tr>
					<td style="border-top: none;">
						<ul class="lrStyle">
							<li class="padB10">
								<h4 style="margin-top: -10px;">알람목록</h4>
							</li>
						</ul>
						
						<div class="panelContent" style="overflow: hidden;">
							<div id="alarmGridList" style="width: 100%; height: 630px;" class="ag-theme-balham"></div>
						</div>
					</td>
					<td style="border-top: none; vertical-align: top;">
						<ul class="lrStyle">
							<li class="padB10">
								<button type="button" class="btn btn-info btn-lg" id="btnNew">신규</button>
								<button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
							</li>
						</ul>
						
						<form id="detailForm" name="detailForm" action="#" th:action="@{'/system/basic/answer/save'}">
							<table >
								<colgroup>
									<col style="width:10%;"/>
									<col style="width:20%;"/>
									<col style="width:10%;"/>
									<col style="width:20%;"/>
									<col style="width:10%;"/>
									<col style="width:20%;"/>
									<col/>
								</colgroup>
								<tr>
									<th>알람ID<i class="star"></i></th>
									<td>
										<input type="text" name="alarmId" readonly="readonly" placeholder="자동생성"/><!-- required="required" data-valid-name="알람ID" -->
									</td>
									
									<th>사용여부</th>
									<td>
										<input type="hidden" name="useYn" value="Y"/>
										<label><input type="checkbox" name="chkUseYn" checked="checked"/>사용</label>
									</td>
								</tr>
								<tr>
									<th>알람제목<i class="star"></i></th>
									<td colspan="3">
										<input type="text" name="alarmTitle" required="required" data-valid-name="알람제목"/>
									</td>
								</tr>
								<tr>
									<th>알람메세지<i class="star"></i><br/>(<span name="count"> 0 </span> / 80 byte)</th>
									<td colspan="9">
										<input type="text" name="alarmMsg" required="required" data-valid-name="알람메시지"/>
									</td>
								</tr>
								<tr>
									<td colspan="4" style="padding-left: 0px;padding-right: 0px;">
										<div class="aL">
											<h4>알람 수신자</h4>
											<button type="button" class="btn btn-warning btn-sm" id="btnAddRow">행추가</button>
											<button type="button" class="btn btn-danger btn-sm" id="btnDeleteRow">행삭제</button>
											<button type="button" class="btn btn-success btn-lg" id="btnReciverSave" style="margin-left:335px;">저장</button>
										</div>
										
										<input type="hidden" id="reciverAlarmId"/>
										<div id="receiverGridList" style="width: 100%; height: 455px;" class="ag-theme-balham"></div>
									</td>
								</tr>
							</table>
						</form>
					</td>
				</tr>
			</table>
		</div>
		
	</div>

<script th:inline="javascript">
/*<![CDATA[*/

	var useYnList = { "Y":"Yes", "N":"No" };
	
	var alarmColumnDefs = [
// 		{headerName: "삭제",		field:'delete',			width:60,	cellClass: 'text-center'
// 			, cellRenderer: function(params) {
// 				return "<a href=\"javascript:void(0);\" class=\"btn btn-danger btn-sm\">삭제</a>";
// 			}
// 		},
		{headerName: "알람ID",		field:'alarmId',		width:100,	cellClass: 'text-center'
// 			, cellRenderer: function(params) { return '<a href=\"javascript:void(0);\">' + params.value + '</a>'; }
		},
		{headerName: "알람제목",	field:'alarmTitle',		width:250,	cellClass: 'text-left'
			, cellRenderer: function(params) { return '<a href=\"javascript:void(0);\">' + params.value + '</a>'; }
		},
		{headerName: "알람메세지",	field:'alarmMsg',		width:455,	cellClass: 'text-left'},
		{headerName: "사용여부",	field:'useYn',			width:80,	cellClass: 'text-center'},
		
		{headerName: "등록자",		field:'regId',			width:120,	cellClass: 'text-center', hide: true},
		{headerName: "등록일시",	field:'regDt',			width:150,	cellClass: 'text-center', hide: true,
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYY/MM/DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss") : '';
			}	
		},
		{headerName: "수정자",		field:'updId',			width:120,	cellClass: 'text-center', hide: true},
		{headerName: "수정일시",	field:'updDt',			width:150,	cellClass: 'text-center', hide: true,
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYY/MM/DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss") : '';
			}	
		}
	];
	
	var receiverColumnDefs = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "알람ID",		field:'alarmId',		width:100,	cellClass: 'text-center', editable:false},
		{headerName: "수신자명",	field:'receiverNm',		width:100,	cellClass: 'text-center', cellEditorParams: { maxlength: 4, required: true }},
		{headerName: "수신자번호",	field:'cellPhnno',		width:150,	cellClass: 'text-center', cellEditorParams: { maxlength: 11, required: true }},
		{headerName: "사용여부",	field:'useYn',			width:80,	cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(useYnList), maxlength: 20, required: true},
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(useYnList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(useYnList, params.newValue); }	
		},
		{headerName: "등록자",		field:'regId',			width:120,	cellClass: 'text-center', hide: true},
		{headerName: "등록일시",	field:'regDt',			width:150,	cellClass: 'text-center', hide: true,
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYY/MM/DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss") : '';
			}	
		},
		{headerName: "수정자",		field:'updId',			width:120,	cellClass: 'text-center', hide: true},
		{headerName: "수정일시",	field:'updDt',			width:150,	cellClass: 'text-center', hide: true,
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYY/MM/DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss") : '';
			}	
		}
	]
	
	
	var alarmGridOptions = gagaAgGrid.getGridOptions(alarmColumnDefs);
	var receiverGridOptions = gagaAgGrid.getGridOptions(receiverColumnDefs);
	receiverGridOptions.rowSelection = 'multiple';
	receiverGridOptions.defaultColDef.editable = true;
	receiverGridOptions.stopEditingWhenGridLosesFocus = true;
	
	// 셀 클릭 이벤트
	alarmGridOptions.onCellClicked = function(event) {
		if (event.colDef.field == 'alarmTitle') {
			fnReceiverSearch(event.data.alarmId);
			fnBindData(event.data);
		}
		
		if (event.colDef.field == 'alarmId') {
// 			fnReceiverSearch(event.data.alarmId);
		}
		
		if (event.colDef.field == 'delete') {
// 			fnDeleteAlarm(event.data.alarmId);
		}
	}
	
	// 바인딩
	var fnBindData = function(data) {
		$('#detailForm input[name=alarmId]').val(data.alarmId);
		$('#detailForm input[name=alarmTitle]').val(data.alarmTitle);
		$('#detailForm input[name=alarmMsg]').val(data.alarmMsg);
		
		if (data.useYn == 'Y') {
			$("#detailForm input:checkbox[name=chkUseYn]").prop('checked', true);
			$("#detailForm input:checkbox[name=chkUseYn]").parent().addClass('checked');
		} else {
			$("#detailForm input:checkbox[name=chkUseYn]").prop('checked', false);
			$("#detailForm input:checkbox[name=chkUseYn]").parent().removeClass('checked');
		}
		
	}
	// 검색
	var fnSearch = function() {
		var formId = '#searchForm';
		gagaAgGrid.fetch($(formId).prop('action'), alarmGridOptions, formId);
	}
	
	// 신규
	$('#btnNew').on('click', function() {
		$('#detailForm')[0].reset();
		$('#detailForm input[name=alarmId]').val('');
		$('#detailForm input[name=alarmTitle]').focus();
		receiverGridOptions.api.setRowData('');
	});
	
	// 저장/수정
	$("#btnSave").on("click", function() {
		var formId = '#detailForm';

		if (!gagajf.validation(formId))
			return;
	
		var msg = '수정하시겠습니까?';
		if (gagajf.isNull($('#detailForm input[name=alarmId]').val())) msg = '등록하시겠습니까?'; 
		
		mcxDialog.confirm(msg, {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				$(formId + ' input[name=useYn]').val($(formId + ' input:checkbox[name=chkUseYn]').is(":checked") ? 'Y' : 'N');	// 사용여부
				gagajf.ajaxFormSubmit('/system/alarm/save', formId, fnSearch);
			}
		});
	});
	
	// 삭제
	var fnDeleteAlarm = function(alarmId) {
		mcxDialog.confirm('삭제하시곘습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var data = {alarmId : alarmId};
				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit('/system/alarm/delete', jsonData, fnSearch);
			}
		});
	}
	
	// 수신자 관련 함수
	// 수신자 조회
	var fnReceiverSearch = function(alarmId) {
		$('#reciverAlarmId').val(alarmId);
		
		var data = {alarmId : alarmId};
		var jsonData = JSON.stringify(data);

		gagajf.ajaxJsonSubmit('/system/alarm/reciver/list', jsonData, function(result) {
			receiverGridOptions.api.setRowData(result);
		});
	}
	
	// 행추가
	$('#btnAddRow').on('click', function() {
		var alarmId = $('#reciverAlarmId').val();
		if (gagajf.isNull(alarmId)) {
			mcxDialog.alert('알람ID를 선택해 주세요.');
			return;
		}
		var data = { alarmId: alarmId, receiverNm: null, cellPhnno: null, useYn: "Y" };
		gagaAgGrid.addRowData(receiverGridOptions, data, 'alarmId');
	});
	
	// 행삭제
	$('#btnDeleteRow').on('click', function() {
		var removedData = gagaAgGrid.removeRowData(receiverGridOptions);
		
		if (removedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		mcxDialog.confirm("삭제하시겠습니까?", {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(removedData);
				gagajf.ajaxJsonSubmit('/system/alarm/reciver/delete', jsonData, function() {
					fnReceiverSearch($('#reciverAlarmId').val());
				});
			}
		});
	});
	
	// 바이트
	$("#detailForm input[name=alarmMsg]").bind('focus focusout input keyup keydown paste change', function () {
		cfnGetTextLength($(this), 80, $('#detailForm span[name=count]'));
	});
	
	// 저장
	$('#btnReciverSave').on('click', function() {
		var changedData = gagaAgGrid.getChangedData(receiverGridOptions);
		
		// Validation
		if (!gagaAgGrid.validation(receiverGridOptions, changedData))
			return;
		
		var Msg = '';
		$(changedData).each(function(idx, item) {
			item.cellPhnno.replaceAll("-", "");
			
			var regexp = /^[0-9]*$/
			if( !regexp.test(item.cellPhnno) ) {
				Msg = '휴대전화번호는 숫자를 입력해주세요.';
				return;
			}
			
			if (item.cellPhnno.length > 11 || item.cellPhnno.length < 11) {
				Msg = '휴대전화번호 길이는 11자리 입니다.';
				return;
			}
		});
		
		if (!gagajf.isNull(Msg)) {
			mcxDialog.alert(Msg);
			return;
		}
		
		mcxDialog.confirm("저장하시겠습니까?", {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(changedData);
				gagajf.ajaxJsonSubmit('/system/alarm/reciver/save', jsonData, function() {
					fnReceiverSearch($('#reciverAlarmId').val());
				});
			}
		});
	});
	
	$(document).ready(function() {
		gagaAgGrid.createGrid('alarmGridList', alarmGridOptions);
		gagaAgGrid.createGrid('receiverGridList', receiverGridOptions);
		
		// Grid 높이 자동 조정
		uifnFitGrid(50);
		fnSearch();
	});

/*]]>*/
</script>

</html>