<%@ 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="schCrdnYmdFrom--${pageName}" name="schCrdnYmdFrom" 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="schCrdnYmdTo--${pageName}" name="schCrdnYmdTo" 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 class="col-6">
		                            <label class="form-label fw-bold form-search-title">자료출처</label>
		                            <select id="crdnInptSeCd--${pageName}" name="crdnInptSeCd" class="form-select">
		                            	<option value="">전체</option>
		                            	<c:forEach items="${FIM003List}" var="item">
		                            		<option value="${item.code}">${item.value}</option>
		                            	</c:forEach>
		                            </select>
		                        </div>
		                        <div class="col-6">
		                            <label class="form-label fw-bold form-search-title">차량번호</label>
		                            <input type="text" id="vhrno--${pageName}" name="vhrno" class="form-control" />
		                        </div>
		                        <div class="col-6">
		                        	<select id="schDateOpt--${pageName}" name="schDateOpt" class="form-select">
		                                <option value="regDt">등록일자</option>
		                                <option value="mdfcnDt">수정일자</option>
		                            </select>
		                            <span class="form-search-linebox">
		                                <input type="text" id="schDateFrom--${pageName}" name="schDateFrom" 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="schDateTo--${pageName}" name="schDateTo" 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 class="col-6">
									<input type="hidden" id="by--${pageName}" name="by" />
									<input type="text" id="byOutput--${pageName}" class="form-control" readonly value="동적 검색" />
									<input type="hidden" id="mainOption--${pageName}" name="mainOption" />
									<input type="hidden" id="subOption--${pageName}" name="subOption" />
									<input type="text" id="term--${pageName}" name="term" class="form-control" />
		                        	<span class="flr">
		                                <button type="button" class="btn btn-open-detail"
		                                	data-bs-toggle="collapse" data-bs-target="#searchDetail--${pageName}">
		                                    <i class="bx bx-chevron-down"></i>
		                                    상세검색
		                                </button>
		                            </span>
		                        </div>
		                    </div>
				        </div>
				        <div id="searchDetail--${pageName}" class="container-search container-search-detail collapse">
				            <div class="row">
					            <div class="col-6">
					                <label class="form-label fw-bold form-search-title">자료상태</label>
		                            <select id="crdnSttsCd--${pageName}" name="crdnSttsCd" class="form-select">
		                            	<option value="">전체</option>
		                            	<c:forEach items="${FIM010List}" var="item">
		                            		<option value="${item.code}">${item.value}</option>
		                            	</c:forEach>
		                            </select>
					            </div>
					            <div class="col-6">

		                        </div>
					        </div>
					        <div class="row">
					        	<div slot="search" class="col-6">
					        		<template class="pvs dpv eca">
							            <slot>
							                <label class="form-label fw-bold form-search-title">견인</label>
							                <label class="form-label">
				                            	<input type="radio" name="towngYn" value="" class="form-check-input" checked />전체
				                            </label>
							                <label class="form-label">
				                            	<input type="radio" name="towngYn" value="Y" class="form-check-input" />예
				                            </label>
				                            <label class="form-label">
				                            	<input type="radio" name="towngYn" value="N" class="form-check-input" />아니오
				                            </label>
							            </slot>
								    </template>
					        	</div>
					        </div>
				        </div>
				    </form>

				    <div>
				        <div 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="" class="btn btn-primary" title="업무처리1">업무 처리1</button>
				            	<button type="button" id="" class="btn btn-primary" title="업무처리2">업무 처리2</button>
				            </span>
				        </div>
				    </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:500px;overflow-y: scroll;">
								<table id="DataTables_Table_0--${pageName}"
									class="datatables-ajax table table-bordered dataTable no-footer">
									<thead>
										<tr id="crdnThead--${pageName}"
										data-by="by--${pageName}" data-by-output="byOutput--${pageName}"
										data-main-option="mainOption--${pageName}" data-sub-option="subOption--${pageName}">
										</tr>
									</thead>
				                    <tbody id="crdnTbody--${pageName}">
				                    </tbody>

				                    <template id="crdnCols--${pageName}">
										<th style="min-width: 80px;" class="cmn">No.</th>
										<th onclick="searchFromGridTitle('CRDN_INPT_SE_CD',this.innerText,'codeValue','FIM003');"
										style="min-width: 80px;" class="pvs bpv dpv eca">자료출처</th>
										<th onclick="searchFromGridTitle('VHRNO',this.innerText,'match','part');"
										style="min-width: 80px;" class="cmn">차량번호</th>
										<th onclick="searchFromGridTitle('CRDN_YMD','위반일자','match','perfect');"
										style="min-width: 80px;" class="cmn">위반일시</th>
										<th onclick="searchFromGridTitle('CRDN_PLC',this.innerText,'match','part');"
										style="min-width: 80px;" class="cmn">위반장소</th>
										<th style="min-width: 80px;" class="cmn">체납액</th>
										<th onclick="searchFromGridTitle('ATCH_FILE_CNT',this.innerText,'match','perfect');"
										style="min-width: 80px;" class="cmn">사진건수</th>
										<th onclick="searchFromGridTitle('CRDN_SN',this.innerText,'match','perfect');"
										style="min-width: 80px;" class="pvs dpv eca">스티커번호</th>
										<th onclick="searchFromGridTitle('PARKNG_PSBLTY_RSLT_CD',this.innerText,'codeValue','FIM034');"
										style="min-width: 80px;" class="dpv">장애차량확인</th>
										<th onclick="searchFromGridTitle('CRDN_STTS_CD',this.innerText,'codeValue','FIM010');"
										style="min-width: 80px;" class="cmn">처리상태</th>
										<th onclick="searchFromGridTitle('LEVY_EXCL_RSN_CD',this.innerText,'codeValue','FIM022');"
										style="min-width: 80px;" class="cmn">제외사유</th>
										<th onclick="searchFromGridTitle('LEVY_EXCL_YMD',this.innerText,'ymd','');"
										style="min-width: 80px;" class="cmn">제외처리일자</th>
										<th onclick="searchFromGridTitle('LEVY_EXCL_ETC_CN',this.innerText,'match','part');"
										style="min-width: 80px;" class="cmn">제외내역</th>
				                    </template>
									<template id="crdnRow--${pageName}">
										<tr data-key="{CRDN_ID}">
											<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-end cmn">{ROW_NUM}</td>
											<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{CRDN_INPT_SE_CD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{VHRNO}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{CRDN_YMD_TM}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{CRDN_PLC}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-end cmn">{체납액}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{ATCH_FILE_CNT}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center pvs dpv eca">{CRDN_SN}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center dpv">{PARKNG_PSBLTY_RSLT_CD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{CRDN_STTS_CD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{LEVY_EXCL_RSN_CD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{LEVY_EXCL_YMD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center cmn">{LEVY_EXCL_ETC_CN}</td>
			                    		</tr>
									</template>
									<template id="crdnNotFound--${pageName}">
										<tr class="dpv">
											<td valign="top" colspan="14" class="dataTables_empty text-center">단속 정보를 찾지 못했습니다.</td>
										</tr>
										<tr class="eca">
											<td valign="top" colspan="14" class="dataTables_empty text-center">단속 정보를 찾지 못했습니다.</td>
										</tr>
										<tr class="pvs">
											<td valign="top" colspan="14" class="dataTables_empty text-center">단속 정보를 찾지 못했습니다.</td>
										</tr>
										<tr class="bpv">
											<td valign="top" colspan="14" class="dataTables_empty text-center">단속 정보를 찾지 못했습니다.</td>
										</tr>
										<tr class="tpv">
											<td valign="top" colspan="14" 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 FIM002 = new CommonCodes(${FIM002});
var FIM003 = new CommonCodes(${FIM003});
var FIM010 = new CommonCodes(${FIM010});
var FIM022 = new CommonCodes(${FIM022});
var FIM026 = new CommonCodes(${FIM026});
var FIM034 = new CommonCodes(${FIM034});
pageObject["${pageName}"] = {};


$(document).ready(function(){

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

	/**************************************************************************
	 * DatasetControl
	 **************************************************************************/
	$P.crdnControl = new DatasetControl({
	    urls : {
	        load : "",
	        getInfo : ""
	    },
	    dataGetter : obj => obj["List"], appendData:true,
	    keymapper : info => info ? info.CRDN_ID : "",
	    formats: {
	    	CRDN_INPT_SE_CD: FIM003,
	    	CRDN_YMD_TM : datetimeFormat,
	    	REG_DT : datetimeFormat,
	    	MDFCN_DT : datetimeFormat,
	    	CVLCPT_PRCS_PRNMNT_DT : dateFormat,
	    	CVLCPT_RCPT_YMD : dateFormat,

	    	RCVMT_AMT : numberFormat,

	    	CRDN_SE_CD: FIM002,
	    	CRDN_STTS_CD 	: FIM010,
	    	CRDN_REG_SE_CD: FIM026,
	    	LEVY_EXCL_YMD : dateFormat,
	    	LEVY_EXCL_RSN_CD : FIM022,
	    	PARKNG_PSBLTY_RSLT_CD : FIM034
		}
	});
	$P.crdnControl.defaultFetchSize = FETCH_XS;
	$P.crdnControl.untilPageNum = 0;
	$P.crdnControl.beforeCurrent = null;
	$P.crdnControl.tableRenderComplete = false;

	/**************************************************************************
	 * 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 = () => {
		var searchForm = $("#frmSearch--${pageName}");
		searchForm.find("input[type='radio']").not("[name='taskSeCd']").prop("checked", false);
		searchForm.find("input[type='checkbox']").prop("checked", false);
		searchForm.find("input[type='text']").val("");
		searchForm.find("input[type='hidden']").val("");
		searchForm.find("select").each(function(){ $(this).find("option:eq(0)").prop("selected", true); });

		$("#byOutput--${pageName}").val("동적 검색");
		$('#schCrdnYmdFrom--${pageName}').datepicker('setDate', DateUtil.getDateDay(-5475).date);
	    $('#schCrdnYmdTo--${pageName}').datepicker('setDate', new Date());
		$P.crdnControl.setData([]);
	}

	$P.fnResetAndChangeBiz = (taskSeCd) => {
		$P.fnReset();
		$P.crdnControl.urls.load = wctx.url("/"+taskSeCd+"/crdn/crdn06/010/list.do");
		$P.crdnControl.urls.getInfo = wctx.url("/"+taskSeCd+"/sprt/sprt02/010/main.do");

		var clsForTask = taskSeCd.toLowerCase();

		//업무별 조회조건
		renderForTask("frmSearch--${pageName}", clsForTask);

		//업무별 그리드
		var colsContent = document.getElementById("crdnCols--${pageName}").content;
		var cols = $(colsContent).find("."+clsForTask+",.cmn");
		var colsStr = "";
		cols.each(function(){
			colsStr += this.outerHTML;
		});
		$("#crdnThead--${pageName}").html(colsStr);
	}

    $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.dblclickCrdnList = (dataKey) => {
		let params = {
			  callControlName : "pageObject['${pageName}'].crdnControl"
			, crdnId : dataKey
		}

		ajax.get({
			url : $P.crdnControl.urls.getInfo,
			data : params,
			success : resp => {

				dialog.open({
					id : "totalDialog--${pageName}",
					title : "개별총정보", size : "xxl", content : resp,
					init : () => {}
				});

			}
		});

	}

	$P.renderCrdnList = (total) => {

	    var crdnList = $P.crdnControl.dataset;
		var empty = crdnList.empty;
		var clsForTask = $("#frmSearch--${pageName} [name='taskSeCd']:checked").val().toLowerCase();
		var notFound = [document.getElementById("crdnNotFound--${pageName}").content.querySelector("."+clsForTask+",.cmn").outerHTML];
		var foundContent = document.getElementById("crdnRow--${pageName}").content;
		var foundTr = $(foundContent).find("tr")[0].cloneNode(false);
		var foundTds = $(foundContent).find("."+clsForTask+",.cmn");

		foundTds.each(function(){
			foundTr.appendChild(this.cloneNode(true));
		});

		var found = foundTr.outerHTML;

		var replacer = (str, dataItem) => str
			.replace(/{onclick}/gi, "pageObject['${pageName}'].clickCrdnList('" + dataItem.getValue("CRDN_ID") + "');")
			.replace(/{ondblclick}/gi, "pageObject['${pageName}'].dblclickCrdnList('" + dataItem.getValue("CRDN_ID") + "');");
		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());
    $("#table-responsive--${pageName}").scroll(function(){ $P.scrollEnd(this); });

	/**************************************************************************
	 * 초기화
	 **************************************************************************/
    initDatepicker("frmSearch--${pageName}"); //달력 초기화
    initDetailSearchButton("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>
