<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" session="false"%>
<%@ include file="/WEB-INF/jsp/include/taglib.jsp"%>
<!-- inner page html -->
<div class="content-wrapper" id="wrapper--${pageName}">
	<div class="container-xxl flex-grow-1 px-0">
		<c:set var="pageKorName" scope="request">계도문 문구 관리</c:set>
		<div class="card">
			<div class="wrapper-list">
				<div>
				    <form id="frmSearch--${pageName}" name="frmSearch">
				        <div class="container-search">
		                    <div class="row g-1">
		                        <div class="col-12">
		                            <label class="form-label fw-bold form-search-title">업무구분</label>
		                            <span class="form-search-linebox">
										<c:forEach items="${FIM054List}" var="item">
											<label>
												<input name="taskSeCd" type="radio" value="${item.code}"
												class="form-check-input" alt="업무구분"
												onchange="pageObject['${pageName}'].fnResetAndChangeBiz(this.value);">
												${item.value}
											</label>
										</c:forEach>
		                            </span>
		                        </div>
		                    </div>
				        </div>
				    </form>
				    
					<div class="container-page-btn mt-3">
				        <button type="button" id="btnReset--${pageName}" class="btn btn-outline-dark" 
				        title="초기화">초기화</button>
				    </div>
				    
				    <div class="h-px-500 mt-4">
				    	
			    		<div class="d-flex flex-row justify-content-center" style="height:100%">
							<div class="card p-4 d-flex flex-row w-px-1300">
								<!-- 그리드 영역 -->
								<div class="card-datatable text-nowrap d-inline-flex" 
									style="border: #D9DEE3 1px solid;">
									<div class="dataTables_wrapper dt-bootstrap5 no-footer">
										<div class="table-responsive"
											style="height:100%;width:470px;overflow-y: auto;">
											<table class="datatables-ajax table table-bordered dataTable no-footer">
												<thead>
													<tr>
														<th style="width:50px;"></th>
														<th style="min-width: 300px;">계도사유</th>
													</tr>
												</thead>
							                    <tbody id="warningWordsTbody--${pageName}"></tbody>
												<template id="warningWordsRow--${pageName}">
													<tr data-key="{LEVY_EXCL_RSN_CD}">
														<td class="text-center" style="min-width:50px;max-width: 50px;">
															<input type="radio" name="gridRadio" value="{LEVY_EXCL_RSN_CD}"
															onchange="{onchange}" />
														</td>
							                    		<td onclick="{onclick}" class="text-center">{LEVY_EXCL_RSN_NM}</td>
							                    	</tr>
												</template>
												<template id="warningWordsNotFound--${pageName}">
													<tr>
														<td valign="top" colspan="2" 
														class="dataTables_empty text-center">정보를 찾지 못했습니다.</td>
													</tr>
												</template>
											</table>
										</div>
									</div>
							    </div>

						    	<!-- 제목,내용 표시영역 -->
							    <div class="w-px-800 d-inline-flex">
						    		<div class="container-md"
						    			style="display: flex;justify-content: space-between;flex-flow: column;">
								    	<div class="row g-1 h-px-400" 
								    		style="overflow-y:auto;border-bottom:#D9DEE3 1px solid">
									    	<div class="col-12">
									    		<form id="frmEditWarningWords--${pageName}">
									    			<input type="hidden" id="ansRsnCd--${pageName}" name="ansRsnCd" />
									    			<input type="hidden" id="ansWordsId--${pageName}" name="ansWordsId" />
									    			<label for="mailTtlNm--${pageName}"
									    			class="w-px-130 bg-lighter pe-2 col-form-label text-sm-center">제목</label>
									    			<input type="text" id="mailTtlNm--${pageName}" name="mailTtlNm" required
									    			class="form-control w-px-500" />
									    			<br/>
									    			<label for="mailCn--${pageName}"
									    			class="w-px-130 bg-lighter pe-2 col-form-label text-sm-center" hidden>내용</label>
									    			<textarea id="mailCn--${pageName}" name="mailCn" class="form-control" required
									    			style="width:100%;" rows="15"
									    			></textarea>
									    		</form>
									    	</div>
								    	</div>
								    	<div class="row g-1 py-2">
								    		<div class="col-12">
								    			<div class="btns float-end">
									            	<button type="button" id="btnSave--${pageName}" 
									            		class="btn btn-primary" title="적용">적용</button>
								    			</div>
							    			</div>
						            	</div>
					            	</div>
								</div>
						    </div>
						</div>
				    </div>
				</div>

				<div class="toast-container position-fixed bottom-0 end-0 p-3">
				  <div id="divToast--${pageName}" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
				    <div class="toast-body bg-black text-white">
				      저장 되었습니다.
				    </div>
				  </div>
				</div>
			</div>
		</div>
	</div>

	<jsp:include page="/WEB-INF/jsp/include/bottom.jsp" />

  	<div class="content-backdrop fade"></div>
</div>

<script>
/**************************************************************************
 * Global Variable
 **************************************************************************/
pageObject["${pageName}"] = {};

$(document).ready(function(){

	var $P = pageObject["${pageName}"];
	
	$P.toast = new bootstrap.Toast(document.getElementById('divToast--${pageName}'), {
        animation: true,
        autohide: true,
        delay: 2000
    });
	
	/**************************************************************************
	 * DatasetControl
	 **************************************************************************/
	$P.warningWordsControl = new DatasetControl({
	    dataGetter : obj => obj["List"], 
	    urls : {}, 
	    formats : {},
	    keymapper : info => info ? info.LEVY_EXCL_RSN_CD : ""
	});
	
	/**************************************************************************
	 * pageObject.function
	 **************************************************************************/
	$P.fnResetAndChangeBiz = (taskSeCd) => {
		$P.warningWordsControl.urls = {};
		$P.warningWordsControl.urls.load = wctx.url("/"+taskSeCd+"/cvlc/cvlc06/010/list.do");
		$P.warningWordsControl.urls.update = wctx.url("/"+taskSeCd+"/cvlc/cvlc06/010/save.do");
		
		$P.fnReset();
	}
	
	$P.fnReset = () => {
		
		$P.warningWordsControl.setData([]);
		$P.renderWarningWordsList(0);
	    $("#frmEditWarningWords--${pageName}").find("input, textarea").val("");

	    $P.searchWordsStng();
	}

	$P.getParams = () => {
		var formFields = new FimsFormFields("#frmSearch--${pageName}");
		var data = formFields.get();
		return data;
	}
	
	$P.searchWordsStng = () => {
		var taskSeCd = $("#frmSearch--${pageName}").find("input[name='taskSeCd']:checked").val();

		ajax.get({
			url : $P.warningWordsControl.urls.load,
			data : {"taskSeCd" : taskSeCd},
			success : resp => {

				$P.warningWordsControl.setData(resp.List);

				$P.renderWarningWordsList(resp.List.length);

			    if(resp.List.length > 0){
			    	var current = $P.warningWordsControl.getCurrent()["LEVY_EXCL_RSN_CD"];
			    	$P.clickWarningWordsList(current);
			    }
			}
		});
	}
	
	$P.renderWarningWordsList = (total) => {

		var warningWordsList = $P.warningWordsControl.dataset;
		var empty = warningWordsList.empty;
		var notFound = [document.getElementById("warningWordsNotFound--${pageName}").innerHTML];
		var found = document.getElementById("warningWordsRow--${pageName}").innerHTML;
		
		var replacer = (str, dataItem) => str
			.replace(/{onclick}/gi, "pageObject['${pageName}'].clickWarningWordsList('" + dataItem.getValue("LEVY_EXCL_RSN_CD") + "');")
			.replace(/{onchange}/gi, "pageObject['${pageName}'].radioClickWarningWordsList('" + dataItem.getValue("LEVY_EXCL_RSN_CD") + "');");

		var trs = empty ? notFound : warningWordsList.inStrings(found, replacer);
		$("#warningWordsTbody--${pageName}").html(trs.join());
	}
	
	$P.radioClickWarningWordsList = (dataKey, gridType) => {
		
		$P.warningWordsControl.setCurrent(dataKey);

		$("#warningWordsTbody--${pageName}").setCurrentRow(dataKey);

		$P.changeTextarea();
	}
	
	$P.clickWarningWordsList = (dataKey, gridType) => {
		
		$("#wrapper--${pageName}").find(":radio[name='gridRadio'][value='"+dataKey+"']").prop("checked",true);
		$("#wrapper--${pageName}").find(":radio[name='gridRadio'][value='"+dataKey+"']").focus();
		
		
		$P.radioClickWarningWordsList(dataKey, gridType);
	}
	
	$P.changeTextarea = () => {
		
		var curData = $P.warningWordsControl.getCurrent();
		
		if(curData == null){
			$("#ansRsnCd--${pageName}").val("");
			$("#ansWordsId--${pageName}").val("");
			$("#mailTtlNm--${pageName}").val("");
			$("#mailCn--${pageName}").val("");
			return;
		}
		
		$("#ansRsnCd--${pageName}").val(curData["LEVY_EXCL_RSN_CD"]);
		$("#ansWordsId--${pageName}").val(curData["ANS_WORDS_ID"]);
		$("#mailTtlNm--${pageName}").val(curData["MAIL_TTL_NM"]);
		$("#mailCn--${pageName}").val(curData["MAIL_CN"]);
	}
	
	$P.refreshWarningWordsInfo = () => {
		
		var cursor = $P.warningWordsControl.getCurrent()["LEVY_EXCL_RSN_CD"];

		var taskSeCd = $("#frmSearch--${pageName}").find("input[name='taskSeCd']:checked").val();

		ajax.get({
			url : $P.warningWordsControl.urls.load,
			data : {"taskSeCd" : taskSeCd},
			success : resp => {
				
				$P.warningWordsControl.setData(resp.List);
			    $P.renderWarningWordsList(resp.List.length);
				if(resp.List.length > 0){
					$P.warningWordsControl.setCurrent(cursor);
					var current = $P.warningWordsControl.getCurrent()["LEVY_EXCL_RSN_CD"];
			    	$P.clickWarningWordsList(current,'warning');
			    }

			}
		});
	}

	//적용
	$P.fnSave = () => {
		
		if(!customValidate($("#frmEditWarningWords--${pageName}").find("input, select, textarea"))) return;
		
		var info = (new FimsFormFields("#frmEditWarningWords--${pageName}")).get();

		info.taskSeCd = $("#frmSearch--${pageName}").find("input[name='taskSeCd']:checked").val();

		dialog.alert({
			content : "저장하시겠습니까?",
			onOK: () => {
				
				ajax.get({
					url : $P.warningWordsControl.urls.update,
					data : info,
					success : resp => {
						if(resp.saved){
							$P.toast.show();	
							$P.refreshWarningWordsInfo();
						}
					}
				});
			}
		});
	}

	/**************************************************************************
	 * element.on			
	 **************************************************************************/
    $('#btnReset--${pageName}').on('click', () => $P.fnReset());
	
	//업무처리 버튼
    $("#btnSave--${pageName}").on("click", () => $P.fnSave());  

	/**************************************************************************
	 * 초기화
	 **************************************************************************/
    var defaultBizValue = $("#layout-navbar input[name='taskSeCd']:checked").val();
	$("#frmSearch--${pageName} input[name='taskSeCd'][value='" + defaultBizValue + "']").prop("checked",true);
	$P.fnResetAndChangeBiz(defaultBizValue);

});


</script>