<%@ 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-12">
                            <span class="form-label fw-bold form-search-title w-px-120 text-end">업무구분</span>
                            <span class="form-search-linebox">
								<c:forEach items="${TaskListForSgg}" 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">
							<span class="form-label fw-bold form-search-title w-px-120 text-end">접수일자</span>
                        	<span class="form-search-linebox">
                                <input type="text" name="schCvlcptRcptYmdFrom"
                                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="schCvlcptRcptYmdTo"
                                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">
							<button type="button" class="w-px-120" onclick="pageObject.${pageName}.$findn('cvlcptPrcsPicNm').val('${currentUserName}');">
								담당자명 지정
							</button>
							<input type="text" name="cvlcptPrcsPicNm"
							class="form-control" />
                        </div>
	                     <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="schCvlcptPrcsPrnmntDtFrom"
                                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="schCvlcptPrcsPrnmntDtTo"
                                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" />
							<!-- 상세 검색조건 버튼 -->
							<span class="flr">
								<button type="button" class="btn btn-open-detail" data-bs-toggle="collapse"
								data-bs-target="[data-doctx='${pageName}'] [name='searchDetail']">
									<i class="bx bx-chevron-down"></i>
									상세검색
								</button>
							</span>
						</div>
                    </div>
		        </div>
		        <div name="searchDetail" class="container-search container-search-detail collapse">
		            <div class="row">
		            	<div class="col-6">
							<select class="form-select w-px-120 text-center" name="schRegDateOpt">
								<option value="regDt">등록일자</option>
								<option value="mdfcnDt">수정일자</option>
							</select>
							<span class="form-search-linebox">
								<input type="text" class="form-control form-date" name="schRegDateFrom"
                                	data-fmt-type="day" title="시작 날짜 선택" />
								<button type="button" class="bx bx-lg bx-calendar bg-white"></button>
                                ~
								<input type="text" class="form-control form-date" name="schRegDateTo"
                                	data-fmt-type="day" title="종료 날짜 선택">
								<button type="button" class="bx bx-lg 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">
						<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="btnOpenCvlcptOrgnl"
		            	class="btn btn-primary" title="민원원본보기">민원원본보기</button>
		            	<button type="button" name="btnDelete"
		            	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-500">
						<table name="crdnTable" class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer">
							<thead name="crdnThead" class="sticky-thead">
								<tr data-search-target="[data-doctx='${pageName}']">
									<th style="width: 80px;">No.</th>
									<th onclick="FimsSupport.searchFromGridTitle('CVLCPT_RCPT_NO',this.innerText,'match','part');"
									style="width: 160px;">접수번호</th>
									<th onclick="FimsSupport.searchFromGridTitle('CVLCPT_LIST_NO',this.innerText,'match','part');"
									style="width: 160px;">목록번호</th>
									<th onclick="FimsSupport.searchFromGridTitle('CRDN_REG_SE_CD',this.innerText,'codeValue','FIM026');"
									style="width: 160px;">등록구분</th>
									<th onclick="FimsSupport.searchFromGridTitle('CVLCPT_APLCNT_NM',this.innerText,'match','part');"
									style="width: 160px;">신고자</th>
									<th onclick="FimsSupport.searchFromGridTitle('CVLCPT_PRCS_PIC_NM',this.innerText,'match','part');"
									style="width: 160px;">담당자</th>
									<th onclick="FimsSupport.searchFromGridTitle('CVLCPT_PRCS_PIC_TELNO',this.innerText,'match','part');"
									style="width: 160px;">담당자전화번호</th>
									<th onclick="FimsSupport.searchFromGridTitle('CVLCPT_RCPT_YMD',this.innerText,'ymd');"
									style="width: 160px;">접수일자</th>
									<th onclick="FimsSupport.searchFromGridTitle('CVLCPT_PRCS_PRNMNT_DT',this.innerText,'ymd');"
									style="width: 180px;">처리기한</th>
									<th onclick="FimsSupport.searchFromGridTitle('CRDN_YMD','위반일자','ymd');"
									style="width: 180px;">위반일시</th>
									<th onclick="FimsSupport.searchFromGridTitle('VLTN_ARTCL',this.innerText);"
									style="width: 160px;">위반내용</th>
									<th onclick="FimsSupport.searchFromGridTitle('VHRNO',this.innerText,'match','part');"
									style="width: 160px;">차량번호</th>
									<th onclick="FimsSupport.searchFromGridTitle('ATCH_FILE_CNT',this.innerText,'match','perfect');"
									style="width: 160px;">사진건수</th>
									<th onclick="FimsSupport.searchFromGridTitle('LEVY_EXCL_RSN_CD',this.innerText,'codeValue','FIM022');"
									style="width: 160px;">서손/계도사유</th>
									<th onclick="FimsSupport.searchFromGridTitle('ETC_CN',this.innerText,'match','part');"
									style="width: 160px;">특기사항</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">CVLCPT_RCPT_NO</td>
									<td onclick ondblclick class="text-center">CVLCPT_LIST_NO</td>
									<td onclick ondblclick class="text-center">CRDN_REG_SE_NM</td>
		                    		<td onclick ondblclick class="text-center">CVLCPT_APLCNT_NM</td>
		                    		<td onclick ondblclick class="text-center">CVLCPT_PRCS_PIC_NM</td>
		                    		<td onclick ondblclick class="text-center">CVLCPT_PRCS_PIC_TELNO</td>
		                    		<td onclick ondblclick class="text-center">CVLCPT_RCPT_YMD</td>
		                    		<td onclick ondblclick class="text-center">CVLCPT_PRCS_PRNMNT_DT</td>
		                    		<td onclick ondblclick class="text-center">CRDN_YMD_TM</td>
		                    		<td onclick ondblclick class="text-center">VLTN_ARTCL</td>
		                    		<td onclick ondblclick class="text-center">VHRNO</td>
		                    		<td onclick ondblclick class="text-center">ATCH_FILE_CNT</td>
		                    		<td onclick ondblclick class="text-center">LEVY_EXCL_RSN_NM</td>
		                    		<td onclick ondblclick class="text-center">ETC_CN</td>
		                    		<td class="dummy-td"></td>
		                    	</tr>
							</template>
							<template name="crdnNotFound">
								<tr>
									<td valign="top" colspan="16" class="dataTables_empty text-center">
									민원 정보를 찾지 못했습니다.
									</td>
								</tr>
							</template>
						</table>
					</div>
				</div>
		    </div>
		    <div class="toast-container position-fixed bottom-0 end-0 p-3">
			  <div name="divToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
			    <div class="toast-body bg-black text-white">
			      삭제 되었습니다.
			    </div>
			  </div>
			</div>



		</div>
	</div>



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


<script>
LoadScript("cvlc03010Script",wctx.url("/resources/js/fims/cvlc/cvlc03010.js?ver=${ver}"));

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

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

$(document).ready(function(){

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

	$P.toast = new bootstrap.Toast($P.findn("divToast"), {
        animation: true,
        autohide: true,
        delay: 2000
    });

	/**************************************************************************
	* DatasetControl, DatasetSupport, FormFields
	**************************************************************************/
	var ctrl = newCvlc03010Control($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("schCvlcptRcptYmdFrom").datepicker('setDate', DateSupport.getAddDay(-365));
		$P.$findn("schCvlcptRcptYmdTo").datepicker('setDate', TODAY());

		ctrl.dataset.setData([]);
	}

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


	$P.getParams = () => {
		var formFields = new FimsFormFields($P.selectorn("frmSearch"));
		var data = formFields.get();
		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("crdnThead").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) => {
		let params = {
			callPageName : "${pageName}",
			crdnId : dataKey
		}

		ajax.get({
			url : ctrl.urls.getInfo,
			data : params,
			success : (resp) => {

				let dialogName = "totalInfoMainDialog";
				let dialogId = dialogName+"-"+uuid();

				dialog.open({
					id : dialogId,
					title : "개별총정보", size : "xxl", content : resp,
					init : () => {
						$("#"+dialogId).attr("name", dialogName);
						$("#"+dialogId).attr("data-ref-doctx","${pageName}");
					}
				});

			}
		});
	}

	$P.fnRemove = () => {

		var cur = ctrl.dataset.getCurrent();
		if(cur == null){
			return;
		}

		let dataIndex = ctrl.dataset.getCurrent("item").index;
		ctrl.dataset.select(dataIndex, true);

		var selected = ctrl.dataset.getDataset("selected");
		if (selected.length < 1) {
			return;
		}

		var params = {
			"crdnIds" : selected.map(item=>item.CRDN_ID).join(",")
		};

		ajax.post({
			url : ctrl.urls.remove,
			data : params,
			success : (resp) => {
				$P.saveCallback(resp);
			}
		});
	}

	$P.saveCallback = (resp) => {
		if (resp.saved){
			$P.toast.show();
			AppSupport.sleep(1000).then(() => $P.refreshCrdnList());
		}
	}

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

		var taskSeCd = $P.$findn("frmSearch").find("input[name='taskSeCd']:checked").val();


		ajax.get({
			url : wctx.url("/cvlc/cvlc01/050/info.do"),
			data : { crdnId : cur["CRDN_ID"] },
			success : (resp) => {
				let dialogName = "cvlcptOrgnlDialog";
				let dialogId = dialogName+"-"+uuid();

				dialog.open({
					id : dialogId,
					title : "민원내역 원본",
					content : resp,
					size : "xl",
					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.provide = {
		"getCountStatus" : function(currentCrdnId){
			var dsArray = ctrl.dataset.getDataset();
    		var arrayindex = dsArray.findIndex(item => item.CRDN_ID == currentCrdnId);
    		return (arrayindex+1) + " of " + dsArray.length;
    	},
		"getNextKey" : function(currentCrdnId){
    		var dsArray = ctrl.dataset.getDataset();
    		var arrayindex = dsArray.findIndex(item => item.CRDN_ID == currentCrdnId);
    		if(dsArray.length > arrayindex+1){
    			return dsArray[arrayindex+1]["CRDN_ID"];
    		} else {
    			return "";
    		}
    	},
    	"getPrevKey" : function(currentCrdnId){
			var dsArray = ctrl.dataset.getDataset();
    		var arrayindex = dsArray.findIndex(item => item.CRDN_ID == currentCrdnId);
    		if(arrayindex != 0 && dsArray.length > 1){
    			return dsArray[arrayindex-1]["CRDN_ID"];
    		} else {
    			return "";
    		}
    	},
    	"selectRow" : function(currentCrdnId){
    		let filtered = ctrl.dataset.getDataset("item").filter(item => item.data.CRDN_ID == currentCrdnId);
    		if(filtered.length > 0){
    			$P.clickCrdnList(filtered[0].index);
			}
    	},
    	"refreshList" : function(){
    		$P.refreshCrdnList();
    	},
    	"hasData" : function(crdnId){
    		let filtered = ctrl.dataset.getDataset("item").filter(item=>item.data.CRDN_ID == crdnId);
    		if(filtered.length > 0){
    			return true;
    		} else {
    			return false;
    		}
    	},
	};


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

	// 동적검색에서 엔터(Enter) 키를 누르면 검색한다.
	$P.$findn("term").onEnterPress($P.searchCrdnList);

	$P.$findn("btnDelete").on("click", () => $P.fnRemove());
	$P.$findn("btnOpenCvlcptOrgnl").on("click", () => $P.fnOpenCvlcptOrgnl());

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

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

    var defaultBizValue = $("#layout-navbar input[name='taskSeCd']:checked").val();
    $P.$findn("frmSearch").find("input[name='taskSeCd'][value='" + defaultBizValue + "']").prop("checked",true);
	$P.fnResetAndChangeBiz(defaultBizValue);

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

    $P.$findn("frmSearch").find("input[name='taskSeCd']").each(function(i) {
		$(this).prop("disabled", "true");
	});
});


</script>