<%@ 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">
	<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>
				    <div class="container-page-btn">
				        <button type="button" id="btnReset--${pageName}" class="btn btn-outline-dark" title="초기화">초기화</button>
				        <span class="container-window-btn-right">
				            <button type="button" id="btnSearch--${pageName}" class="btn btn-search" title="검색">검색</button>
				        </span>
				    </div>

				    <form id="frmSearch--${pageName}" name="frmSearch">
				        <div class="container-search">
		                    <div class="row g-1">
		                        <div class="col-6">
		                            <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 class="col-6">
		                        	<label class="form-label fw-bold form-search-title">요청일자</label>
		                        	<span class="form-search-linebox">
		                                <input type="text" id="schDmndYmdFrom--${pageName}" name="schDmndYmdFrom" 
		                                	class="form-control form-date"
		                                	data-fmt-type="day"   title="시작 날짜 선택" />
		                                <button type="button" class="bx bx-sm bx-calendar bg-white"></button>
		                                ~
		                                <input type="text" id="schDmndYmdTo--${pageName}" name="schDmndYmdTo" 
		                                	class="form-control form-date"
		                                	data-fmt-type="day" title="종료 날짜 선택">
		                                <button type="button" class="bx bx-sm bx-calendar bg-white"></button>
		                            </span>
		                        </div>
		                    </div>
				        </div>
				    </form>

				    <div>
				        <span class="container-page-btn">
				            <div class="d-flex flex-row justify-content-between">
								<label id="dmndPaging--${pageName}PagingInfo" class="dataTables_info" 
									role="status" aria-live="polite"></label>
				                 <ul id="dmndPaging--${pageName}" class="pagination pagination-primary">
				                 </ul>
							</div>
				            <span class="container-window-btn-right">
				            	<button type="button" id="btnOpenDmndPop--${pageName}" 
				            		class="btn btn-primary" title="요청 등록">요청 등록</button>
				            	<button type="button" id="btnDelete--${pageName}" 
				            		class="btn btn-primary" title="한 건 삭제">한 건 삭제</button>
				            	<button type="button" id="btnDeleteAllCompleteData--${pageName}" 
				            		class="btn btn-primary" title="요청 완료자료 전체 삭제">요청 완료자료 전체 삭제</button>
				            </span>
				        </span>
				    </div>

				    <div class="card-datatable text-nowrap">
				        <div id="DataTables_Table_0_wrapper--${pageName}" class="dataTables_wrapper dt-bootstrap5 no-footer">
							<div id="table-responsive--${pageName}" class="table-responsive"
								style="overflow-x: scroll;height:550px;overflow-y: scroll;">
								<table id="DataTables_Table_0--${pageName}"
									class="datatables-ajax table table-bordered dataTable no-footer">
									<thead id="dmndThead--${pageName}">
										<tr data-by="by--${pageName}" data-by-output="byOutput--${pageName}"
											data-main-option="mainOption--${pageName}" data-sub-option="subOption--${pageName}">
											<th style="min-width: 80px;">No.</th>
											<th style="min-width: 80px;">요청일시</th>
											<th style="min-width: 80px;">요청자</th>
											<th style="min-width: 80px;">접수일자</th>
											<th style="min-width: 80px;">목록번호</th>
											<th style="min-width: 80px;">상태</th>
											<th style="min-width: 80px;">응답일시</th>
										</tr>
									</thead>
				                    <tbody id="dmndTbody--${pageName}"></tbody>
									<template id="dmndRow--${pageName}">
										<tr data-key="{INDIV_ID}">
											<td onclick="{onclick}" class="text-end">{ROW_NUM}</td>
											<td onclick="{onclick}" class="text-center">{DMND_YMD}</td>
											<td onclick="{onclick}" class="text-center">{RGTR}</td>
				                    		<td onclick="{onclick}" class="text-center">{RCPT_YMD}</td>
				                    		<td onclick="{onclick}" class="text-center">{PST_NO}</td>
				                    		<td onclick="{onclick}" class="text-center">{STTS_NM}</td>
				                    		<td onclick="{onclick}" class="text-center">{RSPNS_DT}</td>
				                    	</tr>
									</template>
									<template id="dmndNotFound--${pageName}">
										<tr>
											<td valign="top" colspan="7" class="dataTables_empty text-center">요청 정보를 찾지 못했습니다.</td>
										</tr>
									</template>
								</table>
							</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 id="toastText--${pageName}" 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>

<template id="seallDmndDialogTemplate--${pageName}">
	<form id="frmEdit--${pageName}">
		<div class="card">
			<div class="row g-1">
				<div class="col-md-12">
					<label for="rcptYmd--${pageName}"
						class="w-px-120 bg-lighter pe-2 col-form-label text-sm-end required">접수일자</label>
					<input type="text" id="rcptYmd--${pageName}" name="rcptYmd" required 
						class="form-control form-date" data-fmt-type="day" />
					<button type="button" class="bx bx-sm bx-calendar bg-white"></button>
				</div>
				<div class="col-md-12">
					<label for="pstNo--${pageName}"
							class="w-px-120 bg-lighter pe-2 col-form-label text-sm-end required">목록번호</label>
					<input type="text" id="pstNo--${pageName}" name="pstNo" required
						class="form-control" type="text" maxlength="6" data-maxlengthb="6" data-fmt-type="zeroLpadNumber" />
				</div>
			</div>
		</div>
		<div>
			<span class="container-page-btn">
				<span class="container-window-btn-right">
					<button type="button" class="btn btn-primary" id="btnCreate--${pageName}" title="확인">확인</button>
				</span>
			</span>
		</div>
	</form>
</template>

<script>

/**************************************************************************
 * Global Variable
 **************************************************************************/
 var FIM063 = new CommonCodes(${FIM063});
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.dmndControl = new DatasetControl({
	    urls : { load : "", create : "", remove : "" },
	    dataGetter : obj => obj["List"], appendData:true,
	    keymapper : info => info ? info.INDIV_ID : "", 
	    formats : {
	    	DMND_YMD 	: dateFormat,
	    	RCPT_YMD 	: dateFormat,
	    	RSPNS_DT 	: datetimeFormat
		}
	});
	$P.dmndControl.defaultFetchSize = FETCH_XS;
	$P.dmndControl.untilPageNum = 0;
	$P.dmndControl.beforeCurrent = null;
	$P.dmndControl.tableRenderComplete = false;
	
	/**************************************************************************
	 * DatasetControl.on
	 **************************************************************************/
	$P.dmndControl.onDatasetChange = (obj) => {
		
	    $P.renderDmndList(obj["Total"]);

	    $("#dmndPaging--${pageName}").setPagingInfo({
	        list: $P.dmndControl.dataset,
	        prefix: "dmndPaging--${pageName}",
	        start: obj["Start"],
	        totalSize: obj["Total"],
	        fetchSize: obj["Fetch"],
	        func: "pageObject['${pageName}'].dmndControl.load({index})"
	    });

	    $P.dmndControl.tableRenderComplete = true;
	};

	$P.dmndControl.onCurrentChange = (item) => {
		if(!$P.dmndControl.tableRenderComplete){
			return;
		}

		if($P.dmndControl.beforeCurrent != null){
			var beforeCurrentKey = $P.dmndControl.beforeCurrent.key;
			var beforeCurrentIndex = $P.dmndControl.beforeCurrent.index;
			$P.dmndControl.beforeCurrent = null;
			
			if(!$P.dmndControl.dataset.empty){
				var info = $P.dmndControl.dataset.getData(beforeCurrentKey);
				
				if(info != null){
					$P.dmndControl.dataset.setCurrent(beforeCurrentKey,true);
					return;
				}
					
				if(beforeCurrentIndex > ($P.dmndControl.dataset.length - 1)){
					info = $P.dmndControl.dataset.getDataset()[$P.dmndControl.dataset.length - 1];
				} else {
					info = $P.dmndControl.dataset.getDataset()[beforeCurrentIndex];
				}
				
				$P.dmndControl.dataset.setCurrent(info["INDIV_ID"],true);
				return;
			}
		}
		
		$P.dmndControl.tableRenderComplete = false;
		if(!item){
			$P.clickDmndList("", true);
		} else {
			$P.clickDmndList($P.dmndControl.getCurrent()["INDIV_ID"], true);
		}
	}
	
	$P.dmndControl.onRemove = (selected, resp) => {
		if (resp.saved){
			$("#toastText--${pageName}").html("삭제 되었습니다.");
			$P.toast.show();
			
			$P.refreshDmndList();
		}
	}
	
	/**************************************************************************
	 * pageObject.function
	 **************************************************************************/
	$P.fnReset = () => {
    	
		$('#schDmndYmdFrom--${pageName}').datepicker('setDate', DateUtil.getDateDay(-5475).date);
	    $('#schDmndYmdTo--${pageName}').datepicker('setDate', new Date());
		$P.dmndControl.setData([]);
	}

	$P.fnResetAndChangeBiz = (taskSeCd) => {
		$P.fnReset();
		$P.dmndControl.urls.load = wctx.url("/"+taskSeCd+"/cvlc/cvlc04/010/list.do");
		$P.dmndControl.urls.create = wctx.url("/"+taskSeCd+"/cvlc/cvlc04/010/create.do");
		$P.dmndControl.urls.remove = wctx.url("/"+taskSeCd+"/cvlc/cvlc04/010/remove.do");
	}
	
	$P.refreshDmndList = () => {
		$P.dmndControl.untilPageNum = $P.dmndControl.query.pageNum;
		$P.dmndControl.query.fetchSize = $P.dmndControl.defaultFetchSize * $P.dmndControl.query.pageNum;
		
		if(!$P.dmndControl.dataset.empty){
			$P.dmndControl.beforeCurrent = {
				key : $P.dmndControl.getCurrent()["INDIV_ID"],
				index : $P.dmndControl.getCurrent()["ROW_NUM"] - 1
			};
		}
		
	    $P.dmndControl.load(1);
	}
	
	$P.searchDmndList = () => {
		
		$P.dmndControl.query = $P.getParams();
		
	    $P.dmndControl.load(1);
	}

	$P.scrollEnd = (obj) => {
		if(obj.dataset.scrollStatus){
			return;
		}

		var el = $(obj);
    	if(el.scrollTop() == 0){
    		return;
    	}

    	if((el[0].scrollHeight - el.scrollTop() + VERTICAL_SCROLL_HEIGHT) <= el.outerHeight()){
    		obj.dataset.scrollStatus = "waiting";
    		$P.scrollDmndList();
    	}
	}

	$P.scrollDmndList = () => {
		$P.dmndControl.load($P.dmndControl.query.pageNum + 1);
	}

	$P.clickDmndList = (dataKey, auto) => {
		if(dataKey == ""){
			if(auto){
				$("label[for='table-responsive--${pageName}']").trigger("refreshEnd");
			}
			return;
		}
		
		$("#dmndTbody--${pageName}").setCurrentRow(dataKey);

		if(!auto){
			$P.dmndControl.setCurrent(dataKey);
		} else {
			$("label[for='table-responsive--${pageName}']").trigger("refreshEnd");
		}
	}

	$P.renderDmndList = (total) => {

	    var dmndList = $P.dmndControl.dataset;
		var empty = dmndList.empty;
		var notFound = [document.getElementById("dmndNotFound--${pageName}").innerHTML];
		var found = document.getElementById("dmndRow--${pageName}").innerHTML;
		var replacer = (str, dataItem) => str
			.replace(/{onclick}/gi, "pageObject['${pageName}'].clickDmndList('" + dataItem.getValue("INDIV_ID") + "');");
		var trs = empty ? notFound : dmndList.inStrings(found, replacer);
		$("#dmndTbody--${pageName}").html(trs.join());
		
		if(total == dmndList.length){
			$("#table-responsive--${pageName}").attr("data-scroll-status", "complete");
		} else {
			$("#table-responsive--${pageName}").removeAttr("data-scroll-status");
		}
	    
		if($P.dmndControl.untilPageNum != 0){
			$P.dmndControl.query.fetchSize = $P.dmndControl.defaultFetchSize;
			$P.dmndControl.query.pageNum = $P.dmndControl.untilPageNum;
			$P.dmndControl.untilPageNum = 0;
		}  
	}

	$P.getParams = () => {
		var formFields = new FimsFormFields("#frmSearch--${pageName}");
		var data = formFields.get();
		data.fetchSize = $P.dmndControl.defaultFetchSize;

		return data;
	}
	
	$P.fnRemove = (allCompleteDataIds) => {
		
		if(allCompleteDataIds != null){			
			$P.dmndControl.select(allCompleteDataIds,true);
		} else {
			var cur = $P.dmndControl.getCurrent();
			if(cur == null){
				return;
			}
			
			var curKey = cur["INDIV_ID"];
			$P.dmndControl.select(curKey,true);
		}
		
		$P.dmndControl.remove();
	}
	
	$P.fnRemoveAllCompleteData = () => {
		var cur = $P.dmndControl.getCurrent();
		if(cur == null){
			return;
		}
		
		var ds = $P.dmndControl.dataset.getDataset();

		var indivIds = ds.filter(function(item){
			if(item['STTS_CD'] == '9' || item['STTS_CD'] == 'B'){
				return item["INDIV_ID"];
			}
		});

		if(indivIds.length == 0){
			dialog.alert("요청 완료자료가 없습니다.");
			return;
		}
		
		dialog.alert({
			content : "완료된 자료를 모두 삭제하시겠습니까?",
			onOK : () => {
				$P.fnRemove(indivIds);
			}
		});
	}
	
	//요청 등록 팝업 호출
	$P.fnOpenDmndPop = () => {
		dialog.open({
			id : "seallDmndDialog--${pageName}",
			title : "새올 접수 요청",
			content : document.getElementById("seallDmndDialogTemplate--${pageName}").innerHTML,
			size : "lg",
			init : () => {
				initDatepicker("seallDmndDialog--${pageName}");
				$('#rcptYmd--${pageName}').datepicker('setDate', new Date());
				$('#btnCreate--${pageName}').on("click", () => $P.fnCreateDmnd());
			},
			onClose : () => {}
		});
	}
	
	//요청 등록
	$P.fnCreateDmnd = () => {
		
		if(!customValidate($("#frmEdit--${pageName} input"))) return;
		
		var info = (new FimsFormFields("#frmEdit--${pageName}")).get();
		info.taskSeCd = $("#frmSearch--${pageName} input[name='taskSeCd']:checked").val();
		
		ajax.get({
			url : $P.dmndControl.urls.create,
			data : info,
			success : resp => {
				if(resp.saved){
					dialog.close("seallDmndDialog--${pageName}");
					
					$("#toastText--${pageName}").html("등록 되었습니다.");
					$P.toast.show();
					
					if(!$P.dmndControl.dataset.empty){
						$P.refreshDmndList();
					}
				}
			}
		});
	}
	
	/**************************************************************************
	 * element.on
	 **************************************************************************/
    $('#btnReset--${pageName}').on('click', () => $P.fnReset());
    $('#btnSearch--${pageName}').on('click', () => $P.searchDmndList());
    $("#table-responsive--${pageName}").scroll(function(){ $P.scrollEnd(this); });

    $("#btnOpenDmndPop--${pageName}").on("click", () => $P.fnOpenDmndPop());
    $("#btnDelete--${pageName}").on("click", () => $P.fnRemove(null));
    $("#btnDeleteAllCompleteData--${pageName}").on("click", () => $P.fnRemoveAllCompleteData());
    
	/**************************************************************************
	 * 초기화
	 **************************************************************************/
  	//달력 초기화
    initDatepicker("frmSearch--${pageName}");

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

});


</script>