<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" session="false"%>
<%@ include file="/WEB-INF/jsp/include/taglib.jsp"%>
<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>
									<input type="text" id="regDt--${pageName}" name="regDt" class="form-control form-date" data-fmt-type="day"
									title="금일" disabled="disabled" />
		                        </div>
		                    </div>
				        </div>
				    </form>
					<div>
						<span class="container-page-btn">
							<div class="d-flex flex-row justify-content-between">
								<label id="crdnPaging--${pageName}PagingInfo" class="dataTables_info" role="status" aria-live="polite"></label>
				                 <ul id="crdnPaging--${pageName}" class="pagination pagination-primary">
				                 </ul>
							</div>
							<span class="container-window-btn-right">
								<button type="button" id="btnInsertByFile--${pageName}" class="btn btn-primary" title="단속 파일 등록">단속 파일 등록</button>
					         	<button type="button" id="btnInsertByHand--${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>
										<tr id="crdnTheadTr--${pageName}">
											<th style="min-width: 50px;">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: 200px;">위반장소</th>
											<th style="min-width: 80px;">위반내용</th>
										</tr>
				                    </thead>
				                    <tbody id="crdnTbody--${pageName}"></tbody>
									<template id="crdnRow--${pageName}">
			                    		<tr data-key="{CRDN_ID}">
			                    			<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-end">{ROW_NUM}</td>
			                    			<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CRDN_REG_SE_CD}</td>
			                    			<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CRDN_INPT_SE_CD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CRDN_YMD_TM}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{VHRNO}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-start">{CRDN_PLC}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-start">{VLTN_ARTCL}</td>
				                    	</tr>
			                    	</template>
			                    	<template id="crdnNotFound--${pageName}">
			                    		<tr>
			                    			<td valign="top" colspan="7" class="dataTables_empty text-center">단속 정보를 찾지 못했습니다.</td>
			                    		</tr>
			                    	</template>
								</table>
							</div>
						</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
 **************************************************************************/
var FIM003 = new CommonCodes(${FIM003});
var FIM026 = new CommonCodes(${FIM026});
 
pageObject["${pageName}"] = {};


$(document).ready(function(){

	var $P = pageObject["${pageName}"];
	
	/**************************************************************************
	 * DatasetControl
	 **************************************************************************/
	$P.crdnControl = new DatasetControl({
	    urls : { load : "" },
	    dataGetter : obj => obj["List"], appendData:true,
	    keymapper : info => info ? info.CRDN_ID : "",
	    formats: {
			CRDN_INPT_SE_CD : FIM003,
			CRDN_REG_SE_CD 	: FIM026,
			CRDN_YMD_TM 	: datetimeFormat
		}
	});
	$P.crdnControl.defaultFetchSize = FETCH_XS;
	$P.crdnControl.untilPageNum = 0;
	$P.crdnControl.beforeCurrent = null;
	$P.crdnControl.tableRenderComplete = false;
	
	$P.crdnControl.urls.newInfoByFile = "";
	$P.crdnControl.urls.newInfoByHand = "";

	$P.crdnControl.newInfo = (type) => {
		var url = "";
		if(type == "file") url = $P.crdnControl.urls.newInfoByFile;
		if(type == "hand") url = $P.crdnControl.urls.newInfoByHand;

		var dialogId = "";
		if(type == "file") dialogId = "filedialog";
		if(type == "hand") dialogId = "manualdialog";

		var title = "";
		if(type == "file") title = "단속파일 등록";
		if(type == "hand") title = "단속자료 수기 등록";


		ajax.get({
			url : url,
			data: {},
			success:resp => {
				dialog.open({
					id: dialogId,
					title: title,
					content:resp,
					size: "xxl",
					init:() => {}
				});
			}
		});
	};

	/**************************************************************************
	 * DatasetControl.on
	 **************************************************************************/
	$P.crdnControl.onDatasetChange = (obj) => {
		
		$P.renderCrdnList(obj["Total"]);

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

	$P.crdnControl.onCurrentChange = (item) => {
		
		if(!$P.crdnControl.tableRenderComplete){
			return;
		}
		
		$P.crdnControl.tableRenderComplete = false;
		if(!item){
			$P.clickCrdnList("", true);
		} else {
			$P.clickCrdnList($P.crdnControl.getCurrent()["CRDN_ID"], true);
		}
	}

	/**************************************************************************
	 * pageObject.function
	 **************************************************************************/
	$P.fnReset = () => {
		$("#regDt--${pageName}").datepicker('setDate', new Date());
		$P.crdnControl.setData([]);
	}
	
	$P.fnResetAndChangeBiz = (taskSeCd) => {
		$P.fnReset();
		$P.crdnControl.urls.load = wctx.url("/"+taskSeCd+"/crdn/crdn05/010/list.do");
		$P.crdnControl.urls.newInfoByFile = wctx.url("/"+taskSeCd+"/crdn/crdn05/020/info.do");
		$P.crdnControl.urls.newInfoByHand = wctx.url("/"+taskSeCd+"/crdn/crdn05/030/info.do");
		
		switch(taskSeCd){
			case "PVS" : 
			case "BPV" :
				$("#btnInsertByFile--${pageName}").show();
				break;
			case "DPV" : 
			case "ECA" :
			case "TPV" :
				$("#btnInsertByFile--${pageName}").hide();
				break;
		}
	}
	
    $P.refreshCrdnList = () => {
        $P.crdnControl.untilPageNum = $P.crdnControl.query.pageNum;
        $P.crdnControl.query.fetchSize = $P.crdnControl.defaultFetchSize * $P.crdnControl.query.pageNum;
        $P.crdnControl.load(1);
    }
    
	$P.searchCrdnList = () => {
		$P.crdnControl.query = $P.getParams();
	    $P.crdnControl.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.scrollCrdnList();
    	}
	}

	$P.scrollCrdnList = () => {
		$P.crdnControl.load($P.crdnControl.query.pageNum + 1);
	}

	$P.clickCrdnList = (dataKey, auto) => {
		if(dataKey == ""){
			return;
		}
		$("#crdnTbody--${pageName}").setCurrentRow(dataKey);
		
		if(!auto) {
			$P.crdnControl.setCurrent(dataKey);
		}
	}

	$P.renderCrdnList = (total) => {

	    var crdnList = $P.crdnControl.dataset;
		var empty = crdnList.empty;
		var notFound = [document.getElementById("crdnNotFound--${pageName}").innerHTML];
		var found = document.getElementById("crdnRow--${pageName}").innerHTML;
		var replacer = (str, dataItem) => str
			.replace(/{onclick}/gi, "pageObject['${pageName}'].clickCrdnList('" + dataItem.getValue("CRDN_ID") + "');")
        	.replace(/{ondblclick}/gi, "");

		var trs = empty ? notFound : crdnList.inStrings(found,replacer);

		$("#crdnTbody--${pageName}").html(trs.join());

		//보안모드
	    fn_securityModeToggle($("#securityMode--top").is(":checked"));
		
	    if(total == crdnList.length){
			$("#table-responsive--${pageName}").attr("data-scroll-status", "complete");
		} else {
			$("#table-responsive--${pageName}").removeAttr("data-scroll-status");
		}
	    
	    if($P.crdnControl.untilPageNum != 0){
			$P.crdnControl.query.fetchSize = $P.crdnControl.defaultFetchSize;
			$P.crdnControl.query.pageNum = $P.crdnControl.untilPageNum;
			$P.crdnControl.untilPageNum = 0;
		}
	}

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

	/**************************************************************************
	 * element.on
	 **************************************************************************/
    $('#btnReset--${pageName}').on('click', () => $P.fnReset());
	$("#btnSearch--${pageName}").on("click", () => $P.searchCrdnList());
	$("#btnInsertByFile--${pageName}").on('click', () => { $P.crdnControl.newInfo("file"); });
	$("#btnInsertByHand--${pageName}").on('click', () => { $P.crdnControl.newInfo("hand"); });
    $("#table-responsive--${pageName}").scroll(function(){ $P.scrollEnd(this); });

    /**************************************************************************
	 * 초기화
	 **************************************************************************/
    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);
	//보안모드
    fn_securityModeToggle($("#securityMode--top").is(":checked"));
});
</script>