<%@ 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>
		        </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="schDmndYmdFrom"
                                	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="schDmndYmdTo"
                                	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>
		        </div>
		    </form>

		    <div>
		        <span class="container-page-btn">
		            <div class="d-flex flex-row justify-content-between">
						<span is="paging-info" name="dmndPagingInfo" class="dataTables_info"></span>
		                <ul name="dmndPaging" class="pagination pagination-primary"></ul>
					</div>
		            <span class="container-window-btn-right">
		            	<button type="button" name="btnOpenDmndPop"
		            		class="btn btn-primary" title="요청 등록">요청 등록</button>
		            	<button type="button" name="btnDelete"
		            		class="btn btn-primary" title="한 건 삭제">한 건 삭제</button>
		            	<button type="button" name="btnDeleteAllCompleteData"
		            		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="dmndTable" class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer">
							<thead name="dmndThead" class="sticky-thead">
								<tr data-search-target="[data-doctx='${pageName}']">
									<th style="width: 80px;">No.</th>
									<th style="width: 180px;">요청일시</th>
									<th style="width: 180px;">요청자</th>
									<th style="width: 180px;">접수일자</th>
									<th style="width: 180px;">목록번호</th>
									<th style="width: 180px;">상태</th>
									<th style="width: 180px;">응답일시</th>
									<th class="dummy-th"></th>
								</tr>
							</thead>
		                    <tbody name="dmndTbody"></tbody>
							<template is="curly-brackets" name="dmndRow">
								<tr data-index="DATA-INDEX">
									<td onclick class="text-end">ROW_NUM</td>
									<td onclick class="text-center">DMND_YMD</td>
									<td onclick class="text-center">RGTR</td>
		                    		<td onclick class="text-center">RCPT_YMD</td>
		                    		<td onclick class="text-center">PST_NO</td>
		                    		<td onclick class="text-center">STTS_NM</td>
		                    		<td onclick class="text-center">RSPNS_DT</td>
		                    		<td class="dummy-td"></td>
		                    	</tr>
							</template>
							<template name="dmndNotFound">
								<tr>
									<td valign="top" colspan="8" 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 name="toastText" class="toast-body bg-black text-white">
			    </div>
			  </div>
			</div>
		</div>
	</div>

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

  	<template name="saeolDmndDialogTemplate">
		<form name="frmEdit">
			<div class="card">
				<div class="row g-1">
					<div class="col-md-12">
						<label is="name-label" for="rcptYmd" data-ref-doctx="${pageName}"
							class="w-px-120 bg-lighter pe-2 col-form-label text-sm-end required">접수일자</label>
						<input type="text" is="id-input" name="rcptYmd"
							data-ref-doctx="${pageName}"
							class="form-control form-date" required data-fmt-type="day" />
						<button type="button" class="bx bx-lg bx-calendar bg-white"></button>
					</div>
					<div class="col-md-12">
						<label is="name-label" for="pstNo" data-ref-doctx="${pageName}"
								class="w-px-120 bg-lighter pe-2 col-form-label text-sm-end required">목록번호</label>
						<input type="text" is="id-input" name="pstNo" class="form-control"
							data-ref-doctx="${pageName}"
							required maxlength="6" data-maxlengthb="6" data-fmt-type="zeroLpadNumber" />
					</div>
				</div>
			</div>
			<div>
				<span class="container-page-btn">
					<span class="container-window-btn-right">
						<button type="button" class="btn btn-primary" name="btnCreate" title="확인">
						확인
						</button>
					</span>
				</span>
			</div>
		</form>
	</template>
</div>

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

/**************************************************************************
* Global Variable
**************************************************************************/
var FIM063 = new CommonCodes(${FIM063});
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 = newCvlc04010Control($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.renderDmndList(obj?.Paging?.totalSize, ctrl.dataset.length, trs, option);

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

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

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

	/**************************************************************************
	* pageObject.function
	**************************************************************************/
	$P.fnReset = () => {

		$P.$findn("schDmndYmdFrom").datepicker('setDate', DateSupport.getAddDay(-5475));
		$P.$findn("schDmndYmdTo").datepicker('setDate', TODAY());
		ctrl.dataset.setData([]);
	}

	$P.fnResetAndChangeBiz = (taskSeCd) => {
		$P.fnReset();
		ctrl.urls.load = wctx.url("/cvlc/cvlc04/010/list.do");
		ctrl.urls.create = wctx.url("/cvlc/cvlc04/010/create.do");
		ctrl.urls.remove = wctx.url("/cvlc/cvlc04/010/remove.do");
	}

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

		return data;
	}

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

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

	$P.refreshDmndList = () => {

		if(!ctrl.dataset.empty){
			ctrl.beforeCurrent = {
				primaryKey : ctrl.dataset.getCurrent()["INDIV_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, "INDIV_ID");
			ctrl.beforeCurrent = null;
			if(todoCurrent != null){
				ctrl.dataset.setCurrent(todoCurrent.index, true);
			}

		});
	}

	$P.getGridTemplate = () => {
		var notFound = [$P.findn("dmndNotFound").innerHTML];
		var found = $P.findn("dmndRow").innerHTML;
		var replacer = (str, dataItem) => str
			.replace(/{onclick}/gi, "pageObject['${pageName}'].clickDmndList('{DATA-INDEX}');");

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

	$P.renderDmndList = (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);
	}

	$P.clickDmndList = (dataIndex) => {
		if(dataIndex == ""){
			return;
		}

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

	$P.fnRemove = (allCompleteDataIndexs) => {

		if(allCompleteDataIds != null){
			ctrl.dataset.select(allCompleteDataIndexs,true);
		} else {
			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 = {
			"indivIds" : selected.map(item=>item.INDIV_ID).join(",")
		};

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

	}

	$P.removeCallback = (resp) => {
		if (resp.saved){
			$P.$findn("toastText").html("삭제 되었습니다.");
			$P.toast.show();
			AppSupport.sleep(1000).then(() => $P.refreshDmndList());
		}
	}

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

		var ds = ctrl.dataset.getDataset("item");

		let filtered = ds.filter(function(item){
			if(item.data['STTS_CD'] == '9' || item.data['STTS_CD'] == 'B'){
				return true;
			} else {
				return false;
			}
		});

		if(filtered.length == 0){
			dialog.alert({
				content : "요청 완료자료가 없습니다.",
				init : function() {
					AppSupport.focusClose();
				}
			});
			return;
		}
		var dataIndexs = filtered.map(item=>item.index);

		dialog.alert({
			content : "완료된 자료를 모두 삭제하시겠습니까?",
			init : function() {
				AppSupport.focusOK();
			},
			onOK : () => {
				$P.fnRemove(dataIndexs);
			}
		});

	}

	//요청 등록 팝업 호출
	$P.fnOpenDmndPop = () => {

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

		dialog.open({
			id : dialogId,
			title : "새올 접수 요청",
			content : $P.findn("saeolDmndDialogTemplate").innerHTML,
			size : "lg",
			init : () => {
				$("#"+dialogId).attr("name", dialogName);
				$("#"+dialogId).attr("data-ref-doctx","${pageName}");
				let refDlgId = $P.refDlgId("saeolDmndDialog");
				AppSupport.initDatepicker(document.getElementById(refDlgId));
				$("#"+refDlgId).find("[name='rcptYmd']").datepicker('setDate', TODAY());
				$("#"+refDlgId).find("[name='btnCreate']").on("click", () => $P.fnCreateDmnd());
			},
			onClose : () => {}
		});
	}

	//요청 등록
	$P.fnCreateDmnd = () => {

		if(!AppSupport.customValidate($("#"+$P.refDlgId("saeolDmndDialog")).find("[name='frmEdit']").find("input"))) return;

		let selectorStr = "#"+$P.refDlgId("saeolDmndDialog")+" "+"form[name='frmEdit']";
		let ff = new FimsFormFields(selectorStr);
		var info = ff.get();
		info.taskSeCd = $P.$findn("frmSearch").find("input[name='taskSeCd']:checked").val();

		ajax.get({
			url : ctrl.urls.create,
			data : info,
			success : (resp) => {
				if(resp.saved){
					dialog.close($P.refDlgId("saeolDmndDialog"));

					$P.$findn("toastText").html("등록 되었습니다.");
					$P.toast.show();

					if(!ctrl.dataset.empty){
						AppSupport.sleep(1000).then(() => $P.refreshDmndList());
					}
				}
			}
		});
	}

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

	$P.$findn("btnOpenDmndPop").on("click", () => $P.fnOpenDmndPop());
	$P.$findn("btnDelete").on("click", () => $P.fnRemove(null));
	$P.$findn("btnDeleteAllCompleteData").on("click", () => $P.fnRemoveAllCompleteData());

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

	/**************************************************************************
	* 초기화
	**************************************************************************/
  	//달력 초기화
    AppSupport.initDatepicker($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);

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


</script>