/**
 * admin/vers
 */
var mcare_admin_manager = function(){
	//상속
	mcare_admin.call(this);
	
	var self = this;
	//변수
	var $grid = $("#grid"),
		$searchBtn = $("#searchBtn"),
		$searchText = $("#search-text"),
		$selectHospital = $("#select-hospital"),
		$selectDuty = $("#select-duty"),
		$selectWork = $("#select-work"),
		$selectUser = $("#select-user"),
		
		$btnAttrCreate = $("#btnAttrCreate"),
		$btnPopAddLine = $("#btnPopAddLine"),
		$btnPopAddLineCancel = $('#btnPopAddLineCancel'),
		
		$crudServiceBaseUrl = contextPath + "/admin/userAttr";
	
	// 검색 조건 데이터
	var selectHospitalVal;
	var selectDutyVal;
	var selectWorkVal;
	var selectUserType;
	var userVal;
	/**
	 * 초기화
	 */
	this.init = function(){
		initGrid();
		initDropDown();
		addEvent();
	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
		$searchBtn.on("click", function(e) {
	        searchUserAttr(e);
	    });
		$selectHospital.on("change", function(e) {
			selectHospitalVal = $selectHospital.val();
		});
		$selectDuty.on("change", function(e) {
			selectDutyVal = $selectDuty.val();
		});
		$selectWork.on("change", function(e) {
			selectWorkVal = $selectWork.val();
		});

		$btnAttrCreate.on("click", function(e){
			attrPopupOpen();
		});
		
		$btnPopAddLine.on("click", function(e){
			popAddLine();
		});
		$btnPopAddLineCancel.on("click", function(e){
			popAddLineCancel();
		});
	};
	var hospitalList;
	var dutyList;
	var workList;
	var searchTypeList;
	var initDropDown = function(){
		$.ajax ({
			  url : '/mcare-plus/admin/attr/getAttrTypeList.json',
			  type : 'POST',
			  success: function(result){
				  hospitalList = result.hospital;
				  dutyList = result.duty;
				  workList = result.work;
				  searchTypeList = [{attrId: 'userId', attrName: '아이디'},{attrId: 'userName', attrName: '이름'}];
				  $selectHospital.kendoDropDownList({
					  dataSource: hospitalList,
					  dataTextField: "attrName",
					  dataValueField: "attrId",
					  optionLabel: {
						  attrId: "",
						  attrName: "전체"
					  }
					}).data("kendoDropDownList").select(0);
				  $selectDuty.kendoDropDownList({
					  dataSource: dutyList,
					  dataTextField: "attrName",
					  dataValueField: "attrId",
					  optionLabel: {
						  attrId: "",
						  attrName: "전체"
					  },
					  change: selectWorkChange
					}).data("kendoDropDownList").select(0);
				  $selectWork.kendoDropDownList({
					  dataSource: workList,
					  dataTextField: "attrName",
					  dataValueField: "attrId",
					  optionLabel: {
						  attrId: "",
						  attrName: "전체"
					  }
					}).data("kendoDropDownList").select(0);
				  $selectUser.kendoDropDownList({
					  dataSource: searchTypeList,
					  dataTextField: "attrName",
					  dataValueField: "attrId",
					  optionLabel: {
						  attrId: "",
						  attrName: "전체"
					  }
					}).data("kendoDropDownList").select(0);
			  }
			 })
	}
	function selectWorkChange(e){
		var temWorkList=[];
		for(var i=0; i<workList.length; i++){
			if($selectDuty.val()==workList[i].upperAttr){
				temWorkList.push(workList[i]);
			};
		};
		$("#select-work").kendoDropDownList({
			  dataSource: temWorkList,
			  dataTextField: "attrName",
			  dataValueField: "attrId",
			  optionLabel: {
				  attrId: "",
				  attrName: "전체"
			  },
			  change: selectWorkChange
			}).data("kendoDropDownList").select(0);
		
	}
	
	// 데이터소스	
	var dataSource = new kendo.data.DataSource({
	        transport: {
	        	read: function(options) {
	                $.ajax({
	                    url: $crudServiceBaseUrl + "/getList.json",
	                    method: "POST",
	                    dataType: "json",
	                    contentType : "application/json",
	                    data: self.util.stringifyJson( {
	                    	"take":options.data.take,
	                    	"skip":options.data.skip,
	                    	"page":options.data.page,
	                    	"pageSize":options.data.pageSize,
	                    	"sort":options.data.sort,
	                    	"hospitalId":$("#select-hospital").val(),
	                    	"dutyId":$("#select-duty").val(),
	                    	"workId":$("#select-work").val(),
	                    	"selectUserType":$("#select-user").val(),
	                    	"searchText":$("#search-text").val()
	                    	}),
	            		success: function(result) {
	                        options.success(result);
	                    	gridReadComplete(result);
	                      }
	                });
	            },
				update: function(options) {
					console.log(options.data.models[0]);
					var updateData = options.data.models[0];
					$.ajax({
	                    url: $crudServiceBaseUrl + "/save.json",
	                    method: "POST",
	                    dataType: "json",
	                    contentType : "application/json",
	                    data: self.util.stringifyJson({
	                    	"userId": updateData.userId,
	                    	"userName": updateData.userName,
	                    	"userAttrOrder": updateData.userAttrOrder,
	                    	"hospitalId": updateData.hospitalId,
	                    	"dutyId": updateData.dutyId,
	                    	"workId": updateData.workId,
	                    	"addedNode": updateData.addedNode==undefined? false: updateData.addedNode,
	                    	}),
	            		success: function(result) {
	            			alert('저장되었습니다');
	                        options.success(result);
	                    	gridActionComplete(result);
	                    }
	                });
	            },
				destroy: function(options) {
					console.log(options);
					var deleteData = options.data.models[0];
					if(deleteData.userAttrOrder==1){
						alert('사용자는 최소 하나의 속성을 가져야 합니다.');
						$("#grid").data("kendoGrid").cancelChanges();
						return;
					};
					if(deleteData.addedNode!=true){
						$.ajax ({
							  url : $crudServiceBaseUrl + "/remove.json",
							  type : 'POST',
							  data: self.util.stringifyJson({
			                    	"userId": deleteData.userId,
			                    	"userAttrOrder": deleteData.userAttrOrder
			                    	}),
			            		success: function(result) {
			            			if(result.msg==undefined){
			            				alert('삭제되었습니다');
				                        options.success(result);
				                    	gridActionComplete(result);
			            			}else{
			            				alert(result.msg);
			            				$("#grid").data("kendoGrid").cancelChanges();
			            			}
			                     }
						})
					};
	            }
	        },
	        batch: true,
	        pageSize: 13,
	        serverPaging: true,
	        serverSorting: true,
	        schema: {
	            data: "data",
	            total: "totalCount",
	            model: {
					id: "rnum",
					fields: {
						userId: { type: "string", nullable: false, editable: false, validation: { required: true }},
						userName: { type: "string", nullable: false, editable: false, validation: { required: true }},
						userAttrOrder: { type: "string", nullable: false, editable: false, validation: { required: true }},
						hospitalId: { type: "string", nullable: false, validation: { required: true }},
						hospitalName: { type: "string" },
						dutyId: { type: "string", nullable: false,validation: { required: true }},
						dutyName: { type: "string" },
						workId: { type: "string", nullable: false, validation: { required: true }},
						workName: { type: "string" }
					}
				}
	        }
	    });
	/**
	 * 그리드 이벤트 동작 complate
	 * @private
	 */
	function gridActionComplete( result ){
		if(result.msg !=undefined){ 
			alert(result.msg);
		}else{
			$grid.data("kendoGrid").dataSource.read();
		};
	};
	/**
	 * 그리드 이벤트 동작 complate
	 * @private
	 */
	function gridReadComplete( result ){
		if(result.msg !=undefined){ 
			alert(result.msg);
			if( result.type == "AuthException" ){
				window.location.href = contextPath + "/admin/logout.page";
				return;
			}	
		};
	};
    /**
     * 그리드 초기화
     */
    var initGrid = function(){
    	// 그리드 옵션
    	var grid = $("#grid").kendoGrid({
            dataSource: dataSource,
            pageable: true,
            sortable: true,
            resizable: true,
            height: 620,
            columns: [
                 { field: "userId", title: "아이디", width: 80, attributes: {style: "text-align: center;"}}
                ,{ field: "userName", title: "이름", width: 100, attributes: {style: "text-align: center;"}}
                ,{ field: "userAttrOrder", title: "순서", width: 50, attributes: {style: "text-align: center;"}}
                ,{ field: "hospitalId", title: "소속", width: 120, attributes: {style: "text-align: center;"}, editor: hospitalDropDownEditor, template: "#=hospitalName#"}
                ,{ field: "dutyId", title: "직무", width: 120, attributes: {style: "text-align: center;"}, editor: dutyDropDownEditor, template: "#=dutyName#"}
                ,{ field: "workId", title: "업무", width: 80, attributes: {style: "text-align: center;"}, editor: workDropDownEditor, template: "#=workName#"}
                ,{ command: [{name:"edit",text:{edit: "편집", update: "저장", cancel: "취소"}},{name:"destroy",text:"삭제"}], title: "&nbsp;", width: 170, attributes: {style: "text-align: center;"}}
            ],
            editable: {
            	mode: "inline",
            	confirmation:"정말 삭제하시겠습니까?"
            },
            edit: function(e) {                
                if (!e.model.isNew()) {
                  	/*$("select[id=pop-select-hospital]").parent().hide();*/
                  	
    			}else{
    	            /*var editWindow = this.editable.element.data("kendoWindow");
    	            $('.k-edit-form-container').css('width', '580px');
    				editWindow.wrapper.css({top: "20%" });    				
    				$("div[id=createDataBox]").hide();*/
    			}
            },
            change: function(data, arg){
            	$('input[name=attrAddUser]').removeAttr("checked");
            	$('input[name=attrAddUser]')[$(this.select()).index()].checked=true
            	var selected = this.select(),
                item = this.dataItem(selected);
            	createData = item;
            },
            dataBound: function () {
                var rowCount = $grid.find( ".k-grid-content tbody tr" ).length;
                if( rowCount < dataSource._take ) {
                    var addRows = dataSource._take - rowCount;
                    for( var i = 0; i < addRows; i++ ) {
                         $grid.find( ".k-grid-content tbody" )
                            .append( "<tr class='kendo-data-row'><td>&nbsp;</td></tr>" );
                    }
                }
                $('.k-grid-edit', grid.element).on("click", function () {
                	//추가할 데이터가 저장되지 않은 경우
                	if($('#grid .k-grid-edit-row').length>0
                			&&$('#grid').data("kendoGrid").dataSource.data()[0].addedNode==true){
        	    		alert('저장하지 않은 데이터가 있습니다.' );
        	    		return false;
        	    	};
                });
            }
    	}).data("kendoGrid");
        
        /*$('.k-grid-add', grid.element).on("click", function () {
            // Temporarily set editable to "popup"
        	if($(".k-grid-cancel").length>0){
        		$(".k-grid-cancel").click();
        	};
            grid.options.editable = {
                	mode: "popup",
                	template: $('#popTemplate').html()
                };
        });*/
    };
    function hospitalDropDownEditor(container, options) {
        $('<input required name="' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                autoBind: false,
                dataTextField: "attrName",
                dataValueField: "attrId",
                dataSource: hospitalList,
                optionLabel: {
  				  attrId: "",
  				  attrName: "선택"
                  }
              }).data("kendoDropDownList").select(0);
    };
    
    function dutyDropDownEditor(container, options) {
        $('<input required name="' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                autoBind: false,
                dataTextField: "attrName",
                dataValueField: "attrId",
                change: selectChangeDuty,
                dataSource: dutyList,
                optionLabel: {
  				  attrId: "",
  				  attrName: "선택"
                  }
              }).data("kendoDropDownList").select(0);
    };
    function selectChangeDuty(e){
    	var options= {model:{dutyId: e.sender._selectedValue}};
    	var container = $('.k-grid-edit-row [data-container-for=workId]');
    	
    	var temWorkList=[];
    	for(var i=0; i<workList.length; i++){
    		if(options.model.dutyId==workList[i].upperAttr){
    			temWorkList.push(workList[i]);
    		};
    	};
    	container.find('input').data("kendoDropDownList").dataSource.data(temWorkList);
    };
    function workDropDownEditor(container, options) {
    	var temWorkList=[];
    	for(var i=0; i<workList.length; i++){
    		if(options.model.dutyId==workList[i].upperAttr){
    			temWorkList.push(workList[i]);
    		};
    	};
    	
        $('<input required name="' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                autoBind: false,
                dataTextField: "attrName",
                dataValueField: "attrId",
                dataSource: temWorkList,
                optionLabel: {
  				  attrId: "",
  				  attrName: "선택"
                  }
              }).data("kendoDropDownList").select(0);
    };
    
    function searchUserAttr(e) {
    	$grid.data("kendoGrid").dataSource.read(); 
    };
    
	
	/**
	 * 그리드 이벤트 동작 complate
	 * @private
	 */
	function popGridActionComplete( result ){
		if(result.msg !=undefined){ 
			alert(result.msg);
		}else{
			$('#grid3').data("kendoGrid").dataSource.read();
		};
	};
	/**
	 * 그리드 이벤트 동작 complate
	 * @private
	 */
	function popGridReadComplete( result ){
		if(result.msg !=undefined){ 
			alert(result.msg);
			if( result.type == "AuthException" ){
				window.location.href = contextPath + "/admin/logout.page";
				return;
			}	
		};
	};
	
	
    /**
     * 그리드 초기화
     */
    var popInitGrid = function(){
    	// 그리드 옵션
        var option = {
            dataSource: popDataSource,
            pageable: true,
            sortable: true,
            resizable: true,
            selectable: true,
            height: 400,
            columns: [
                 { title: "", width: 30, template: '<input type="radio" name="attrAddUser"/>'}
                ,{ field: "userId", title: "아이디", width: 80, attributes: {style: "text-align: center;"}}
                ,{ field: "userName", title: "이름", width: 100, attributes: {style: "text-align: center;"}}
                ,{ field: "userAttrOrder", title: "순서", width: 50, hidden: true, attributes: {style: "text-align: center;"}}
                ,{ field: "hospitalId", title: "소속ID", width: 120, hidden: true, attributes: {style: "text-align: center;"}}
                ,{ field: "hospitalName", title: "소속", width: 120, attributes: {style: "text-align: center;"}}
                ,{ field: "dutyId", title: "직무ID", width: 120, hidden: true, attributes: {style: "text-align: center;"}}
                ,{ field: "dutyName", title: "직무", width: 120, attributes: {style: "text-align: center;"}}
                ,{ field: "workId", title: "업무ID", width: 80, hidden: true, attributes: {style: "text-align: center;"}}
                ,{ field: "workName", title: "업무", width: 80, attributes: {style: "text-align: center;"}}
            ],
            change: function(data, arg){
            	$('input[name=attrAddUser]').removeAttr("checked");
            	$('input[name=attrAddUser]')[$(this.select()).index()].checked=true
            	var selected = this.select(),
                item = this.dataItem(selected);
            	createData = item;
            },
            dataBound: function () {
                var rowCount = $('#grid3').find( ".k-grid-content tbody tr" ).length;
                if( rowCount < popDataSource._take ) {
                    var addRows = popDataSource._take - rowCount;
                    for( var i = 0; i < addRows; i++ ) {
                         $('#grid3').find( ".k-grid-content tbody" )
                            .append( "<tr class='kendo-data-row'><td>&nbsp;</td></tr>" );
                    }
                }
            }
        };
        //그리드 초기화
        self.grid( $('#grid3'), option );
    };
    
    var popDataSource = new kendo.data.DataSource({
	        transport: {
	            read: {
	                url: $crudServiceBaseUrl + "/getList.json",
	                method: "post",
	                dataType: "json",
	                contentType: "application/json",
	                complete: popGridReadComplete
	            },
	            parameterMap: function parameterMap( options, operation ){
	    			kendo.ui.progress($("#grid3"), true);
	    			var param = $.extend(true, {}, options, {
	    				hospitalId: $('#pop-select-hospital').val(),
	    				dutyId : $('#pop-select-duty').val(),
	    				workId : $('#pop-select-work').val(),
	    				selectUserType : $('#pop-select-user').val(),
	    				searchText : $('#pop-search-text').val(),
	    				userAttrOrder: "1"
	                }, null);
	    			console.log(self.util.stringifyJson( param ));
	            	return self.util.stringifyJson( param );
	    		}
	        },
	        pageSize: 10,
	        serverPaging: true,
	        serverSorting: true,
	        schema: {
	            data: "data",
	            total: "totalCount",
	            model: {
					id: "rnum",
					fields: {
						userId: { type: "string", nullable: false, validation: { required: true }},
						userName: { type: "string", nullable: false, validation: { required: true }},
						userAttrOrder: { type: "string", nullable: false, validation: { required: true }},
						hospitalId: { type: "string", nullable: false, validation: { required: true }},
						dutyId: { type: "string", nullable: false,validation: { required: true }},
						workId: { type: "string", nullable: false, validation: { required: true }}
					}
				}
	        }
	    });
    
    
	    function popSearchUserAttr(e) {
	    	popDataSource.page(1);
	    }
	    
	    function setWidth(el)
	    {
	    	var d = el;
	        if (d.data("kendoDropDownList") !== undefined) {
	            var p = d.data("kendoDropDownList").popup.element;
	            var w = p.css("visibility", "hidden").show().outerWidth() + 20;
	            p.hide().css("visibility", "visible");
	            var kw = d.closest(".k-widget");
	            if (kw.width() < w) {
	                d.data("kendoDropDownList").list.width(100);
	            }
	        }
	    }
	    
	    function attrPopupOpen(e){
	    	if($('#grid .k-grid-edit-row').length>0){
	    		alert('저장하지 않은 데이터가 있습니다.' );
	    		return;
	    	};
	    	 popInitGrid();
			 $("#pop-search").on("click", function(e) {
			    	popSearchUserAttr(e);
			    });
			    $("#pop-select-hospital").width(100).kendoDropDownList({
				    dataSource: hospitalList,
				    dataTextField: "attrName",
		            dataValueField: "attrId",
		            optionLabel: {
		            	attrName: "전체",
		                attrId: ""
		            }
			    }).data("kendoDropDownList").select(0);
			  $("#pop-select-duty").width(100).kendoDropDownList({
				    dataSource    : dutyList,
				    dataTextField: "attrName",
		            dataValueField: "attrId",
		            optionLabel: {
		            	attrName: "전체",
		                attrId: ""
		            }
			  }).data("kendoDropDownList").select(0);
			  $("#pop-select-work").width(100).kendoDropDownList({
				    dataSource    : workList,
				    dataTextField: "attrName",
		            dataValueField: "attrId",
		            optionLabel: {
		            	attrName: "전체",
		                attrId: ""
		            }
			  }).data("kendoDropDownList").select(0);
			  $("#pop-select-user").width(100).kendoDropDownList({
				    dataSource    : searchTypeList,
				    dataTextField: "attrName",
		            dataValueField: "attrId",
		            optionLabel: {
		            	attrName: "전체",
		                attrId: ""
		            }
			  }).data("kendoDropDownList").select(0);
	    	
	    	$("#attrCreatePop").kendoWindow({
	                modal: true,
	                title: "사용자 속성 추가",
	                width:600,
	                position:{
	                    top:"15%",
	                    left:"35%"
	                }
	    	}).data("kendoWindow").center().open();
	    	
	    };
	    
	    function popAddLine(e){
	    	$('#grid').data("kendoGrid").dataSource.insert(0, {
	    		"dutyId" : "",
	    		"dutyName" : "",
	    		"hospitalId" : "",
	    		"hospitalName": "",
	    		"id": createData.userId,
	    		"userAttrOrder": createData.lastOrder+1,
	    		"userId": createData.userId,
	    		"userName": createData.userName,
	    		"workId": "",
	    		"workName": "",
	    		"addedNode": true
	    	});
	    	$('.k-grid-edit')[0].click();
	    	$("#attrCreatePop").data("kendoWindow").close();
	    	
	    	$('.k-grid-cancel').on('click', function(e){
	    		$('#grid').data("kendoGrid").dataSource.remove($('#grid').data("kendoGrid").dataSource.data()[0]);
	    	});
	    };
	    
	    function popAddLineCancel(e){
	    	$("#attrCreatePop").data("kendoWindow").close();
	    }
};
