<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" session="false"%>
<%@ include file="/WEB-INF/jsp/include/taglib.jsp"%>
<c:set var="pageKorName" scope="request">면제차량 관리</c:set>
<div class="content-wrapper" data-doctx="${pageName}">
	<div class="container-xxl flex-grow-1 px-0">
		<div class="card wrapper-list">
		    <div class="container-page-btn">
		        <button type="button" name="btnReset" class="btn btn-outline-dark w-px-120" title="초기화">초기화</button>
		        <span class="container-window-btn-right">
					<button type="button" name="btnSearch" class="btn btn-search w-px-120" title="검색">검색</button>
					<button type="button" name="btnExcel" class="btn btn-excel w-px-120" title="엑셀 저장">엑셀</button>
		        </span>
		    </div>

		    <form name="frmSearch">
		        <div class="container-search">
                    <div class="row g-1">
                        <div class="col-6">
                            <label is="name-label" for="vhrno" class="form-label fw-bold form-search-title w-px-120 text-end">차량번호</label>
							<input type="text" is="id-input" name="vhrno" class="form-control" />
                        </div>
                        <div class="col-6">
                            <label is="name-label" for="delYn" class="form-label fw-bold form-search-title w-px-120 text-end">삭제여부</label>
                            <select is="id-select" name="delYn" class="form-select">
                            	<option value="">전체</option>
                            	<option value="N">사용</option>
                            	<option value="Y">삭제</option>
                            </select>
                        </div>
                    </div>
		        </div>
		    </form>
			<div>
				<span class="container-page-btn">
					<div class="d-flex flex-row justify-content-between">
						<span is="paging-info" name="exmptnVhclPagingInfo" class="dataTables_info"></span>
		                <ul name="exmptnVhclPaging" class="pagination pagination-primary"></ul>
					</div>
					<span class="container-window-btn-right">
						<button type="button" name="btnCreate" class="btn btn-primary" title="면제차량 등록">면제차량 등록</button>
			         	<button type="button" name="btnOpenDelRsn" class="btn btn-primary" title="면제차량 삭제">면제차량 삭제</button>
			         	<button type="button" name="btnHistory" class="btn btn-primary" title="면제차량 수정이력">면제차량 수정이력</button>
					</span>
			     </span>
			</div>
			<div class="card-datatable text-nowrap">
		        <div class="dataTables_wrapper dt-bootstrap5 no-footer">
					<div name="table-responsive" class="table-responsive ox-scroll oy-scroll h-px-600">
						<table name="exmptnVhclTable" class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer">
							<thead class="sticky-thead">
								<tr name="exmptnVhclTheadTr">
									<th style="width: 80px;">No.</th>
									<th style="width: 130px;">차량번호</th>
									<th style="width: 200px;">사유</th>
									<th style="width: 150px;">공문번호</th>
									<th style="width: 150px;">소유주명</th>
									<th style="width: 200px;">면제기간</th>
									<th style="width: 150px;">등록자</th>
									<th style="width: 180px;">등록일시</th>
									<th style="width: 150px;">수정자</th>
									<th style="width: 180px;">수정일시</th>
									<th style="width: 150px;">삭제자</th>
									<th style="width: 200px;">삭제사유</th>
									<th style="width: 180px;">삭제일시</th>
									<th class="dummy-th"></th>
								</tr>
		                    </thead>
		                    <tbody name="exmptnVhclTbody"></tbody>
							<template is="curly-brackets" name="exmptnVhclRow">
	                    		<tr data-index="DATA-INDEX">
	                    			<td onclick ondblclick class="text-end">ROW_NUM</td>
	                    			<td onclick ondblclick class="text-center">VHRNO</td>
	                    			<td onclick ondblclick class="text-start">EXMPTN_RSN</td>
		                    		<td onclick ondblclick class="text-start">DOC_NO</td>
		                    		<td onclick ondblclick class="text-start">OWNR_NM</td>
		                    		<td onclick ondblclick class="text-center">{EXMPTN_BGNG_YMD} ~ {EXMPTN_END_YMD}</td>
		                    		<td onclick ondblclick class="text-start">RGTR_NM</td>
		                    		<td onclick ondblclick class="text-center">REG_DT</td>
		                    		<td onclick ondblclick class="text-start">MDFR_NM</td>
		                    		<td onclick ondblclick class="text-center">MDFCN_DT</td>
		                    		<td onclick ondblclick class="text-start">DLTR_NM</td>
		                    		<td onclick ondblclick class="text-start">DEL_RSN</td>
		                    		<td onclick ondblclick class="text-center">DEL_DT</td>
		                    		<td class="dummy-td"></td>
		                    	</tr>
	                    	</template>
	                    	<template name="exmptnVhclNotFound">
	                    		<tr><td valign="top" colspan="15" class="dataTables_empty text-center">면제차량 정보를 찾지 못했습니다.</td>
	                    		</tr>
	                    	</template>
						</table>
					</div>
				</div>
		    </div>
		</div>
	</div>
  	<div class="content-backdrop fade"></div>
</div>
<script>
LoadScript("crdn08010Script",wctx.url("/resources/js/fims/crdn/crdn08010.js?ver=${ver}"));

/**************************************************************************
* Global Variable
**************************************************************************/

pageObject["${pageName}"] = newDoctxFinder("${pageName}");

$(document).ready(function(){

	var $P = pageObject["${pageName}"];

	/**************************************************************************
	* DatasetControl, DatasetSupport, FormFields
	**************************************************************************/
	var ctrl = newCrdn08010Control($P);
	ctrl.defaultFetchSize = FETCH_XS;
	ctrl.query = { pageNum : 1, fetchSize : ctrl.defaultFetchSize };

	ctrl.dataset.onDatasetChange = (obj, option) => {
		var t = $P.getGridTemplate();
		var trs = Apply.fromDataset.getTbody(ctrl.dataset, t.found, t.notFound, t.replacer);
		$P.renderExmptnVhclList(obj?.Paging?.totalSize, ctrl.dataset.length, trs, option);

		$P.pagingSupport.setPagingInfo(obj);
	};

	ctrl.dataset.onCurrentChange = (dataItem) => {
		Apply.fromDataset.currentRow(ctrl.dataset, dataItem, $P.findn("exmptnVhclTbody"));
	}

	$P.pagingSupport = new FimsPagingSupport({
		doq: $P,
        linkContainer: "[name='exmptnVhclPaging']"
	});

	/**************************************************************************
	* pageObject.function
	**************************************************************************/
	$P.fnReset = () => {
		var searchForm = $P.$findn("frmSearch");
		searchForm.find("input[type='text']").val("");
		searchForm.find("input[type='hidden']").val("");

		ctrl.dataset.setData([]);
	}

	$P.getParams = () => {
		var formFields = new FimsFormFields($P.selectorn("frmSearch"));
		var data = formFields.get();
//		data.taskSeCd = "BPV";
		data.fetchSize = ctrl.defaultFetchSize;
		return data;
	}

	$P.searchExmptnVhclList = () => {
		ctrl.query = $P.getParams();
	    ctrl.load(1);
	}

	$P.scrollExmptnVhclList = () => {
		ctrl.load(ctrl.query.pageNum + 1);
	}

	$P.refreshExmptnVhclList = () => {
    	if (ctrl.query.pageNum == null)
    		ctrl.query.pageNum = 1;
        ctrl.reload({all : true});
    }

	$P.fnExcelDown = () => {
		if (ctrl.dataset.empty)
    		return alert("조회된 자료가 없습니다.");

		var cellDefs = AppSupport.getCellDefs(
			$P.$findn("exmptnVhclTheadTr").find("th").not(".dummy-th").not(":eq(0)"),
    		$($P.findn("exmptnVhclRow").content).find("td").not(".dummy-td").not(":eq(0)")
    	);
		ctrl.query.cellDefs = cellDefs;

    	ctrl.download();
	}

	$P.getGridTemplate = () => {
		var notFound = [$P.findn("exmptnVhclNotFound").innerHTML];
		var found = $P.findn("exmptnVhclRow").innerHTML;
		var replacer = (str, dataItem) => str
			.replace(/{onclick}/gi, "pageObject['${pageName}'].clickExmptnVhclList('{DATA-INDEX}');")
        	.replace(/{ondblclick}/gi, "pageObject['${pageName}'].dblclickExmptnVhclList('{EXMPTN_VHCL_ID}');");

		return {
			found : found,
			notFound : notFound,
			replacer : replacer
		};
	}

	$P.renderExmptnVhclList = (total, listLength, trs, option) => {

		let noMore = (listLength >= total);
		var initScroll = (ctrl.query.pageNum < 2);
		if (option != null && option.reloaded){
			initScroll = false;
		}

		$P.findn("table-responsive").changeContent(trs, initScroll, noMore);

		//보안모드
	    fn_securityModeToggle($("#securityMode--top").is(":checked"));
	}

	$P.clickExmptnVhclList = (dataIndex) => {
		if (dataIndex == ""){
			$P.$findn("btnOpenDelRsn").prop("disabled", true);
			$P.$findn("btnHistory").prop("disabled", true);
			return;
		}

		if (ctrl.dataset.getData(dataIndex)["DEL_YN"] == "N"){
			$P.$findn("btnOpenDelRsn").prop("disabled", false);
		} else {
			$P.$findn("btnOpenDelRsn").prop("disabled", true);
		}
		$P.$findn("btnHistory").prop("disabled", false);

		$P.$findn("exmptnVhclTbody").setCurrentRow(dataIndex);

		Apply.toDataset.current(ctrl.dataset, dataIndex);
	}

	$P.dblclickExmptnVhclList = (dataKey) => {
		if (!dataKey) return;

		let dataItem = ctrl.dataset.getDataset("item").filter(item => item.data.EXMPTN_VHCL_ID == dataKey)[0];
		var data = dataItem.data;
		if (data.DEL_YN == "Y"){
			dialog.alert({
				content : "삭제된 자료입니다.",
				init : function() {
					AppSupport.focusClose();
				}
			});
			return;
		}
		$P.getInfo({"exmptnVhclId" : dataKey});
	}

	$P.getInfo = (param) => {
		ajax.get({
			url : ctrl.urls.getInfo,
			data: param,
			success:(resp) => {
				let dialogName = "exmptnvhclDialog";
				let dialogId = dialogName+"-"+uuid();

				dialog.open({
					id: dialogId,
					title: "면제차량 수정",
					content:resp,
					size: "lg",
					init:() => {
						$("#"+dialogId).attr("name", dialogName);
						$("#"+dialogId).attr("data-ref-doctx","${pageName}");

						var parentRes = new Object();
						var childReq = pageObject.childReq.pop();

						for(var reqKey in childReq) {
						    if ($P.provide[reqKey]){
						    	parentRes[reqKey] = $P.provide[reqKey];
						    } else {
						    	parentRes[reqKey] = function(){};
						    }
						}

						pageObject.parentRes.push(parentRes);
					}
				});
			}
		});
	};

	$P.newInfo = () => {
		ajax.get({
			url : ctrl.urls.newInfo,
			data: {},
			success:(resp) => {
				let dialogName = "exmptnvhclDialog";
				let dialogId = dialogName+"-"+uuid();

				dialog.open({
					id: dialogId,
					title: "면제차량 등록",
					content:resp,
					size: "lg",
					init:() => {
						$("#"+dialogId).attr("name", dialogName);
						$("#"+dialogId).attr("data-ref-doctx","${pageName}");

						var parentRes = new Object();
						var childReq = pageObject.childReq.pop();

						for(var reqKey in childReq) {
						    if ($P.provide[reqKey]){
						    	parentRes[reqKey] = $P.provide[reqKey];
						    } else {
						    	parentRes[reqKey] = function(){};
						    }
						}

						pageObject.parentRes.push(parentRes);
					}
				});
			}
		});
	};

	$P.fnOpenDelRsnDialog = () => {

		fetch(wctx.url("/resources/html/inputRsnDialog.html"))
        .then(function(resp) { return resp.text(); })
        .then(function(template) {
			let dialogName = "inputDelRsnDialog";
			let dialogId = dialogName + "-" + uuid();
            dialog.open({
                   id: dialogId
                 , title: "삭제 사유 입력"
                 , size: "lg"
                 , content: template
                 , init: () => {
					$("#"+dialogId).attr("name", dialogName);
					$("#"+dialogId).attr("data-ref-doctx","${pageName}");

					AppSupport.setDialogZindex();
				 }
                 , onOK: () => {

                	 $P.fnRemove($("#reason").val());
                 }
            });
        });

	}

	$P.fnRemove = (reason) => {
		var dataKey = ctrl.dataset.getCurrent()["EXMPTN_VHCL_ID"];
		ajax.get({
			url : ctrl.urls.remove,
			data : {
				"exmptnVhclId" : dataKey,
				"delRsn" : reason
			},
			success : (resp) => {
				if (resp.saved){
					$P.refreshExmptnVhclList();
				}
			}
		});
	};

	$P.fnOpenHistory = () => {
		var dataKey = ctrl.dataset.getCurrent()["EXMPTN_VHCL_ID"];

		ajax.get({
			url : wctx.url("/crdn/crdn08/030/list.do"),
			data: { "exmptnVhclId" : dataKey },
			success:(resp) => {
				let dialogName = "exmptnvhclHistoryDialog";
				let dialogId = dialogName+"-"+uuid();

				dialog.open({
					id: dialogId,
					title: "면제차량 이력",
					content : resp,
					size: "xxl",
					init:() => {

					}
				});
			}
		});
	}

	$P.provide = {
		"refreshList" : function(){
    		$P.refreshExmptnVhclList();
    	}
	}

	/**************************************************************************
	* element.on
	**************************************************************************/
	$P.$findn("btnReset").on('click', () => $P.fnReset());
	$P.$findn("btnSearch").on("click", () => $P.searchExmptnVhclList());
	$P.$findn("btnExcel").on('click', () => $P.fnExcelDown());

	$P.$findn("btnCreate").on('click', () => { $P.newInfo(); });
	$P.$findn("btnOpenDelRsn").on('click', () => { $P.fnOpenDelRsnDialog(); });
	$P.$findn("btnHistory").on('click', () => { $P.fnOpenHistory(); });

	Componentization.fnMakeScrollableTable($P.findn("table-responsive"), $P.scrollExmptnVhclList);
	Componentization.fnMakeResizableTable($P.findn("table-responsive"));

    /**************************************************************************
	* 초기화
	**************************************************************************/
    AppSupport.initDatepicker($P.findn("frmSearch")); //달력 초기화

	$P.fnReset();
	//보안모드
    fn_securityModeToggle($("#securityMode--top").is(":checked"));
});

</script>