var gridManagerBtn = null, refreshFlag = false;
$(document).ready(function() {
	initUI();
	//initButtonGrid();
	 initFileclassGrid();
	 initExistFileclassGrid();
});

function initUI() {
	//UICtrl.initDefaultLayout();
	UICtrl.layout("#layout",{
		leftWidth:5,
		rightWidth:5,
		allowLeftCollapse: false, 
		allowRightCollapse: false,
		allowLeftResize: false,
		allowRightResize: false
	});
	//页面布局
	$(".ui-layout-center .btn.btn-primary").parent().parent().css("width","70px").parent().attr("align","center").each(function(){
		var _height = $(this).height();
		$(this).children("[position='center']").css("margin-top",(parseInt(_height)/2)+"px");
	});
	//去边框
	$("#layout").find('div.ui-layout-center>div.ui-layout-warp').css('border',0);
	
	//判断表单编号是否存在
	 $('#formNo').onFocus();
	 $('#formNo').bind('blur', function (e) {
	       var formNo=this.value;
	       var url=web_app.name + '/safFormslist/getExistFormNo.ajax';
	        Public.ajax(url ,{id:$("#id").val(),formNo:this.value},
	    	        function (data) {
	      	       if (data.flag==1){
	         	       UICtrl.alert("当前编号"+formNo+"已经存在！");
	          	       $('#formNo').val();
	      	       }
	         }); 
	    });
}


function getId(){
	return $("#id").val() || "";
}

function addCustomButton(){
	
	 UICtrl.showAjaxDialog({
		  title:'添加自定义按钮',
		  url: web_app.name +'/safForms/loadCustomButtonDetail.load',
		      param: {id:$('#id').val(),tableName:$("#tableName").val()},
		      width: 800,
		      height:300,
		      init:function(){
		         initCustomButton();
		      },
		     ok: doSaveCustomButton,
		     close: onDialogCloseHandler 
		 });
}
//保存 选择的按钮
function saveHandler(){
	 var rows = gridManagerBtn.getSelectedRows();
	var _self = this;
	var url = "/syfForms/saveFormButtonLists.ajax";
    $('#syfFormsForm').ajaxSubmit({
        url: web_app.name + (url),
        param:{detailData1:encodeURI($.toJSON(rows)),id:$("#id").val(),tableName:$("#tableName").val()},
        success: function () {
            refreshFlag = true;
            gridManagerBtn.loadData();
           // _self.close();
        }
    });
 //
}
 
function initCustomButton(){ 
} 
	 
//保存自定义按钮方法
function doSaveCustomButton(){
	 var _self = this;
	   var id = getId();
	   var url = '/syfForms/saveCustomButton.ajax';
	  $('#customButtonForm').ajaxSubmit({
	       url: web_app.name +url,
	       success: function (data) {
	      	  reloadGrid();
	       	  refreshFlag = true;
	          _self.close();
	      }
	   });
	 }

//删除自定义按钮 
function deleteHandler(){
	 var rows = UICtrl.checkSelectedRows(gridManagerBtn);
	 //alert(rows.buttonType);
	 if (rows.buttonType==2) {
	    var action = "/syfForms/deleteCustomButton.ajax?buttonValue="+rows.buttonValue+"&buttonName="+rows.buttonName;
	    $('#syfFormsForm').ajaxSubmit({
		       url: web_app.name +action,
		       success: function (data) {
		      	  reloadGrid();
		       	  refreshFlag = true;
		         // _self.close();
		      }
		   });
	  /*  DataUtil.delSelectedRows({
	        action: action,
	        idFieldName: 'id',
        gridManager : gridManagerBtn,
	        onSuccess: reloadGrid
	    });*/
	 }else {
		 Public.tip("只能删除自定义按钮!")
	 }
}
function reloadGrid() {
   gridManagerBtn.loadData();
}
//关闭对话框
function onDialogCloseHandler() {
    if (refreshFlag) {
        reloadGrid();
        refreshFlag = false;
    }
}

//***********************************************88*****8
function initFileclassGrid() {
	    fileclassGridManager = UICtrl.grid('#projectFileClassListGrid', {
	        columns: [
	            { display: "表名称", name: "tableName", width: 180, minWidth: 80, type: "string", align: "left"},
	        	{ display: "中文名称", name: "name", width: 130, minWidth: 80, type: "string", align: "left"},
	        //	{ display: "字段类型", name: "fieldDataType", width: 120, minWidth: 60, type: "string", align: "left"},
				//{ display: "文件类别编码", name: "fileclassCode", width: 90, minWidth: 60, type: "string", align: "left"},
	        	//{ display: "长度", name: "stage", width: 82, minWidth: 80, type: "string", align: "left" }
				 { display: "", name: "parentId",hide: true},
		         { display: "", name: "id",hide: true}
	         ],
	        dataAction: 'server',
	        url: web_app.name + '/safFormslist/queryAlternativeTableLists.ajax',
	        //toolbar: toolbarOptions,
	        sortName: "id",
	        sortOrder: "asc",
	        autoAddRowByKeydown : false,
	        width: '99.8%',
	        height: '380px',
	        heightDiff: -1,
	        usePager:true,
	        pageSize:10,
	        checkbox: true,
	        onBeforeCheckRow:function(flag,data){
	        	//if (data.status==0){
	        	//	UICtrl.alert("当前数据被禁用，不能选择!");
	    	     //   return false;
	              // }
	        	return true;
	        },
	        onDblClickRow : function(row){ //实现双击进入另一个grid中
				var g=this,gridManagers=["fileclassGridManager","existfileclassGridManager"];
				g.selected = []; //清空selected 避免多次选中
				g.select(row);
				gridManagers.splice($.inArray(g.element.id,gridManagers),1); //筛选被加入的gridManager
				UICtrl.moveSelectedRowsToOtherGrid(fileclassGridManager,existfileclassGridManager);
			},
			 onAfterShowData:function () {// alert(3); alert($(".l-grid-header-inner"));
		  		  $(".l-grid-header-inner")[1].style="width:336px";
		 		},
	        rownumbers: false,
	        enabledEdit: false,
	        fixedCellHeight: true,
	        selectRowButtonOnly: true,
	    });
	    UICtrl.setSearchAreaToggle(fileclassGridManager);
		
	}

	function initExistFileclassGrid(){
		existfileclassGridManager = UICtrl.grid('#projectExistFileClassListGrid', {
	        columns: [
	            { display: "表名称", name: "tableName", width: 140, minWidth: 60, type: "string", align: "left"},
	        	{ display: "中文名称", name: "name", width: 90, minWidth: 60, type: "string", align: "left"},
	        	//{ display: "字段类型", name: "fieldDataType", width: 90, minWidth: 60, type: "string", align: "left"},
	        	//{ display: "*顺序号", name: "nums", width: 60, type: "int", align: "left",
				//	editor: { type:'text',required:true,mask:'999',maxLength:'3'}
				//},
				{ display: "*类型", name: "tableTypeTextView", width: 80, minWidth: 60, type: "string", align: "left" 
					,editor: { type:'dictionary',data:{name:'tableType'},textField:'tableTypeTextView',valueField:'tableType'}
				},
				{ display: "", name: "parentId",hide: true},
		         { display: "", name: "id",hide: true}
	         ],
	        dataAction: 'server',
	        url: web_app.name + '/safFormslist/querySelectedTableLists.ajax',
	        parms:{id:getId()},
	        sortName: "parentId",
	        sortOrder: "asc",
	        pageSize:100,
	        width: '99.8%',
	        height: '90%',
	        isScroll:true,
	        heightDiff: -1,
	        onDblClickRow : function(row){ //实现双击进入另一个grid中
				var g=this,gridManagers=["existfileclassGridManager","fileclassGridManager"];
				g.selected = []; //清空selected 避免多次选中
				g.select(row);
				gridManagers.splice($.inArray(g.element.id,gridManagers),1); //筛选被加入的gridManager
				UICtrl.moveSelectedRowsToOtherGrid(existfileclassGridManager,fileclassGridManager);
			},
			 onAfterShowData:function () {// alert(3); alert($(".l-grid-header-inner"));
			  		  $(".l-grid-header-inner")[3].style="width:340px";
			 },
	        checkbox: true,
	        rownumbers: true,
	        enabledEdit: true,
	        fixedCellHeight: true,
	        selectRowButtonOnly: true,
	    });	
	}
	//左表向右表移动
	function addData(){
		var leftData=fileclassGridManager.getSelecteds();		
		if(leftData){
			for(var i=0;i<leftData.length;i++){
				if(leftData[i].status==0){
					Public.tip('不能选择禁用的数据!');
					return;
				}
			}	
			UICtrl.moveSelectedRowsToOtherGrid(fileclassGridManager,existfileclassGridManager);
		}else{
			Public.tip('请选择左侧功能!');
			return;
		}
		
	}
	//右表向左表移动
	function deleteData(){
		var rightData=existfileclassGridManager.getSelecteds();
		if(rightData){
			UICtrl.moveSelectedRowsToOtherGrid(existfileclassGridManager,fileclassGridManager);
			//moveSelectedRowsToOtherGridByTree(existfileclassGridManager,fileclassGridManager);
		}else{
			Public.tip('请选择右侧功能!');
			return;
		}
		
	}
	//右表全部删除，并移动到左表
	function doDeleteAll(){
		var records = existfileclassGridManager.records;
		existfileclassGridManager.selected = []; //清空selected 避免多次选中
		for (var rowid in records){
			existfileclassGridManager.select(records[rowid]); //循环遍历全选
		}
		UICtrl.moveSelectedRowsToOtherGrid(existfileclassGridManager,fileclassGridManager);	
	}

	

