<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : SystemAlarmForm.html
 * @desc    : 시스템알람관리 화면 Page
 *=============================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *=============================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  ==================================
 * 1.0  2020.11.13   yujung      최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		
		<!-- 검색조건 영역 -->
		<div class="panelStyle">
			<!-- Search -->
			<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:10%;"/>
						<col/>
					</colgroup>
					<tbody>
						<tr>
							<th>알람제목</th>
							<td>
								<input type="text" class="w300" name="alarmTitle" maxlength="100"/>
							</td>
						</tr>
					</tbody>
				</table>
				
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-base btn-lg" id="btnSearch">조회</button>
						<button type="button" class="btn btn-gray btn-lg" onclick="$('#searchForm')[0].reset();">초기화</button>
					</li>
				</ul>
			</form>
		</div>
		<!-- //검색조건 영역 -->

		<div class="panelStyle">
			<!-- 다중 TABLE 배치 -->
			<ul class="division">
				<li style="width: 60%">
					<div class="panelBar">
						<h4>알람목록</h4>
					</div>
					<div id="gridList1" style="width: 100%; height: 570px" class="ag-theme-balham"></div>
				</li>
				<li style="width: 40%">
					<!-- 버튼 배치 영역 -->
					<ul class="panelBar">
						<li>
							<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/alarm/save'}">
						<input type="hidden" name="mode" value="N"/>
						
						<table class="frmStyle" aria-describedby="등록/수정폼">
							<colgroup>
								<col style="width:20%;"/>
								<col style="width:30%;"/>
								<col style="width:20%;"/>
								<col/>
							</colgroup>
							<tr>
								<th>알람ID<i class="required" title="필수" aria-hidden="true"></i></th>
								<td>
									<input type="text" name="alarmId" placeholder="자동생성" readonly="readonly"/>
								</td>
								<th>사용여부</th>
								<td>
									<input type="hidden" name="useYn" value="Y"/>
									<label class="chkBox"><input type="checkbox" name="chkUseYn" checked="checked"/>사용</label>
								</td>
							</tr>
							<tr>
								<th>알람제목<i class="required" title="필수" aria-hidden="true"></i></th>
								<td colspan="3">
									<input type="text" name="alarmTitle" required="required" data-valid-name="알람제목"/>
								</td>
							</tr>
							<tr>
								<th>알람메세지<i class="required" title="필수" aria-hidden="true"></i><br/>(<span id="alarmMsgCnt">0</span> / 80 byte)</th>
								<td colspan="3">
									<input type="text" name="alarmMsg" required="required" data-valid-name="알람메시지"/>
								</td>
							</tr>
						</table>
					</form>
					
					<ul class="panelBar">
						<li>
							<h4>알람 수신자</h4>
						</li>
						<li class="right">
							<button type="button" class="btn btn-warning btn-lg" id="btnAddRow">행추가</button>
							<button type="button" class="btn btn-danger btn-lg" id="btnDeleteRow">행삭제</button>
							<button type="button" class="btn btn-success btn-lg" id="btnSaveReceiver">알람수신자 저장</button>
						</li>
					</ul>
					
					<div id="gridList2" style="width: 100%; height: 385px" class="ag-theme-balham"></div>
				</li>
			</ul>
		</div>
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	let ynList = { "Y":"Yes", "N":"No" };
	
	let columnDefs1 = [
		{
			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},
		{headerName: "알람메세지", field: "alarmMsg", width: 450},
		{
			headerName: "사용여부", field: "useYn", width: 80, cellClass: 'text-center',
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(ynList, params.value); }
		}
	];
	
	let columnDefs2 = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "CRUD", field: "crud", width: 75, hide: true},
		{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(ynList), maxlength: 20, required: true},
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(ynList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(ynList, params.newValue); }
		}
	]
	
	// Get GridOptions
	let gridOptions1 = gagaAgGrid.getGridOptions(columnDefs1);
	let gridOptions2 = gagaAgGrid.getGridOptions(columnDefs2);
	
	// 수정 가능
	gridOptions2.defaultColDef.editable = true;
	
	// 중복 선택 가능
	gridOptions2.rowSelection = 'multiple';
	
	gridOptions2.stopEditingWhenGridLosesFocus = true;
	
	// 셀 클릭 이벤트
	gridOptions1.onCellClicked = function(event) {
		if (event.colDef.field == 'alarmId') {
			$('#detailForm input[name=mode]').val('U');
			$('#detailForm input[name=alarmId]').val(event.data.alarmId);
			$('#detailForm input[name=alarmTitle]').val(event.data.alarmTitle);
			$('#detailForm input[name=alarmMsg]').val(event.data.alarmMsg);
			
			$("#detailForm input[name=useYn]").val(event.data.useYn);
			if (event.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');
			}
			
			// 수신자 목록
			fnSearchReceiverList();
		}
	}
	
	$('#btnSearch').on('click', function() {
		gagaAgGrid.fetch($('#searchForm').prop('action'), gridOptions1, '#searchForm');
	});
	
	// 수신자 목록 조회
	var fnSearchReceiverList = function() {
		let actionUrl = '/system/alarm/receiver/list/' + $('#detailForm input[name=alarmId]').val();
		gagaAgGrid.fetch(actionUrl, gridOptions2);
	}
	
	// 신규
	$('#btnNew').on('click', function() {
		$('#detailForm')[0].reset();
		$('#detailForm input[name=alarmId]').val('');
		$('#detailForm input[name=alarmTitle]').focus();
		gridOptions2.api.setRowData('');
	});
	
	// 알람 저장
	$("#btnSave").on("click", function() {
		if (!gagajf.validation('#detailForm'))
			return;
	
		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				$('#detailForm input[name=useYn]').val($('#detailForm input:checkbox[name=chkUseYn]').is(":checked") ? 'Y' : 'N'); // 사용여부
				gagajf.ajaxFormSubmit('/system/alarm/save', '#detailForm', function() {
					$('#btnSearch').trigger('click');
				});
			}
		});
	});
	
	// 행추가
	$('#btnAddRow').on('click', function() {
		var alarmId = $('#detailForm input[name=alarmId]').val();
		if (gagajf.isNull(alarmId)) {
			mcxDialog.alert('알람목록에서 알람ID를 선택해 주세요.');
			return;
		}
		
		var data = { alarmId: alarmId, receiverNm: null, cellPhnno: null, useYn: "Y" };
		gagaAgGrid.addRowData(gridOptions2, data, 'alarmId');
	});
	
	// 행삭제
	$('#btnDeleteRow').on('click', function() {
		var removedData = gagaAgGrid.removeRowData(gridOptions2);
		
		if (removedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		mcxDialog.confirm("삭제하시겠습니까?", {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(removedData);
				gagajf.ajaxJsonSubmit('/system/alarm/receiver/delete', jsonData, function() {
					fnSearchReceiverList();
				});
			}
		});
	});
	
	// 알람메시지 Byte 계산
	$("#detailForm input[name=alarmMsg]").bind('focus focusout input keyup keydown paste change', function () {
		cfnGetTextLength($(this), 80, $('#alarmMsgCnt'));
	});
	
	// 알람수신자 저장
	$('#btnSaveReceiver').on('click', function() {
		var changedData = gagaAgGrid.getChangedData(gridOptions2);
		
		if (changedData.length == 0) {
			mcxDialog.alert('변경된 데이터가 없습니다.');
			return;
		}
		
		// Validation
		if (!gagaAgGrid.validation(gridOptions2, 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/receiver/save', jsonData, function() {
					fnSearchReceiverList();
				});
			}
		});
	});
	
	$(document).ready(function() {
		gagaAgGrid.createGrid('gridList1', gridOptions1);
		gagaAgGrid.createGrid('gridList2', gridOptions2);
	});
/*]]>*/
</script>

</html>