<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html lang="ko">
<head>
	<title>권한별메뉴관리</title>
	<%@ include file="/WEB-INF/jsp/adm/include/topLinkTag.jsp" %>
</head>
<body>
<h1>ICOMSYS ADMIN</h1>

<div class="skip_navigation">
	<ul>
		<li>
			<a href="#Content" class="go_content">본문 바로가기</a>
		</li>
		<li>
			<a href="#Gnb">메뉴 바로가기</a>
		</li>
	</ul>
</div>

<header id="header">
	<%@ include file="/WEB-INF/jsp/adm/include/header.jsp" %>
</header>

<c:import url="/adm/menu/getLnbMenu.do" />

<script>
$(document).ready( function () {

	// 권한별메뉴 조회
	$('#btnSearchCust').on('click',function() {
		fncSearchCust();
    });

	// 권한별메뉴 수정
	$('#btnEditCust').on('click',function() {
		fncUpdateCustInfo();
    });

	// 권한별메뉴 리스트 그리기
	fncSearchCust();
});

function fncKeyPresshandler(e) {
	if (event.keyCode == 13) {
		fncSearchCust();
		return false;
	}
}

// 권한별메뉴 리스트 그리기
function fncSearchCust() {

	$('#listTable tbody').empty();

	var param = "searchKeyword=" + $('#keyword').val();
	var resultTr = '';

	$.ajax({
		type : "post",
		async : false,
		datatype : "text",
		url : "<c:url value='/admin/system/retrieveMenuAuth.do'/>",
		data : param,
		success : function(data){

			$.each($.parseJSON(data.nMap), function(i, val) {
				i += 1;

				resultTr += '<tr class="modalLoad" rel="reg_edit_modal" data-auth-code="' + val.authCode + '">';
				resultTr += '	<td class="tl">' + val.authCode + '</td>';
				resultTr += '	<td class="tl">' + val.authName + '</td>';
				resultTr += '	<td class="tl">' + val.authDesc + '</td>';
				resultTr += '	<td>' + authHasYn(val.chkYeoBu) + '</td>';
				resultTr += '</tr>';
			});

			$('#listTable tbody').append(resultTr);

			// 권한별메뉴 수정 modal open event
			$('#listTable tbody tr').on('dblclick', function() {
				fncSearchDetail($(this));
			});

			// scripts.js : 권한별메뉴 list modal 연결
			modalUi();

			// scripts.js : 체크 박스 체크에 따른 '모두 체크' 변경
			checkAllChecked();
		}
	});
}

function authHasYn(count) {
	return count > 0 ? 'Y' : 'N';
}

// 수정 modal 값 가져오기
function fncSearchDetail(tr){
	var authCode = $(tr).data('authCode');

	var param = "authCode=" + authCode;

	$.ajax({
		type : "post",
		async : false,
		datatype : "text",
		url : "<c:url value='/admin/system/menuCreatSelect.do'/>",
		data : param,
		success : function(data) {
			fncSetDetailInfo(data);
		}
	});
}

//수정 modal 값 채우기
function fncSetDetailInfo(infoData) {
	// 서비스 코드 양식 그리기
	var shtml = '';

	var instance = $('#menuTree').jstree(true);

	// console.log('init instance : ' + instance);
	if(instance) {
		instance = $('#menuTree').jstree("destroy");
		// console.log('init?? true' + instance);
	}

	$('#menuTree').empty();

	// console.log('empty() instance : ' + instance);

	var len = infoData.list_menulist.length;
	var dataList = infoData.list_menulist;
	var afterLevel;
	var nowLevel;
	var checkedArr = new Array;
	var upperNode = new Array;

	for(var i=0; len > i; i++) {
		nowLevel = dataList[i].level;

		if(dataList[i].useFlag != null && dataList[i].useFlag == 'Y') {
			// 체크 되어 있는 서비스코드 항목
			var menuNolen = dataList[i].menuNo.toString().length;
			if(menuNolen >= 7 && dataList[i].menuNo.toString().substr(menuNolen-2, menuNolen) != "00") {
				checkedArr.push('chk' + dataList[i].menuNo);
			}
			else {
				upperNode.push('chk' + dataList[i].menuNo);
			}
		}
		else {
			if(menuNolen < 7 || dataList[i].menuNo.toString().substr(menuNolen-2, menuNolen) == "00") {
				upperNode.push('chk' + dataList[i].menuNo);
			}
		}

		if(len > i + 1) {
			afterLevel = dataList[i+1].level;
		}
		else {
			afterLevel = 0;
		}

		if(i == 0) {
			shtml += '<ul>';
		}

		if(nowLevel == afterLevel) {
			// 다음 노드가 동위 노드

			shtml += '<li id="chk' + dataList[i].menuNo + '">' + dataList[i].menuName + '</li>';
		}
		else if(nowLevel < afterLevel) {
			// 다음 노드가 하위 노드

			//shtml += '<li id="chk' + dataList[i].menuNo + '" data-jstree=\'{ "opened" : true }\'>' + dataList[i].menuName;
			shtml += '<li id="chk' + dataList[i].menuNo + '" data-jstree=\'{ "checkbox_disabled" : true }\'>' + dataList[i].menuName;
			//shtml += '<li id="chk' + dataList[i].menuNo + '">' + dataList[i].menuName;
			shtml += '<ul>';
		}
		else if(afterLevel == 0) {
			// 현재가 마지막 노드

			shtml += '<li id="chk' + dataList[i].menuNo + '">' + dataList[i].menuName + '</li>';

			for(var j=0; nowLevel > j; j++) {
				shtml += '</ul>';
				shtml += '</li>';
			}

			shtml += '</ul>';
		}
		else {
			// nowLevel > afterLevel : 다음 노드가 상위 노드

			shtml += '<li id="chk' + dataList[i].menuNo + '">' + dataList[i].menuName + '</li>';

			for(var j=0; (nowLevel - afterLevel) > j; j++) {
				shtml += '</ul>';
				shtml += '</li>';
			}
		}
	}

	//$('#menuTree').append(shtml);
	$('#menuTree').html(shtml);

	instance = $('#menuTree').jstree(true);
	//instance2.deselect_all();
    //instance2.select_node('1');

	// console.log('innerHtml instance : ' + instance);
	// instance.deselect_all();
	// console.log('instance : ' + instance);

	if(instance) {
    	//instance.deselect_all();
        //instance.select_node('1');
    }
    else {
		$('#menuTree').jstree({


			"core" : {
				"check_callback" : function (operation, node, node_parent, node_position, more) {
					// operation can be 'create_node', 'rename_node', 'delete_node', 'move_node', 'copy_node' or 'edit'
					// in case of 'rename_node' node_position is filled with the new node name

					//return operation === 'rename_node' ? true : false;
					//console.log('check_callback');
				}
			},
			"checkbox" : {
				//"keep_selected_style" : false
				//"tie_selection" : false
			},
	        "plugins" : [
	            "checkbox"
	        ]
	    }).on("changed.jstree", function (e, data) {
	    	//console.log('changed');
	    	//console.log(data.instance.get_selected(true)[0].text);
			//console.log(data.instance.get_node(data.selected[0]).text);
	    }).on("select_node.jstree", function (e, data) {
	    	//console.log('select_node');
	    }).on("deselect_node.jstree", function (e, data) {
	    	//console.log('unselect_node');
	    });


		// json data 생성 형태
		//{ "id" : "Test node", "state" : { "checkbox_disabled" : true } }


		instance = $('#menuTree').jstree(true);

		var selected1 = instance.get_selected();
		//instance.select_all();
		//instance.select_node("j1_1");
		//instance.select_node("1");
		//instance.select_node("2");
		//instance.select_node("j1_3");
		instance.select_node(checkedArr);
		//instance.refresh();
		//instance.set_id("j1_4", "aa");
		var jsonData = instance.get_json();
		var textData = instance.get_text();
		//set_id(obj, id)
		//get_json([obj, options])
		//redraw([full])
		//get_text(obj)
		//get_undetermined ([full])
		//class='jstree-undetermined'

		// 안됨
		//var selected3 = instance.get_undetermined();
		var selected3 = instance._undetermined();
		//instance.disable_checkbox(upperNode);
		//instance.disable_checkbox();
		instance.disable_node(upperNode);

		var selected2 = instance.get_selected();

		// tree 모두 펼치기
		instance.open_all();

		//console.log();
		//instance.hide_checkboxes();
    }


	// 값 채우기
	$('#authCode').val(infoData.menuCreatVO.authCode);

}

// 기존 권한별메뉴 수정
function fncUpdateCustInfo() {
	swalAlert('warning', '수정', updateCustInfo);
}

// 권한별메뉴 update
function updateCustInfo() {
	var param = "authCode=" + $('#authCode').val();
		param += "&checkedAuthorForInsert=" + $('#authCode').val();
		param += "&checkedMenuNoForInsert=";

	// var checkbox = $('#serviceCode input[name=checkbox]:checked');
	var checkbox = $('#menuTree').jstree('get_selected', true);
	$.each(checkbox, function(i, val) {
		if(i == 0) {
			// param += $(val).data('text');
			param += checkbox[i].id;
		}
		else {
			// param += ',' + $(val).data('text');
			param += ',' + checkbox[i].id;
		}
	});
	$("#menuTree").find(".jstree-undetermined").each(function (i, element) {
		param += ',' + $(element).closest('.jstree-node').attr("id");
	});

	$.ajax({
		type : "post",
		async : false,
		datatype : "text",
		url : "<c:url value='/admin/system/menuCreatInsert.do'/>",
		data : param,
		success : function(data) {
			swalAlert('success', '수정');
		}
	});

	// edit_modal close
	$('#reg_edit_modal a.close').trigger('click');

	// 권한별메뉴 리스트 그리기
	fncSearchCust();
}

</script>
<section id="Content" class="system_management">
    <div class="location">
        <ul>
            <li class="home"><a href="#">HOME</a></li>
            <li><a href="#">시스템관리</a></li>
            <li><a href="#">권한별메뉴관리</a></li>
        </ul>
    </div>
    <div class="sub_cont menu06_03_01">
        <div class="cont_box">
            <div class="box_title">
                <div class="fl">
                    <h2 class="mt12">권한별메뉴 조회</h2>
                </div>
                <div class="btn_wrap fr">
                	<a href="#" id="btnSearchCust" class="btn">조회</a>
                </div>
            </div>
            <div class="tbl">
                <table class="search">
                    <colgroup>
                        <col width="130px">
                        <col width="auto">
                    </colgroup>
                    <tbody>
                    <tr>
                        <th class="tl">권한코드</th>
                        <td class="tl">
                            <div class="ipt_box">
                                <input type="text" placeholder="권한코드를 입력해주세요." id="keyword" class="" onkeypress="return fncKeyPresshandler(event);">
                            </div>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="cont_box">
            <div class="box_title">
                <div class="fl">
                    <h2 class="mt12">권한별메뉴 리스트</h2>
                </div>
            </div>
            <div class="tbl">
            	<form id="custListForm">
	                <table id="listTable" class="">
	                    <colgroup>
	                        <col width="30%">
	                        <col width="25%">
	                        <col width="auto">
	                        <col width="110px">
	                    </colgroup>
	                    <thead>
	                    <tr>
	                        <th>권한코드</th>
	                        <th>권한명</th>
	                        <th>권한설명</th>
	                        <th>메뉴생성여부</th>
	                    </tr>
	                    </thead>
	                    <tbody>
	                    </tbody>
	                </table>
                </form>
            </div>
        </div>
    </div>
</section>

<!--  modal :: 권한별메뉴 수정 팝업  -->
<div class="modal" id="reg_edit_modal">
    <div class="modal_header">
        <h3>권한별메뉴 수정</h3>
    </div>
    <div class="modal_body">
        <div class="modal_cont">
	        <form id="editServiceInfo">
	            <dl>
	                <dt><h4><em class="">권한코드</em></h4></dt>
	                <dd>
	                    <div class="ipt_box">
	                        <input type="text" id="authCode" name="authCode" value="1" readonly>
	                    </div>
	                </dd>
	            </dl>
	            <dl class="">
	                <dt><h4><em class="important">서비스코드</em></h4></dt>
	                <dd>
	                    <div class="content tree">
	                        <div id="menuTree" class="tree_wrap">
	                            <ul>
	                                <li data-jstree='{ "opened" : true }'>root
	                                    <ul>
	                                        <li data-jstree='{ "opened" : true }'>주소BOT
	                                            <ul>
	                                                <li>지명 유사어 관리</li>
	                                                <li>빌딩 유사어 관리</li>
	                                                <li>유의어 전처리 관리</li>
	                                                <li>주소봇 멘트 관리</li>
	                                                <li>발화 건물유형 관리</li>
	                                                <li>주소 월별 업데이트</li>
	                                                <li>주소처리내역(녹취)</li>
	                                            </ul>
	                                        </li>
	                                        <li data-jstree='{ "opened" : true }'>BOT 공통 관리
	                                            <ul>
	                                                <li data-jstree='{ "opened" : true }'>서비스별관리
	                                                    <ul>
	                                                        <li>요일/시간대별 멘트 관리</li>
	                                                        <li>휴무일 관리</li>
	                                                        <li>자연어 전처리 관리</li>
	                                                    </ul>
	                                                </li>
	                                                <li>공통 코드 관리</li>
	                                            </ul>
	                                        </li>
	                                        <li data-jstree='{ "opened" : true }'>무인접수BOT
	                                            <ul>
	                                                <li>무인 접수 리스트</li>
	                                                <li>제품군 유의어 관리</li>
	                                            </ul>
	                                        </li>
	                                        <li data-jstree='{ "opened" : true }'>영상상담
	                                            <ul>
	                                                <li>컨텐츠등록 관리</li>
	                                                <li>영상상담</li>
	                                                <li>상담이력 조회</li>
	                                            </ul>
	                                        </li>
	                                    </ul>
	                                </li>
	                            </ul>
	                        </div>
	                    </div>
	                </dd>
                </dl>
            </form>
        </div>
    </div>
    <div class="modal_footer">
        <div class="btn_wrap fr">
            <a href="#" id="btnEditCust" class="btn">저장</a>
        </div>
    </div>
    <div class="modal_controller">
        <a href="#" class="close">close</a>
    </div>
</div>
<!--  modal :: 권한별메뉴 수정 팝업 end -->

</body>
</html>