<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" session="false"%>
<%@ include file="/WEB-INF/jsp/include/taglib.jsp"%>
<jsp:include page="/WEB-INF/jsp/include/head.jsp" />
<body>
    <div class="layout-wrapper layout-content-navbar layout-without-menu">
        <div class="layout-container">

        	<div class="layout-page">

        		<div class="content-wrapper mt-0">
        			<jsp:include page="/WEB-INF/jsp/include/userMenus.jsp" />
        			<div class="content-body menu-aware">
						<div class="sticky-wrapper">
							<div class="sticky-element">
								<jsp:include page="/WEB-INF/jsp/include/top.jsp" />
								<ul id="menu-tabs" class="nav nav-tabs mt-1" role="tablist"
								style="--bs-nav-link-padding-y: .125rem; background-image: linear-gradient(#8AB9DB, whitesmoke);">
								</ul>
							</div>
						</div>
						<template id="main-tab">
							<li class="nav-item" role="presentation">
								<div class="nav-link border-bottom-0" data-bs-toggle="tab" data-bs-target="{tab-target}"
								role="tab" aria-controls="{index}" tabindex="-1">
									<span onclick="openMenu('{url}');" class="w-px-150 text-truncate">{name}</span>
									<span onclick="mainTabs.close('{url}')" class="ms-2">&times;</span>
								</div>
							</li>
						</template>
						<div id="main-tab-content" class="tab-content shadowed">
							<div id="dashboard" class="tab-pane fade" role="tabpanel">
								<jsp:include page="/WEB-INF/jsp/dashboard.jsp" />
							</div>
						</div>
						<template id="tab-pane">
							<div id="{index}" class="tab-pane fade" role="tabpanel">{inner-content}</div>
						</template>
						<jsp:include page="/WEB-INF/jsp/include/bottom.jsp" />
					</div>


        		</div>

            </div>
        </div>
    </div>

	<div id="selectTaskModal" class="modal fade h-auto" tabindex="-1"
		data-bs-backdrop="static" data-bs-focus="false" data-bs-keyboard="false">
		<div class="modal-dialog modal-sm" role="document">
			<div class="modal-content">
				<div class="modal-body modal-body-min">
					<div class="h3 fw-bold text-center">업무를 선택하세요.</div>
					<span id="selectTaskButtons" class="row g-3 d-flex flex-column">

					</span>
				</div>
			</div>
		</div>
	</div>

    <jsp:include page="/WEB-INF/jsp/include/tail.jsp" />
    <!-- 자동 로그아웃 -->
    <script src="<c:url value="/webjars/3rd-party/sneat/libs/idletimer/idletimer.js"/>"></script>

    <c:set var="onload">

    </c:set>

    <script>
		//단축키 등록
    	FimsSupport.registShortcutKey();

		let sticky = {id: -1, index: "dashboard", name: "대시보드", url: "/dashboard.do", parentID: null, description: "대시보드"};
		let mainTabs = new TabControl({
			sticky: null,
			getMenu: (url) => menuSupport.getMenu(url),
			onDatasetChange: tabs => {
				let template = document.getElementById("main-tab").innerHTML,
					toTab = (tmpl, item) => tmpl.replace(/{tab-target}/gi, "#" + "{index}"),
					tags = mainTabs.inStrings(template, toTab);
				document.getElementById("menu-tabs").innerHTML = tags.join("");

				if (!mainTabs.sticky.empty)
					$("#menu-tabs .nav-item").eq(0).find("span.ms-2").remove();

			},
			onCurrentChange: tab => {
				if (!tab || !tab.data) return;

				let url = tab.data.url;
				menuSupport.setActive(url);
				document.querySelector("#menu-tabs li span[onclick=\"openMenu('" + url + "');\"]").click();

				let currentPane = document.querySelector("#" + tab.data.index);
				if (!currentPane) {
					let template = document.getElementById("tab-pane").innerHTML,
						html = tab.inString(template);

					if (tab.data.content) {
						html = html.replace(/{inner-content}/, tab.data.content);
						delete tab.data.content;
						$("#main-tab-content").append(html);
					}
				}

				document.querySelectorAll("#main-tab-content > div.tab-pane")
					.forEach(tabPane => {
						let current = tab.data.index == tabPane.getAttribute("id");
						if (current)
							tabPane.classList.add("show", "active");
						else
							tabPane.classList.remove("show", "active");
					});
			},
			onRemove: tabs => {
				let mainTab = document.querySelector("#main-tab-content");
				tabs.forEach(tab => {
					let tabPane = document.querySelector("#" + tab.data.index);
					if (!tabPane) return;

					mainTab.removeChild(tabPane);
					delete tabPane;
				});
				mainTabs.onDatasetChange();
			}
		});

		function openMenu(url) {
			mainTabs.open(url)
		}

		$(".sticky-element").sticky({
			topSpacing: $(".nav-bar").height() + 1,
			width: "100%",
		    zIndex: 9
		});



    	const FETCH_XXS = 10;
    	const FETCH_XS = 30;
    	const FETCH_SM = 50;
    	const FETCH_MD = 100;
    	const FETCH_LG = 300;
    	const FETCH_XL = 500;
    	const FETCH_XXL = 1000;

    	const DEFAULT_FETCH_SIZE = 30;

    	//자동 로그아웃
        const ONE_MINUTE = 60 * 1000;
		let sessionConfig = 30 * ONE_MINUTE;
		$.idleTimer(sessionConfig);
		$(document).bind("idle.idleTimer", function(){
			$.idleTimer('destroy');

			ajax.post({
				url : wctx.url("/logout.do"),
				data : { "${_csrf.parameterName}" : "${_csrf.token}" },
				success : async function(){
					var ok = await alert2("세션이 종료되어 로그아웃되었습니다.");
					if(ok){
						location.href = wctx.url("/login.do");
					}
				}
			});
		});

		let fastSearch = false;

    	var pageObject = {};
    	pageObject.help = function(){
			console.log("pageObject : 로드된 페이지이름(서버에서 반환하는 pageName변수 또는 jsp파일명)을 하위 키로 갖는 전역객체");
		};
    	pageObject.childReq = [];
    	pageObject.parentRes = [];
    	pageObject.top = newDoctxFinder("top");

    	function LoadScript(scriptId, scriptPath){
    		if(document.getElementById(scriptId) == null){
    			$("body").append("<script id='"+scriptId+"' src='"+scriptPath+"' />");
    		}
    	}

    	async function LoadJson(path){
    		let resp = await fetch(path);
    		return await resp.json();
		}

    	function FindObject(objectName, pageName){
    		return pageName ? pageObject[pageName][objectName] : window[objectName];
    	}

    	function RegistObject(objectName, def, pageName){
    		if(pageName == undefined || pageName == null || pageName == ""){
    			window[objectName] = def;
    			return window[objectName];
    		} else {
    			pageObject[pageName][objectName] = def;
    			return pageObject[pageName][objectName];
    		}
    	}

    	var ALL_TASK = {};
    	var MY_INFO = {};
    	var SYS_LINK_INFO = {};
    	var PARAM_TASK = "${param.taskSeCd}";

		async function fnGetAllTask(){
    		return new Promise((resolve, reject) => {
				$.ajax({
					type: "get",
					url: wctx.url("/code/getAllTaskSeCd.do"),
					data: {},
					dataType: 'json',
					success: function(resp, textStatus, jqXHR) {
						ALL_TASK = resp.allTask;
						resolve({resp, textStatus, jqXHR});
					},
					error: function(jqXHR, textStatus, error) {
					}
				});
    		});
    	};

    	async function fnCheckSggTask(){
    		return new Promise((resolve, reject) => {
				$.ajax({
					type: "get",
					url: wctx.url("/code/sggHasTask.do"),
					data: {},
					dataType: 'json',
					success: function(resp, textStatus, jqXHR) {
						if(resp.sggHasTask == "Y" || "${currentUser.user.getCntnSeCd()}" == "02"){
							resolve({resp, textStatus, jqXHR});
						} else {
							reject("시군구 업무 설정이 없습니다.");
						}
					},
					error: function(jqXHR, textStatus, error) {
					}
				});
    		});
    	}

    	async function fnGetSysLinkInfo(){
   			return new Promise((resolve, reject) => {
   				$.ajax({
   					type: "get",
   					url: wctx.url("/user/sysLinkInfo.do"),
   					data: {},
   					dataType: 'json',
   					success: function(resp, textStatus, jqXHR) {
   						SYS_LINK_INFO = resp.sysLinkInfo;
   						resolve({resp, textStatus, jqXHR});
   					},
   					error: function(jqXHR, textStatus, error) {
   					}
   				});
       		});
    	};

		async function fnGetMyInfo(){
   			return new Promise((resolve, reject) => {
   				$.ajax({
   					type: "get",
   					url: wctx.url("/user/myInfo.do"),
   					data: {},
   					dataType: 'json',
   					success: function(resp, textStatus, jqXHR) {
   						MY_INFO = resp.myInfo;
   						resolve({resp, textStatus, jqXHR});
   					},
   					error: function(jqXHR, textStatus, error) {
   					}
   				});
       		});
    	};

    	function fnSelectDefaultTask(taskSeCd){
    		ajax.get({
    			url : wctx.url("/user/saveDefaultTask.do"),
    			data : {
    				"taskSeCd" : taskSeCd
    			},
    			success : (resp) => {
    				if(resp.saved){
    					$("#selectTaskModal").modal("hide");
    		    		initIndexPage(true, PARAM_TASK, taskSeCd);
    				}
    			}
    		});
    	}

    	function initIndexPage(isPublicOfficer, paramTask, userDefaultTask){
    		if(!isPublicOfficer){

<%--   			$("#home").html("과태료통합관리시스템<br/>("+"임대기업사용자"+")"); --%>
    			$("#home").html("북촌 통행제한 관리 시스템");

    			$("#btnOpenTempFileUploadWindow").remove();
    			$("#btnOpenSelectStngDialog").remove();
    			$("#btnGoToCvlcptDscsn").remove();
    			$("#btnGoToSchdl").remove();
    			$("#btnDownloadMenual--top").remove();
    			$("#btnGoToNtc").remove();

				return;
			}

    		$("#btnCancelAccount--Top").remove();

			if(paramTask != "" || $("#layout-navbar").find("input[name='taskSeCd'][value='"+paramTask+"']").length > 0){
				$("#layout-navbar input[name='taskSeCd'][value='"+paramTask+"']").prop("checked", true);
		    } else if(userDefaultTask != "" || $("#layout-navbar").find("input[name='taskSeCd'][value='"+userDefaultTask+"']").length > 0){
		    	$("#layout-navbar input[name='taskSeCd'][value='"+userDefaultTask+"']").prop("checked", true);
		    } else {
		    	$("#layout-navbar input[name='taskSeCd']").eq(0).prop("checked", true);
		    }

			//좌측상단제목, 최상단 배경색
			var checkedId = $("#layout-navbar input[name='taskSeCd']:checked")[0].id;
			var checkedText = $("label[for='"+checkedId+"']").text();
			$("#home").html("북촌 통행제한<br/>관리 시스템");

			var taskTheme = "task-theme-" + $("#layout-navbar input[name='taskSeCd']:checked").val().toLowerCase();
			$("#layout-navbar").addClass(taskTheme);
<%--
			//대시보드 로드
			${dashboardLoadScript}
--%>
    	}
    	
    	function crdnTotalInfo(params = {}, onClose = () => {}) {
    		if (!params.crdnId) return;
    		
    		ajax.get({
	  			  url: wctx.url("/sprt/sprt02/010/main.do")
	  			, 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}");
	
//	  						AppSupport.setDialogZindex();
	  					}
	  					, onClose: onClose
	  				});
	  			}
    		});
    	}

        ${functions}

        ${topScript}

        ${userMenus}

        ${dashboardScript}

        $(function(){
            ${onload}

            //mainTabs.getTab(sticky.url);

            fnGetAllTask()
            .then(() => { return fnCheckSggTask(); })
            .then(() => { return fnGetSysLinkInfo(); })
            .then(() => { return fnGetMyInfo(); })
			.then(() => {

				var msg = "";
   				var available = true;

   				if(MY_INFO.user.status == "A" || MY_INFO.user.status == "D" || MY_INFO.user.locked == "Y"){

   					if(MY_INFO.user.status == "A"){
   						msg = "계정이 미승인 상태입니다.";
   					} else if(MY_INFO.user.status == "D"){
   						msg = "삭제된 계정입니다.";
   					} else if(MY_INFO.user.locked == "Y"){
   						msg = "잠금처리된 계정입니다.";
   					}
   					available = false;
   				}

   				if(!(MY_INFO.info.isAdmin)){
					if(MY_INFO.info.isPublicOfficer){
						if(!(MY_INFO.info.hasTaskAuth)){
							msg = "계정에 부여된 업무권한이 없습니다.";
		   					available = false;
						}
					}
   				}

   				if(msg != ""){
   					alert(msg);
   				}

   				//로그아웃
   				if(!available){
   					var form = $("<form action=\""+wctx.url("/logout.do")+"\", method=\"POST\">");
   					$("<input name=\"${_csrf.parameterName}\" value=\"${_csrf.token}\" type=\"hidden\">").appendTo(form);
   					form.appendTo("body").submit();
   					return;
   				}

   				//지자체 심볼
   				if(MY_INFO.info.sggSymbolPath != ""){
 <%--  					$("#symbol--left").attr("src", MY_INFO.info.sggSymbolPath); --%>
   					$("#symbol--left").attr("src", "<c:url value='resources/img/login/mainLogo_01.png'/>");
   				}

   				//사용하지 않는 연계와 관련된 메뉴 제거
   				//새올민원 관련 메뉴 제거
   				if(SYS_LINK_INFO == null || SYS_LINK_INFO.CVLCPT_LINK_SE_CD != '01'){
   					var saeolMenuUrl = wctx.url("/cvlc/cvlc04/010/main.do");
   					$("ul[id='menus']").find("li[class='menu-item']").each(function(){
						if($(this).children("a[onclick]").length > 0){
							let oc = $(this).children("a[onclick]").attr("onclick").split("'");
							if(oc.length == 3 && oc[1] == saeolMenuUrl){
								$(this).remove();
							}
						}
   					});
   				}

   				if(MY_INFO.info.isPublicOfficer){
   					//사용자별 선택가능한 업무 렌더링
   	   				$("#selectTaskButtons").html("");
   					let length = MY_INFO.info.taskForUser.length;
   	   				for(var i = 0; i < length; i++){
   	   					var taskCd = MY_INFO.info.taskForUser[i];
   	   					var taskNm = ALL_TASK[taskCd];

   	   					var radio = "<span>";
   	   					radio += "<input type='radio' id='taskSeCd"+(i+1)+"--top' name='taskSeCd' value='"+taskCd+"' title='"+taskNm+"' style='margin-right: .5rem;' />";
   	   					radio += "<label for='taskSeCd"+(i+1)+"--top'>"+taskNm+"</label>";
   	   					radio += "</span>";
   	   					$("#taskSeCd--Top").append(radio);

   	   					var button = `<button type="button" class="btn btn-xl btn-primary" onclick="fnSelectDefaultTask('`
   	   							+taskCd
   	   							+`');">`
   	   							+taskNm
   	   							+`</button>`;
   	   					$("#selectTaskButtons").append(button);
   	   				}
   	   				if (length < 2)
   	   					$("#taskSeCd--Top").parent().hide();

   	   				$("#layout-navbar input[name='taskSeCd']").on("click", function(){
   	   					$("#userNav--top").click();
   	   					window.open(wctx.url("/")+"?taskSeCd="+this.value, "_blank", "");
   	   					return false;
   	   				});

   	   				//업무선택 모달 다이얼로그
   	   				if(MY_INFO.info.defaultTask == null || MY_INFO.info.defaultTask == ""){
   	   					$("#selectTaskModal").modal("show");
   	   					return;
   	   				} else {
   	   					initIndexPage(true, PARAM_TASK, MY_INFO.info.defaultTask);
   	   					return;
   	   				}
				} else {
					initIndexPage(false, "", "");
				}

			}).catch((msg) => {
				alert(msg);

				var form = $("<form action=\""+wctx.url("/logout.do")+"\", method=\"POST\">");
				$("<input name=\"${_csrf.parameterName}\" value=\"${_csrf.token}\" type=\"hidden\">").appendTo(form);
				form.appendTo("body").submit();
				return;
            });
            
        });
//# sourceURL=index.jsp
    </script>
</body>
</html>