/**
 * admin/category
 */
var mplus_admin_category = function(){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//변수
	var $wrapper = $(".main-wrapper #wrapper"),
		$btnCreateNode = $("#btnCreateNode"),
		$btnSaveNode = $("#btnSaveNode"),
		$btnRemoveNode = $("#btnRemoveNode"),
		$btnDeselectNode = $("#btnDeselectNode"),
		$categoryTreeView = $("categoryTreeView"),
		$txtId = $("#txtId"),
		$txtName = $("#txtName"),
		$txtUri = $("#txtUri"),
		$spanUri = $("#spanUri"),
		$txtCategoryDesc = $("#txtCategoryDesc"),
		$spanCreateDt = $("#spanCreateDt"),
		$spanCreateId = $("#spanCreateId"),
		$spanUpdateDt = $("#spanUpdateDt"),
		$spanUpdateId = $("#spanUpdateId"),
		$crudServiceBaseUrl = contextPath + "/admin/category";
	//tree
	var $tree;
	/**
	 * 초기화
	 */
	this.init = function(){
		initTree();
		addEvent();
		/*if($("#categoryTreeView .fancytree-expander")[0]!=undefined){
			$('#categoryTreeView').fancytree('getTree').getNodeByKey($("#categoryTreeView .fancytree-expander")[0].id).setActive();
		};*/
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		//아이템 추가
		$btnCreateNode.on("click",function(e){
			addItem(e);
		});
		//아이템 저장
		$btnSaveNode.on("click",function(e){
			saveItem(e);
		});
		//아이템 삭제
		$btnRemoveNode.on("click",function(e){
			removeItem(e);
		});
		//아이템 선택 해제
		$btnDeselectNode.on("click",function(e){
			deselectItem();
		});
	};
	/**
	 * 아이템 추가 이벤트
	 */
	var addItem = function(e){
		/*
		addedNodeCheck( e, treeView.dataSource.data().toJSON() );
		
		if( addedNodeArr.length > 0 ) {
			alert( "저장하지 않은 아이템 [ " + addedNodeArr[0].catName + " ] (이)가 있습니다" );
			addedNodeArr = [];
			return false;
		}*/
		if($("#categoryTreeView").fancytree("getActiveNode")!=null){
	        var node = $("#categoryTreeView").fancytree("getActiveNode"),
			item = $("#categoryTreeView").fancytree("getActiveNode").data,
			parentCatSeq = item.catSeq;
	        
	        if(node.expanded==undefined){
				$("#categoryTreeView").fancytree("getActiveNode").setExpanded();
			};
		}else{
			var node = $("#categoryTreeView").fancytree("getRootNode"),
			parentCatSeq = '';
		};
		
    	var nodeData = null,
    		defData = {
    			catSeq : null,
    			parentCatSeq : parentCatSeq,
    			catName : 'NewItem',
    			catDesc : null,
    			childCount : 0,
    			addedNode : true,
    			pathName : ""
  		};
    	
    	node.addChildren({
    		title: defData.catName,
        	key: defData.catSeq,
        	folder: false,
        	lazy: false,
        	data: defData}
        );
    	addedNodeArr.push( defData );
    	if(node.children.length==1){
    		$("#categoryTreeView").fancytree("getActiveNode").setExpanded();
    	};
        node.children[node.children.length-1].li.click();
        $txtName.focus();
	};
	/**
	 * 아이템 저장 이벤트
	 */
	var saveItem = function(e){
		var node = $("#categoryTreeView").fancytree("getActiveNode"),
	    	item = $("#categoryTreeView").fancytree("getActiveNode").data,
			pnode = node.parent.data;

		var paramItem = {};
		if(item.addedNode==true){
			paramItem = {
				catSeq: null,
				catName: $txtName.val(),
				pathName: $txtUri.val(),
				parentPath : $spanUri.text(),
				catDesc: $txtCategoryDesc.val(),
				childCount : 0,
				parentCatSeq: pnode.catSeq
			}
		}else{
			paramItem = item;
			paramItem.catName = $txtName.val();
			paramItem.pathName = $txtUri.val();
			paramItem.catDesc = $txtCategoryDesc.val();
			paramItem.parentPath = $spanUri.text();
		};
		
		if( paramItem.catName === null || paramItem.catName === "" ) {
			alert( "이름을 입력해주세요." );
			return false;
		}
		
		if( paramItem.pathName === null || paramItem.pathName === "" ) {
			alert( "카테고리 URI를 입력해주세요." );
			return false;
		};

		var regExp = /^[a-z0-9_-]{2,16}$/;
		if( !regExp.test( paramItem.pathName ) ) {
			alert( "카테고리 URI는 소문자나 숫자, 언더스코어, 하이픈을 포함할 수 있고 2byte이상 15byte이하만 가능합니다" );
			return false;
		}

		var opt = {
				url : $crudServiceBaseUrl + "/save.json",
				type : "POST",
				data : self.util.stringifyJson( paramItem ),
				dataType : "json",
				contentType : "application/json;charset=utf-8"
    	};
    	var success = function(data){
    		alert("저장 되었습니다");
    		addedNodeArr = [];
			var saveItemData = $('#categoryTreeView').fancytree('getActiveNode');
			$('#title'+saveItemData.key).text(data.catName);
			saveItemData.data = data;
    		/*location.reload(true);*/
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(xhr.responseText);
    	};
    	self.ajaxAdmin( opt, success, error );
    	addedNodeArr = [];
	};
	/**
	 * 아이템 삭제 이벤트
	 */
	var removeItem = function(e){
		var node = $("#categoryTreeView").fancytree("getActiveNode"),
	    item = $("#categoryTreeView").fancytree("getActiveNode").data;
		
		if( node.length === 0 ) {
			alert( "선택한 아이템이 없습니다" );
			return false;
		};
		

		if( item.addedNode === true ) {
			node.remove();
			addedNodeArr = [];
			
			$('#categoryDetail').css('display', 'none');
			$('#categoryDetailEmpty').css('display', 'block');
			return false;
		};

		if( item.childCount > 0 ) {
			alert( "하위 카테고리가 존재하여 삭제할 수 없습니다" );
			return false;
		};

		if( item.apiCount > 0 ) {
			alert( "하위 API가 존재하여 삭제할 수 없습니다" );
			return false;
		};

		if( !confirm("삭제 하시겠습니까?") ) {
			return false;
		}

		var opt = {
				url : $crudServiceBaseUrl + "/remove.json",
				type : "POST",
				data : { catSeq : item.catSeq }
    	};
    	var success = function(data){
    		alert("삭제 되었습니다");
    		$('#categoryTreeView').fancytree('getActiveNode').remove();
			/*location.reload(true);*/
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(xhr.responseText);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
	/**
	 * 트리 초기화
	 */
	 var createDeptNodeData = function(data) {
	        return $.extend({
	            title : data.catName,
	            key : data.catSeq,
	            folder : data.childCount>0? true: false,
	            lazy : data.childCount>0? true: false,
	            data : data
	        }, data);
	    };
	
	var initTree = function(){
		$tree = $("#categoryTreeView").fancytree({
                	extensions: ["edit"],
	                lazyLoad : function(event, ctx) {         	
		            	var param_lazyload = {
		            			async: false,
		            			url : $crudServiceBaseUrl + "/getList.json",
		            			dataType : 'json',
		            			type : 'POST',
		            			data: {catSeq: ctx.node.data.catSeq}
		            	};
		            	result = [];
		            	var success_lazyload = function(data){
		            		categorytList = data;
		            		
		                	for ( var i in categorytList) {
		                        var item = categorytList[i];
		                        result.push(createDeptNodeData(item));
		                    };
		                    ctx.result = result;
		                    
		            	};
		            	var error_lazyload = function(xhr,d,t){
		            		console.log(xhr);
		        			console.log(t);
		            	};
		            	self.ajaxAdmin( param_lazyload, success_lazyload, error_lazyload );
	                },
		            selectMode : 3,
		            activate : function(event, ctx) {
		            	var categoryData = ctx.node.data;
		            	var parentUrl = '';
		            	var parentData = ctx.node.parent;
		            	if(parentData.title!='root'){
			            	do{
			            		parentUrl = parentData.data.pathName + '/' + parentUrl;
			            		parentData = parentData.parent;
			            	}while(parentData.parent!=null);
		            	};
		            	$spanUri.text('/'+parentUrl);
		            	if(categoryData.catSeq==undefined){
		            		$txtId.val('');
		            		$txtName.val('');
		            		$txtUri.val('');
		            		$txtCategoryDesc.val('');
		            		$spanCreateDt.text('');
		            		$spanCreateId.text('');
		            		$spanUpdateDt.text('');
		            		$spanUpdateId.text('');
		            	}else{
		            		var opt = {
		            				url : $crudServiceBaseUrl + "/getCategory.json",
		            				type : "POST",
		            				data : self.util.stringifyJson( {'catSeq': categoryData.catSeq,
		            					'pathName': categoryData.pathName} ),
		            				dataType : "json",
		            				contentType : "application/json;charset=utf-8"
		                	};
		                	var success = function(data){
		                		$txtId.val(data.catSeq);
				            	$txtName.val(data.catName);
				            	$txtUri.val(data.pathName);
				            	$txtCategoryDesc.val(data.catDesc);
				            	$spanCreateDt.text(moment(data.createDt).format('YYYY-MM-DD'));
			            		$spanCreateId.text(data.createId==null? '': data.createId);
			            		$spanUpdateDt.text(moment(data.updateDt).format('YYYY-MM-DD'));
			            		$spanUpdateId.text(data.updateId==null? '':data.updateId);
		                	};
		                	var error = function(xhr,d,t){
		                		console.log(xhr);
		            			console.log(xhr.responseText);
		                	};
		                	self.ajaxAdmin( opt, success, error );
		            	};
		            	$('#categoryDetail').css('display', 'block');
		    			$('#categoryDetailEmpty').css('display', 'none');
		            }
                }).fancytree('getTree');
		var deptList;
		$.ajax({
			async : false,
			url : $crudServiceBaseUrl + "/getList.json",
			dataType : 'json',
			type : 'POST',
			contentType : 'application/json',
			success : function(result){
				categoryList = result;
			}
		});
		
    	var $root = $tree.getRootNode();
        for ( var i in categoryList) {
            var item = categoryList[i];
            $root.addNode(createDeptNodeData(item));
        }
	};
	
	var deselectItem = function(e){
		var node = $("#categoryTreeView").fancytree("getActiveNode");
		if(node!=undefined){
		    node.setActive(false);
		    node.setFocus(false);
		
		    $txtId.val('');
	  		$txtName.val('');
	  		$txtUri.val('');
	  		$txtCategoryDesc.val('');
	  		$spanCreateDt.text('');
	  		$spanCreateId.text('');
	  		$spanUpdateDt.text('');
	  		$spanUpdateId.text('');
	  		
	  		$('#categoryDetail').css('display', 'none');
			$('#categoryDetailEmpty').css('display', 'block');
		};
	};
	
	// 저장하지 않은 아이템 확인
	var addedNodeArr = [];
	function addedNodeCheck( e, treeViewData ) {
		if( treeViewData ) {
			for( var n = 0; n < treeViewData.length; n++) {
				 var childData = treeViewData[n];
				 if( childData.addedNode === true ) {
					 addedNodeArr.push(childData);
					 return;

				} else {
					var child = childData.items;
					if (child) {
						if (child.length > 0) {
							addedNodeCheck(e, child);
						}
					}
				}
			}
		}
	};
	/**
	 *  선택된 노드의 부모경로 가져오기
	 */
	var getTotalPath = function(node){
		var treeView = self.treeView,
			totalPathName = "",
			//현재 선택된 노드 모델 정보
			item = treeView.dataItem( node );

		var cat_seq = item.catSeq;
		var cat_name = item.catName;
		var cat_path_name = "";
		
		cat_path_name = "";
		//부모있으면
		while ( item.parentNode() ) {
			//있을 때까지 부모로 설정해서 경로를 만듬
			item = item.parentNode();
			cat_path_name = item.pathName + "/" + cat_path_name;
		}
		//부모경로가 없으면 '/' 있으면 '/ + 부모경로'
		return totalPathName = (cat_path_name !== ""?"/" + cat_path_name : "/");
	};
};
