<%@ 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="schCvlcptRcptYmdFrom--${pageName}" name="schCvlcptRcptYmdFrom" 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="schCvlcptRcptYmdTo--${pageName}" name="schCvlcptRcptYmdTo" 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">
									<button type="button" onclick="$('#cvlcptPrcsPicNm--${pageName}').val('${currentUserName}');">담당자명 지정</button>
									<input type="text" id="cvlcptPrcsPicNm--${pageName}" name="cvlcptPrcsPicNm" class="form-control"/>
		                        </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">
		                        	<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>
				        </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="btnOpenCvlcptOrgnl--${pageName}"
				            	class="btn btn-primary" title="민원원본보기">민원원본보기</button>
				            	<button type="button" id="btnDelete--${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="crdnThead--${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 onclick="searchFromGridTitle('CVLCPT_RCPT_NO',this.innerText,'match','part');"
											style="min-width: 80px;">접수번호</th>
											<th onclick="searchFromGridTitle('CVLCPT_LIST_NO',this.innerText,'match','part');"
											style="min-width: 80px;">목록번호</th>
											<th onclick="searchFromGridTitle('CRDN_REG_SE_CD',this.innerText,'codeValue','FIM026');"
											style="min-width: 80px;">등록구분</th>
											<th onclick="searchFromGridTitle('CVLCPT_APLCNT_NM',this.innerText,'match','part');"
											style="min-width: 80px;">신고자</th>
											<th onclick="searchFromGridTitle('CVLCPT_PRCS_PIC_NM',this.innerText,'match','part');"
											style="min-width: 80px;">담당자</th>
											<th onclick="searchFromGridTitle('CVLCPT_PRCS_PIC_TELNO',this.innerText,'match','part');"
											style="min-width: 80px;">담당자전화번호</th>
											<th onclick="searchFromGridTitle('CVLCPT_RCPT_YMD',this.innerText,'ymd');"
											style="min-width: 80px;">접수일자</th>
											<th onclick="searchFromGridTitle('CVLCPT_PRCS_PRNMNT_DT',this.innerText,'ymd');"
											style="min-width: 80px;">처리기한</th>
											<th onclick="searchFromGridTitle('CRDN_YMD','위반일자','ymd');"
											style="min-width: 80px;">위반일시</th>
											<th onclick="searchFromGridTitle('VLTN_ARTCL',this.innerText);"
											style="min-width: 80px;">위반내용</th>
											<th onclick="searchFromGridTitle('VHRNO',this.innerText,'match','part');"
											style="min-width: 80px;">차량번호</th>
											<th onclick="searchFromGridTitle('ATCH_FILE_CNT',this.innerText,'match','perfect');"
											style="min-width: 80px;">사진건수</th>
											<th onclick="searchFromGridTitle('LEVY_EXCL_RSN_CD',this.innerText,'codeValue','FIM022');"
											style="min-width: 80px;">서손/계고사유</th>
											<th onclick="searchFromGridTitle('ETC_CN',this.innerText,'match','part');"
											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">{CVLCPT_RCPT_NO}</td>
											<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CVLCPT_LIST_NO}</td>
											<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CRDN_REG_SE_CD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CVLCPT_APLCNT_NM}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CVLCPT_PRCS_PIC_NM}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CVLCPT_PRCS_PIC_TELNO}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CVLCPT_RCPT_YMD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CVLCPT_PRCS_PRNMNT_DT}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{CRDN_YMD_TM}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{VLTN_ARTCL}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{VHRNO}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{ATCH_FILE_CNT}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{LEVY_EXCL_RSN_CD}</td>
				                    		<td onclick="{onclick}" ondblclick="{ondblclick}" class="text-center">{ETC_CN}</td>
				                    	</tr>
									</template>
									<template id="crdnNotFound--${pageName}">
										<tr>
											<td valign="top" colspan="15" 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 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>


<script>

/**************************************************************************
 * Global Variable
 **************************************************************************/
var FIM022 = new CommonCodes(${FIM022});
var FIM026 = new CommonCodes(${FIM026});

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.crdnControl = new DatasetControl({
	    urls : { load : "", getInfo : "", remove : "" },
	    dataGetter : obj => obj["List"], appendData:true,
	    keymapper : info => info ? info.CRDN_ID : "",
	    formats : {
	    	CRDN_REG_SE_CD 			: FIM026,
	    	CVLCPT_RCPT_YMD 		: dateFormat,
	    	CVLCPT_PRCS_PRNMNT_DT 	: datetimeFormat,
	    	CRDN_YMD_TM 			: datetimeFormat
		}
	});
	$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;
		}

		if($P.crdnControl.beforeCurrent != null){
			var beforeCurrentKey = $P.crdnControl.beforeCurrent.key;
			var beforeCurrentIndex = $P.crdnControl.beforeCurrent.index;
			$P.crdnControl.beforeCurrent = null;

			if(!$P.crdnControl.dataset.empty){
				var info = $P.crdnControl.dataset.getData(beforeCurrentKey);

				if(info != null){
					$P.crdnControl.dataset.setCurrent(beforeCurrentKey,true);
					return;
				}

				if(beforeCurrentIndex > ($P.crdnControl.dataset.length - 1)){
					info = $P.crdnControl.dataset.getDataset()[$P.crdnControl.dataset.length - 1];
				} else {
					info = $P.crdnControl.dataset.getDataset()[beforeCurrentIndex];
				}

				$P.crdnControl.dataset.setCurrent(info["CRDN_ID"],true);
				return;
			}
		}

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

	$P.crdnControl.onRemove = (selected, resp) => {
		if (resp.saved){
			$P.toast.show();
			$P.refreshCrdnList();
		}
	}

	/**************************************************************************
	 * 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("동적 검색");
		$('#schCvlcptRcptYmdFrom--${pageName}').datepicker('setDate', DateUtil.getDateDay(-5475).date);
	    $('#schCvlcptRcptYmdTo--${pageName}').datepicker('setDate', new Date());

		$P.crdnControl.setData([]);
	}

	$P.fnResetAndChangeBiz = (taskSeCd) => {
		$P.fnReset();
		$P.crdnControl.urls.load = wctx.url("/"+taskSeCd+"/cvlc/cvlc03/010/list.do");
		$P.crdnControl.urls.getInfo = wctx.url("/"+taskSeCd+"/sprt/sprt02/010/main.do");
		$P.crdnControl.urls.remove = wctx.url("/"+taskSeCd+"/cvlc/cvlc01/010/remove.do");
	}

	$P.refreshCrdnList = () => {
		$P.crdnControl.untilPageNum = $P.crdnControl.query.pageNum;
		$P.crdnControl.query.fetchSize = $P.crdnControl.defaultFetchSize * $P.crdnControl.query.pageNum;
		$P.crdnControl.beforeCurrent = {
			key : $P.crdnControl.getCurrent()["CRDN_ID"],
			index : $P.crdnControl.getCurrent()["ROW_NUM"] - 1
		};
	    $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 == ""){

			if(auto){
				$("label[for='table-responsive--${pageName}']").trigger("refreshEnd");
			}
			return;
		}

		$("#crdnTbody--${pageName}").setCurrentRow(dataKey);

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

	$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 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, "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;
	}



	$P.fnRemove = () => {

		var cur = $P.crdnControl.getCurrent();
		if(cur == null){
			return;
		}

		var curKey = cur["CRDN_ID"];
		$P.crdnControl.select(curKey,true);

		$P.crdnControl.remove();
	}



	$P.fnOpenCvlcptOrgnl = () => {
		var cur = $P.crdnControl.getCurrent();
		if(cur == null){
			return;
		}

		var taskSeCd = $("#frmSearch--${pageName} input[name='taskSeCd']:checked").val();

		var dialogId = "cvlcptOrgnlDialog--${pageName}";
		ajax.get({
			url : wctx.url("/"+taskSeCd+"/cvlc/cvlc01/050/info.do"),
			data : { crdnId : cur["CRDN_ID"] },
			success : resp => {
				dialog.open({
					id : dialogId,
					title : "민원내역 원본",
					content : resp,
					size : "xl",
					init : () => {
						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.provide = {
		"getCountStatus" : function(currentKey){
			var ds = $P.crdnControl.dataset.getDataset();
    		var index = ds.findIndex(item => item.CRDN_ID == currentKey);
    		return (index+1) + " of " + ds.length;
    	},
		"getNextKey" : function(currentKey){
    		var ds = $P.crdnControl.dataset.getDataset();
    		var index = ds.findIndex(item => item.CRDN_ID == currentKey);
    		if(ds.length > index+1){
    			return ds[index+1]["CRDN_ID"];
    		} else {
    			return "";
    		}
    	},
    	"getPrevKey" : function(currentKey){
			var ds = $P.crdnControl.dataset.getDataset();
    		var index = ds.findIndex(item => item.CRDN_ID == currentKey);
    		if(index != 0 && ds.length > 1){
    			return ds[index-1]["CRDN_ID"];
    		} else {
    			return "";
    		}
    	},
    	"selectRow" : function(currentKey){
    		$P.clickCrdnList(currentKey);
    	},
    	"refreshList" : function(){
    		$P.refreshCrdnList();
    	},
    	"hasData" : function(key){
    		if($P.crdnControl.dataset.getData(key) == null){
    			return false;
    		} else {
    			return true;
    		}
    	},
	};


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

    $("#btnDelete--${pageName}").on("click", () => $P.fnRemove());
    $("#btnOpenCvlcptOrgnl--${pageName}").on("click", () => $P.fnOpenCvlcptOrgnl());
	/**************************************************************************
	 * 초기화
	 **************************************************************************/
  	//달력 초기화
    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>