/**
 * admin/vers
 */
var mplus_admin_manager = function(){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//변수
	var $sltUser = $('#sltUser'),
		$txtSearch = $('#txtSearch'),
		$btnSearch = $('#btnSearch'),
		$txtUserId = $('#txtUserId'),
		$txtUserOrder = $('#txtUserOrder'),
		$sltHospital = $('#sltHospital'),
		$sltDuty = $('#sltDuty'),
		$sltWork = $('#sltWork'),
		$btnNew = $('#btnNew'),
		$btnSave = $('#btnSave'),
		
		div = $('<div></div>'),
		span = $('<span></span>'),
		label = $('<label></label>'),
		button = $('<button></button>'),
				
		$crudServiceBaseUrl = contextPath + "/admin/userAttr",
		$crudServiceAttrUrl = contextPath + "/admin/attr";

	

	var workList = [];
	var userInfo;
	var userList = [];
	var userAttrList = [];
	var totalCount = '';
	var pageSize = 15;
	/**
	 * 초기화
	 */
	this.init = function(){
		initUserAttrList(1, '', '');
		initDropDown();
		addEvent();
		if($('#table_user tr')[0]==undefined){
			$('#userAttrDetail').css('display', 'none');
			$('#userAttrDetailEmpty').css('display', 'block');
		}else{
			$('#table_user tr')[0].click();
		};
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		$btnNew.on('click', function(e){
			newUserAttr(e);
		});
		
		$sltDuty.on('change', function(e){
			selectWorkChange(e);
		});
		
		$btnSave.on('click', function(e){
			saveUserAttr(e);
		});
		
		$btnSearch.on('click', function(e){
			initUserAttrList(1, $sltUser.val(), $txtSearch.val());
		});
	};
	
	var initUserAttrList = function(page, selectType, searchText){
		$('#divUserAttr').empty();
		$('#noUserAttr').css('display', 'block');
		$('#divUserAttr').css('display', 'none');
		
		userList = [];
		userAttrList = [];
		
		var opt = {
				url: $crudServiceBaseUrl + "/getList.json",
				type: "post",
				dataType: "json",
				async: false,
				contentType: "application/json",
				data: self.util.stringifyJson({
					pageSize: pageSize, 
					page: page, 
                    selectUserType: selectType, 
                    searchText: searchText, 
                    hospitalId: "", 
                    dutyId: "", 
                    workId: ""
				})
			};
		var success = function(result){
    		userList = result.data;
    		totalCount = result.totalCount;
    		$('#table_user').empty();
    		for(var i=0; i<userList.length; i++){
    			var tr = $('<tr></tr>').clone().attr('seq', i).attr('userId', userList[i].userId);
    			var tdUserId = $('<td></td>').clone().text(userList[i].userId);
    			var tdUserName = $('<td></td>').clone().text(userList[i].userName);
    			
    			$('#table_user').append(tr.append(tdUserId).append(tdUserName));    			
    		};
    		$('#table_user tr').on('click', function(e){
				getUserAttrList(e.currentTarget.attributes.seq.value);
				$('#table_user tr').removeClass('active');
				$(this).addClass('active');
			})
    		
    		if(page<11){
                $('#ulPagination').empty();
                if(totalCount>0){
                    for(j=0; j<Math.ceil(totalCount/pageSize); j++ ){ 
                        if(j<10){
                        	var li = $('<li></li>').clone();
                			var a = $('<a></a>').clone().attr('seq', j+1).text(j+1);
                			var span = $('<span></span>').clone().addClass('sr-only');
                			
                			$('#ulPagination').append(li.attr('id', 'page_'+(j+1)).append(a.append(span)));
                        }else if(j==10){
                        	$('#ulPagination').append('<li id="next_'+(j+1)+'"><a href="#">>></a></li>');
                            $('#next_'+(j+1)).on('click', function(e){
                            	next(e);
                            });
                        }else {};
                    };
                }else{
                	var li = $('<li></li>').clone();
        			var a = $('<a></a>').clone().attr('seq', 1).text(1);
        			var span = $('<span></span>').clone().addClass('sr-only');
        			
        			$('#ulPagination').append(li.attr('id', 'page_'+(1)).append(a.append(span)));
                };
            };
            
            $('#ulPagination li[id*="page_"]').removeClass('active');
            if($('#page_'+page)!=null) $('#page_'+page).addClass('active');
            
            $('#ulPagination li[id*="page_"]').unbind();
            $('#ulPagination li[id*="page_"]').on('click', function(e){
            	initUserAttrList(Number(e.currentTarget.id.split('_')[1]), '', '');
            });
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
	
	  var previous = function(e){
	    	var startNo = Number(e.currentTarget.id.split('_')[1]);
	        if(startNo>Math.ceil(totalCount/pageSize)) return;
	        $('#ulPagination').empty();
	        
	        if(startNo-10>1){
	            $('#ulPagination').append('<li id="previous_'+(startNo-10)+'"><a href="#"><<</a></li>');
	            $('#previous_'+(startNo-10)).on('click', function(e){
	            	previous(e);
	            });
	        };
	        
	        for(i=startNo-10; i<startNo; i++){
	            $('#ulPagination').append('<li id="page_'+i+'"><a href="#">'+i+'</a></li>');
	            $('#ulPagination li[id*="page_"]').unbind();
	            $('#ulPagination li[id*="page_"]').on('click', function(e){
	            	initUserAttrList(Number(e.currentTarget.id.split('_')[1]), '','');
	            });
	            if((startNo)==(i+1)){
	                $('#ulPagination').append('<li id="next_'+(i+1)+'"><a href="#">>></a></li>');
	                $('#next_'+(i+1)).on('click', function(e){
	                	next(e);
	                });
	            };
	        };
	    };
	    
	    var next = function(){
	    	 var startNo = Number(event.currentTarget.id.split('_')[1]);
	         if(startNo>Math.ceil(totalCount/pageSize)) return;
	         $('#ulPagination').empty();
	         
	         $('#ulPagination').append('<li id="previous_'+startNo+'"><a href="#"><<</a></li>');
	         $('#previous_'+startNo).on('click', function(e){
	         	previous(e);
	         });
	         
	         for(i=startNo; i<startNo+10; i++){
	             if(i>Math.ceil(totalCount/pageSize)) return;
	             $('#ulPagination').append('<li id="page_'+i+'"><a href="#">'+i+'</a></li>');
	             $('#ulPagination li[id*="page_"]').unbind();
	             $('#ulPagination li[id*="page_"]').on('click', function(e){
	            	 initUserAttrList(Number(e.currentTarget.id.split('_')[1]), '', '');
	             });
	             
	             if((startNo+10)==(i+1) && i!=Math.ceil(totalCount/pageSize)){
	                 $('#ulPagination').append('<li id="next_'+(i+1)+'"><a href="#">>></a></li>');
	                 $('#next_'+(i+1)).on('click', function(e){
	                 	next(e);
	                 });
	             };
	         };
	    };
	
	
	var initDropDown = function(){
		var opt = {
				url: $crudServiceAttrUrl + "/getAttrTypeList.json",
				type: "post",
				dataType: "json",
				contentType: "application/json"
			};
		var success = function(result){
			for(var i=0; i<result.attrTypeList.length; i++){
				var attrOpt = {
						url: $crudServiceAttrUrl + "/getAttrList.json",
						type: "post",
						dataType: "json",
						async: false,
						contentType: "application/json",
						data: self.util.stringifyJson({
		                    attrType: result.attrTypeList[i].attrType
						})
					};
				var attrSuccess = function(attrResult){
					if(result.attrTypeList[i].attrType=='hospital'){
						for(var j=0; j<attrResult.attrList.length; j++){
							var option = $('<option></option>').clone().attr('value', attrResult.attrList[j].attrId).text(attrResult.attrList[j].attrName);
							$sltHospital.append(option);
						};
					}else if(result.attrTypeList[i].attrType=='duty'){
						for(var j=0; j<attrResult.attrList.length; j++){
							var option = $('<option></option>').clone().attr('value', attrResult.attrList[j].attrId).text(attrResult.attrList[j].attrName);
							$sltDuty.append(option);
						};
					}else if(result.attrTypeList[i].attrType=='work'){
						workList = attrResult.attrList;
					}else{
						
					};
				};
				var attrError = function(xhr,d,t){
		    		console.log(xhr);
					console.log(t);
		    	};
		    	self.ajaxAdmin( attrOpt, attrSuccess, attrError );
			}
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	}
	
	var getUserAttrList = function(seq){
		userInfo = userList[seq];
		
		$('#userAttrDetail').css('display', 'block');
		$('#userAttrDetailEmpty').css('display', 'none');
		
		var opt = {
				url: $crudServiceBaseUrl + "/getUserAttrList.json",
				type: "post",
				dataType: "json",
				contentType: "application/json",
				data: self.util.stringifyJson({
                    userId: userInfo.userId
				})
			};
		
		var success = function(result){
			$('#divUserAttr').empty();
			userAttrList = result;
			if(result.length==0){
				$('#noUserAttr').css('display', 'block');
				$('#divUserAttr').css('display', 'none');
			}else{
				$('#noUserAttr').css('display', 'none');
				$('#divUserAttr').css('display', 'block');
				for(var i=0; i<result.length; i++){	
					var attrWrapper = div.clone().addClass('form-group col-md-4');
					var attrPanel = div.clone().addClass('panel panel-default');
					var attrPanelBody = div.clone().addClass('panel-body');
					
					var attrItemButton = button.clone().addClass('user-attr-remove').attr('id', 'btnUserAttr_' + i).append(span.clone().addClass('glyphicon glyphicon-remove'));
					
					var attrItemWrapper = div.clone().addClass('form-group col-md-12');
					var attrItemDetail = div.clone().addClass('col-md-4 text-center pd0');
					var attrItemDetail2 = div.clone().addClass('col-md-8 text-center');
					
					var attrItemHospital = attrItemWrapper.clone().append(attrItemDetail.clone().append(label.clone().text('소속'))).append(attrItemDetail2.clone().append(span.clone().text(result[i].hospitalName==null? '':result[i].hospitalName)));
					var attrItemDuty = attrItemWrapper.clone().append(attrItemDetail.clone().append(label.clone().text('직무'))).append(attrItemDetail2.clone().append(span.clone().text(result[i].dutyName==null? '': result[i].dutyName)));
					var attrItemWork = attrItemWrapper.clone().append(attrItemDetail.clone().append(label.clone().text('업무'))).append(attrItemDetail2.clone().append(span.clone().text(result[i].workName==null? '': result[i].workName)));
					
					var attrItem = attrWrapper.clone().attr('id', 'userAttrOrder_'+result[i].userAttrOrder).append(attrPanel.clone().append(attrPanelBody.clone().append(attrItemButton).append(attrItemHospital).append(attrItemDuty).append(attrItemWork)));
					
					$('#divUserAttr').append(attrItem);
				};
				
				$('#userAttrOrder_'+userInfo.useAttrOrder).addClass('use-attr-order');
				
				$('[id*=btnUserAttr_').on('click', function(e){
					removeUserAttr(e);
				});
				
			};
			
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
	
	var newUserAttr = function(){
		$txtUserId.val(userInfo.userId);
		$txtUserOrder.val(userInfo.userAttrOrder);
		$sltHospital.val('');
		$sltDuty.val('');
		$sltWork.val('');
		
		$('#addAttrModal').modal('show');
		
		$('#addAttrModal').on('shown.bs.modal', function () {
			$sltHospital.focus();
		});
	};
	
	var saveUserAttr = function(){
		var opt = {
				url: $crudServiceBaseUrl + "/save.json",
				type: "post",
				dataType: "json",
				async: false,
				contentType: "application/json",
				data: self.util.stringifyJson({
                    userId: userInfo.userId,
                    userAttrOrder: $('[id*=userAttrOrder_]').length+1,
                    hospitalId: $sltHospital.val(),
                    dutyId: $sltDuty.val(),
                    workId: $sltWork.val()
				})
			};
		
		var success = function(result){
			$('#addAttrModal').modal('hide');
			if(userInfo.useAttrOrder==0 && confirm('해당 속성을 사용자의 선택속성으로 변경하시겠습니까?')){
				var changeAttrOpt = {
						url: $crudServiceBaseUrl + "/changeUserAttr.json",
						type: "post",
						async: false,
						contentType: "application/json",
						data: self.util.stringifyJson({
		                    userId: userInfo.userId,
		                    useAttrOrder: $('[id*=userAttrOrder_]').length+1
						})
					};
				var changeAttrSuccess = function(result){
					initUserAttrList(Number($('#ulPagination li.active')[0].id.split('_')[1]), '', '');
					
					$('#table_user tr[userId="'+userInfo.userId+'"]').click();
		    	};
		    	var changeAttrError = function(xhr,d,t){
		    		console.log(xhr);
					console.log(t);
		    	};
		    	self.ajaxAdmin( changeAttrOpt, changeAttrSuccess, changeAttrError );
			};
			initUserAttrList(Number($('#ulPagination li.active')[0].id.split('_')[1]), '', ''); //요거바꿔야함!!필수!!!!!!!!!!!!!!!!!!!!!★★★★★★★★★★★★★★★★★★★★★
			$('#table_user tr[userId="'+userInfo.userId+'"]').click();
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
	};
		
	var removeUserAttr = function(e){
		if(confirm('해당속성을 삭제하시겠습니까?')){
			var attrSeq = e.currentTarget.id.split('_')[1];
			var attrInfo = userAttrList[attrSeq];
			var opt = {
					url: $crudServiceBaseUrl + "/remove.json",
					type: "post",
					dataType: "json",
					async: false,
					contentType: "application/json",
					data: self.util.stringifyJson({
	                    userId: attrInfo.userId,
	                    userAttrOrder: attrInfo.userAttrOrder,
	                    hospitalId: attrInfo.hospitalId,
	                    dutyId: attrInfo.dutyId,
	                    workId: attrInfo.workId
					})
				};
			
			var success = function(result){
				initUserAttrList(Number($('#ulPagination li.active')[0].id.split('_')[1]), '', '');
				$('#table_user tr[userId="'+userInfo.userId+'"]').click();
	    	};
	    	var error = function(xhr,d,t){
	    		console.log(xhr);
				console.log(t);
	    	};
	    	self.ajaxAdmin( opt, success, error );
		};
	};
	
	var selectWorkChange = function(e){
		var temWorkList=[];
		for(var i=0; i<workList.length; i++){
			if(e.currentTarget.value==workList[i].upperAttr){
				temWorkList.push(workList[i]);
			};
		};
		$sltWork.empty();
		var option = $('<option></option>').clone().attr('value', '').text('선택');
		$sltWork.append(option);
		
		for(var j=0; j<temWorkList.length; j++){
			var option = $('<option></option>').clone().attr('value', temWorkList[j].attrId).text(temWorkList[j].attrName);
			$sltWork.append(option);
		};
	};
};
