<%@ 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" data-doctx="${pageName}">
	<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 class="fieldset-legend mt-4">
					<div class="fieldset-legend-content fs-big" data-label="배치 수동 실행">
						<button type="button" class="btn btn-primary" onclick="executeBatch('smgReceive');">국민신문고 수신</button>
						<button type="button" class="btn btn-primary" onclick="executeBatch('smgSend');">국민신문고 답변 송신</button>
						<button type="button" class="btn btn-primary" onclick="executeBatch('epostSend');">전자우편 송신</button>
						<button type="button" class="btn btn-primary" onclick="executeBatch('epostReceive');">전자우편결과 수신</button>
					</div>
				</div>
				
				<div class="fieldset-legend mt-4">
					<div class="fieldset-legend-content fs-big" data-label="업무시스템 수동 통보">
						<button type="button" class="btn btn-primary" onclick="exceuteAlert('smgReceive');">국민신문고 수신</button>
					</div>
				</div>
				
				<div class="fieldset-legend mt-4">
					<div class="fieldset-legend-content fs-big" data-label="파일 현황">
						<div class="card-datatable text-nowrap">
					        <div id="DataTables_Table_0_wrapper" class="dataTables_wrapper dt-bootstrap5 no-footer">
								<div class="d-flex flex-row justify-content-evenly mh-px-400">
									<div class="w-50 mx-2 oy-auto">
										<h5 class="mt-3">파일트리</h5>
										<div id="menu-tree" class="main-left d-flex flex-column flex-grow-1">
											<div class="d-flex justify-content-between py-2 border-separator-y">
												<button type="button" class="btn btn-primary"
												onclick="getFileTree();">갱신</button>
											</div>
											<div id="fileTree" class="ox-auto oy-auto pt-3 h-px-300">
											</div>
										</div>
									</div>
			
									<div class="w-50 mx-2">
										<h5 class="mt-3">파일내용</h5>
										<div class="d-flex flex-row justify-content-start p-3">
											<textarea id="viewCn" rows="14" cols="100%" readonly="readonly"></textarea>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				
				<div class="fieldset-legend mt-4">
					<div class="fieldset-legend-content fs-big" data-label="시군구 정보 백업 & 복제">
						<button type="button" class="btn btn-primary" id="btnOpenSggAddDel">시군구 추가/삭제</button>
						<button type="button" class="btn btn-primary" id="btnOpenCopySggStng">시군구 설정 복사</button>
					</div>
				</div>
			</div>
			
		</div>
		

		
	</div>

	<input type="file" id="serverFile" name="serverFile" hidden onchange="fnImportFile(this);" />

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

<script>
pageObject['${pageName}'] = newDoctxFinder("${pageName}");

/**
 * 수동 배치 실행
 */
function executeBatch(batch){
	ajax.get({
		url : wctx.url("/admin/executeBatch.do"),
		data : { batch : batch},
		success : (resp) => {
			dialog.alert("실행되었습니다.");
		}
	});
}

function exceuteAlert(alertName){
	if(alertName != "smgReceive"){
		return;
	}
	
	var interfaceKey = prompt("인터페이스키를 입력하세요.");
	
	if(interfaceKey == null || interfaceKey == ""){
		return;
	}
	
	ajax.post({
		url : wctx.url("/admin/executeAlert.do"),
		data : { 
			alertName : alertName,
			interfaceKey : interfaceKey 
		},
		success : (resp) => {
			dialog.alert("실행되었습니다.");
		}
	});
}

var tempPathArray = [];

/**
 * 파일트리 컨텍스트 메뉴
 */
function customContextMenu(node){
	var items = {
		
		newDirectory : {
			label:"디렉토리 추가", 
			action:function(data){
				var inst = $.jstree.reference(data.reference);
                var obj = inst.get_node(data.reference);
				var pathArray = $("#fileTree").jstree("get_path", obj.id);
				
				var directoryName = prompt("디렉토리명을 입력하세요");
				
				if(directoryName != null && directoryName != ""){
					pathArray.push(directoryName);
					
					ajax.post({
						url : wctx.url("/admin/createDirectory.do"),
						data : {
							directories : pathArray
						},
						success : (resp) => {
							if(resp.saved){
								getFileTree();
							} else {
								alert("폴더 생성에 실패하였습니다.");
							}
						}
					});
				}
			}
		},
		newFile : {
			label:"파일 추가", 
			action:function(data){
				var inst = $.jstree.reference(data.reference);
                var obj = inst.get_node(data.reference);
				var pathArray = $("#fileTree").jstree("get_path", obj.id);
				tempPathArray = pathArray;

				$("#serverFile").click();
				
			}
		},
		viewCn : {
			label : "내용 보기",
			action:function(data){
				var inst = $.jstree.reference(data.reference);
                var obj = inst.get_node(data.reference);
				var pathArray = $("#fileTree").jstree("get_path", obj.id);
				
				ajax.post({
					url : wctx.url("/admin/getFileText.do"),
					data : {
						directories : pathArray
					},
					success : (resp) => {
						$("#viewCn").val(resp.fileCn);
					}
				});
				
			}
		}
	};
	
	if(node.type == "file") {
        delete items.newDirectory;
        delete items.newFile;
    }
	
	if(node.type == "directory"){
		delete items.viewCn;
	} else if(!node.text.endsWith(".txt") && !node.text.endsWith(".xml")
			&& !node.text.endsWith(".TXT") && !node.text.endsWith(".XML")){
		delete items.viewCn;
	}
	
	return items;
}

$('#fileTree').jstree({
    "core" : {
        "data": {}
    },
    "plugins": ["types","contextmenu"],
    "types" : {
        "directory" : { "icon" : "fa fa-folder" },
        "file" : { "icon" : "fa fa-file" }
    },
    trace: true,
    core : {
    	check_callback:true,
	    multiple:false
	},
	contextmenu : {
		items : customContextMenu
	}
});
$("#fileTree").bind("refresh.jstree", function(){
	$(this).jstree("open_all");
});

/**
 * 파일트리 조회
 */
function getFileTree(){
	ajax.get({
		url : wctx.url("/admin/getFileTree.do"),
		data : {},
		headers: { Accept: "application/json; charset=utf-8" },
		success : (resp) => {
			
			$('#fileTree').jstree(true).settings.core.data = resp.tree;
			$('#fileTree').jstree(true).refresh();
			
		}
	});
}

/**
 * 파일 추가
 */
function fnImportFile(obj){
	if(obj.files.length == 0){
		return;
	}
	
	var form = new FormData();
    form.append("newFile", obj.files[0]);
    form.append("directories[]", tempPathArray);
    
	ajax.post({
		url : wctx.url("/admin/importFile.do"),
		data : form,
		processData : false,
        contentType : false,
		success : (resp) => {
			if(resp.saved){
				getFileTree();
			} else {
				alert("파일 추가에 실패하였습니다.");
			}
		}
	});
}

$("#btnOpenSggAddDel").on("click", function(){
	ajax.get({
		url :  "/admin/sggAddDelInfo.do",
		data: {},
		success: (resp) => {
			
			let dialogName = "sggAddDelDialog";
			let dialogId = dialogName+"-"+uuid();
			
			dialog.open({
				id: dialogId,
				title: "시군구 추가,삭제",
				content: resp ,
				size: "xxl",
				init:() => {
					$("#"+dialogId).attr("name", dialogName);
					$("#"+dialogId).attr("data-ref-doctx","${pageName}");
				}
			});
		}
	});
});

$("#btnOpenCopySggStng").on("click", function(){
	ajax.get({
		url :  "/admin/copySggStngInfo.do",
		data: {},
		success: (resp) => {

			let dialogName = "copySggStngDialog";
			let dialogId = dialogName+"-"+uuid();
			
			dialog.open({
				id: dialogId,
				title: "시군구 설정 복사",
				content: resp ,
				size: "xl",
				init:() => {
					$("#"+dialogId).attr("name", dialogName);
					$("#"+dialogId).attr("data-ref-doctx","${pageName}");
				}
			});
		}
	});
});

$(document).ready(function(){
	getFileTree();
});

</script>