<%@ 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">
                        	<span class="form-label fw-bold form-search-title w-px-120 text-end">단속일자</span>
                        	<span class="form-search-linebox">
                                <input type="text" name="schCrdnYmdFrom"
                                class="form-control form-date"
                                	data-fmt-type="day"   title="시작 날짜 선택" />
                                <button type="button" class="bx bx-lg bx-calendar bg-white"></button>
                                ~
                                <input type="text" name="schCrdnYmdTo"
                                class="form-control form-date"
                                	data-fmt-type="day" title="종료 날짜 선택">
                                <button type="button" class="bx bx-lg bx-calendar bg-white"></button>
                            </span>
                        </div>
						<div class="col-6">
                        	<input type="hidden" name="by" />
							<input type="text" class="form-control fw-bold w-px-120 text-end" name="byOutput" value="동적 검색" readonly />
							<input type="hidden" name="mainOption" />
							<input type="hidden" name="subOption" />
							<input type="text" class="form-control w-px-400" name="term" autocomplete="off" />
						</div>
                    </div>
		        </div>
		    </form>
		    <div>
		        <span class="container-page-btn">
		        	<div class="d-flex flex-row justify-content-between">
						<span is="paging-info" name="crdnPagingInfo" class="dataTables_info"></span>
		                <ul name="crdnPaging" class="pagination pagination-primary"></ul>
					</div>
		            <span class="container-window-btn-right">
		                <button type="button" name="btnUpdateToConfirmData"
		                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="crdnTable" class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer" >
							<thead class="sticky-thead">
								<tr name="crdnTheadTr" data-search-target="[data-doctx='${pageName}']">
									<th style="width: 100px;">No.</th>
									<th onclick="FimsSupport.searchFromGridTitle('CRDN_INPT_SE_CD',this.innerText,'codeValue','FIM003');"
									style="width: 200px;">자료출처</th>
									<th onclick="FimsSupport.searchFromGridTitle('CRDN_YMD','위반일자','ymd','');"
									style="width: 200px;">위반일시</th>
									<th onclick="FimsSupport.searchFromGridTitle('VHRNO',this.innerText,'match','part');"
									style="width: 200px;">차량번호</th>
									<th onclick="FimsSupport.searchFromGridTitle('CRDN_STDG_NM',this.innerText,'match','perfect');"
									style="width: 200px;">법정동</th>
									<th
									style="width: 200px;"
									class="text-orange">잔액</th>
									<th onclick="FimsSupport.searchFromGridTitle('ATCH_FILE_CNT',this.innerText,'match','perfect');"
									style="width: 200px;">사진건수</th>
									<th onclick="FimsSupport.searchFromGridTitle('CRDN_SN',this.innerText,'match','perfect');"
									style="width: 200px;">발행번호</th>
									<th class="dummy-th"></th>
								</tr>
		                    </thead>
		                    <tbody name="crdnTbody">
							</tbody>
							<template is="curly-brackets" name="crdnRow">
								<tr data-index="DATA-INDEX">
									<td onclick ondblclick class="text-end">ROW_NUM</td>
		                    		<td onclick ondblclick class="text-center">CRDN_INPT_SE_NM</td>
		                    		<td onclick ondblclick class="text-center">CRDN_YMD_TM</td>
		                    		<td onclick ondblclick class="text-center">VHRNO</td>
		                    		<td onclick ondblclick class="text-center">CRDN_STDG_NM</td>
		                    		<td onclick ondblclick class="text-end">BLNC</td>
		                    		<td onclick ondblclick class="text-center">ATCH_FILE_CNT</td>
		                    		<td onclick ondblclick class="text-start">CRDN_SN</td>
		                    		<td class="dummy-td"></td>
								</tr>
							</template>
							<template name="crdnNotFound">
								<tr>
	                    			<td valign="top" colspan="9" class="dataTables_empty text-center">
	                    			단속 정보를 찾지 못했습니다.
	                    			</td>
	                    		</tr>
							</template>
						</table>
					</div>
				</div>
		    </div>
		</div>
	</div>



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


<script>
LoadScript("crdn03010Script",wctx.url("/resources/js/fims/crdn/crdn03010.js?ver=${ver}"));

/**************************************************************************
 * Global Variable
 **************************************************************************/
var FIM003 = new CommonCodes(${FIM003});
var FIM010 = new CommonCodes(${FIM010});
pageObject["${pageName}"] = newDoctxFinder("${pageName}");


$(document).ready(function(){

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

	/**************************************************************************
	* DatasetControl, DatasetSupport, FormFields
	**************************************************************************/
	var ctrl = newCrdn03010Control($P);

	ctrl.defaultFetchSize = FETCH_XS;
	ctrl.query = { pageNum : 1, fetchSize : ctrl.defaultFetchSize };
	ctrl.beforeCurrent = null;

	ctrl.dataset.onDatasetChange = (obj, option) => {

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

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

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

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

	/**************************************************************************
	* pageObject.function
	**************************************************************************/
	$P.fnReset = () => {
		var searchForm = $P.$findn("frmSearch");
		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); });

		$P.$findn("byOutput").val("동적 검색");
		$P.$findn("schCrdnYmdFrom").datepicker('setDate', DateSupport.getAddDay(-5475));
		$P.$findn("schCrdnYmdTo").datepicker('setDate', TODAY());
	    ctrl.dataset.setData([]);
	}

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

		return data;
	}

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

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

	$P.refreshCrdnList = () => {

		ctrl.beforeCurrent = {
			primaryKey : ctrl.dataset.getCurrent()["CRDN_ID"],
			arrayIndex : ctrl.dataset.getCurrent()["ROW_NUM"] - 1
        };

	    Apply.fromDatasetControl.reload(ctrl).then((resp)=>{
			Apply.toDataset.set(ctrl.dataset, resp);
			ctrl.dataset.onDatasetChange(resp, {reloaded : true});

			let todoCurrent = Apply.fromDataset.getTodoCurrent(ctrl.dataset, ctrl.beforeCurrent, "CRDN_ID");
			ctrl.beforeCurrent = null;
			if(todoCurrent != null){
				ctrl.dataset.setCurrent(todoCurrent.index, true);
			}

		});
	}

	$P.fnExcelDown = () => {

    	if(ctrl.dataset.empty){
    		alert("조회된 자료가 없습니다.");
    		return;
    	}

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

    	ctrl.download();
	}

	$P.getGridTemplate = () => {

		var notFound = [$P.findn("crdnNotFound").innerHTML];
		var found = $P.findn("crdnRow").innerHTML;
		var replacer = (str, dataItem) => str
        	.replace(/{onclick}/gi, "pageObject['${pageName}'].clickCrdnList('{DATA-INDEX}');")
    		.replace(/{ondblclick}/gi, "pageObject['${pageName}'].dblclickCrdnList('{CRDN_ID}');");

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

	$P.renderCrdnList = (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.clickCrdnList = (dataIndex) => {
		if(dataIndex == ""){
			return;
		}

		$P.$findn("crdnTbody").setCurrentRow(dataIndex);
		Apply.toDataset.current(ctrl.dataset, dataIndex);

	}

	$P.dblclickCrdnList = (dataKey) => {
		crdnTotalInfo({
			callPageName : "${pageName}",
			crdnId : dataKey
		});
	}
	$P.save = () => {

    	if(!ctrl.dataset.getCurrent()) {
    		dialog.alert({
				content : "선택된 자료가 없습니다.",
				init : function(){
					AppSupport.focusClose();
				}
			});
    		return;
    	};

    	dialog.alert({
			content : "현 자료를 장애차량 확인된 자료로 변경하시겠습니까?",
			init : function(){
				AppSupport.focusOK();
			},
			onOK : () => {
				var info = { 'crdnId' : ctrl.dataset.getCurrent()["CRDN_ID"] };
				ajax.post({
					url : ctrl.urls.update,
					data : info,
					success : (resp) => {
						$P.saveCallback(resp);
					}
				});
    		}
		});
    }

	$P.saveCallback = (resp) => {
		if (resp.saved) {
			dialog.alert({
				content : "저장됐습니다.",
				onClose : () => {
					$P.refreshCrdnList();
				}
			});
		}
	}

	/**************************************************************************
	* element.on
	**************************************************************************/
	$P.$findn("btnReset").on('click', () => $P.fnReset());
	$P.$findn("btnSearch").on('click', () => $P.searchCrdnList());
 	// 동적검색에서 엔터(Enter) 키를 누르면 검색한다.
	$P.$findn("term").onEnterPress($P.searchCrdnList);
	$P.$findn("btnExcel").on('click', () => $P.fnExcelDown());

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

    $P.$findn("btnUpdateToConfirmData").on('click', () => $P.save());

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

    $P.fnReset();

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

});

</script>