var metaDataGridManager = null,existMetaDataGridManager,refreshFlag = false;
$(document).ready(function () {
    initUI();
    bindEvent();
    initMetaDataGrid();
    initExistMetaDataGrid();
});

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);
}

function bindEvent(){
	$('#tableName').bind('blur',function(e){
		/*var $clicked = $(e.target || e.srcElement);
		if($clicked.is('a.GridStyle')){
			$('div.divChoose',this).removeClass('divChoose');
			var id=$clicked.attr('id'),name=$.trim($clicked.text()),fileKind=$clicked.attr('fileKind');
			viewAttachment(id,name,fileKind);
			$clicked.parent().addClass('divChoose');
		}*/
		if  (this.value!=""){
		  Public.ajax(web_app.name + '/dbSettings/findExistTableName.ajax', {
   	          id:getId(),tableName:this.value
   	        }, function (data) { //alert(data);
   		       if (data.result!=""){
     		     Public.tip("警告："+data.result); 
     		     $('#tableName').val("");
     		     return false;
   		       }
   	        });
	    }
	});
}
function initMetaDataGrid() {
   
    metaDataGridManager = UICtrl.grid('#metaDataListGrid', {
        columns: [
            { display: "字段名称", name: "fieldCode", width: 130, minWidth: 60, type: "string", align: "left"},
        	{ display: "中文名称", name: "fieldName", width: 120, minWidth: 60, type: "string", align: "left"},
        	{ display: "字段类型", name: "fieldDataType", width: 100, 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 + '/dbSettings/queryAlternativeMetaLists.ajax',
        //toolbar: toolbarOptions,
        sortName: "id",
        sortOrder: "asc",
        autoAddRowByKeydown : false,
        width: '99.8%',
        height: '400px',
        heightDiff: -1,
        usePager:true,
        checkbox: true,
        onBeforeCheckRow:function(flag,data){
        	//if (data.status==0){
        	//	UICtrl.alert("当前数据被禁用，不能选择!");
    	     //   return false;
              // }
        	return true;
        },
        onDblClickRow : function(row){ //实现双击进入另一个grid中
			var g=this,gridManagers=["metaDataGridManager","existMetaDataGridManager"];
			g.selected = []; //清空selected 避免多次选中
			g.select(row);
			gridManagers.splice($.inArray(g.element.id,gridManagers),1); //筛选被加入的gridManager
			UICtrl.moveSelectedRowsToOtherGrid(metaDataGridManager,existMetaDataGridManager);
		},
		 onAfterShowData:function () {// alert(3); alert($(".l-grid-header-inner"));
	  		  $(".l-grid-header-inner")[1].style="width:336px";
	 		},
        rownumbers: true,
        enabledEdit: false,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
    });
    UICtrl.setSearchAreaToggle(metaDataGridManager);
	
}

function initExistMetaDataGrid(){
	existMetaDataGridManager = UICtrl.grid('#existMetaDataListGrid', {
        columns: [
            { display: "字段名称", name: "fieldCode", width: 110, minWidth: 100, type: "string", align: "left"},
        	{ display: "中文名称", name: "fieldName", width: 100, minWidth: 90, type: "string", align: "left"},
        	{ display: "字段类型", name: "fieldDataType", width: 90, minWidth: 80, type: "string", align: "left"},
          	{ display: "*顺序号", name: "nums", width: 70, type: "int", align: "left",
				editor: { type:'text',required:true,mask:'999',maxLength:'3'}
			},
			//{ display: "状态", name: "statusTextView", width: 40, minWidth: 30, type: "string", align: "left" }
			{ display: "", name: "parentId",hide: true},
	         { display: "", name: "id",hide: true}
         ],
        dataAction: 'server',
        url: web_app.name + '/dbSettings/querySelectedMetaLists.ajax',
        parms:{tableId:getId()},
        sortName: "parentId",
        sortOrder: "asc",
        pageSize:100,
        width: '99.8%',
        height: '90%',
        isScroll:true,
        heightDiff: -1,
        onDblClickRow : function(row){ //实现双击进入另一个grid中
			var g=this,gridManagers=["existMetaDataGridManager","metaDataGridManager"];
			g.selected = []; //清空selected 避免多次选中
			g.select(row);
			gridManagers.splice($.inArray(g.element.id,gridManagers),1); //筛选被加入的gridManager
			UICtrl.moveSelectedRowsToOtherGrid(existMetaDataGridManager,metaDataGridManager);
		},
		 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=metaDataGridManager.getSelecteds();		
	if(leftData){
		for(var i=0;i<leftData.length;i++){
			if(leftData[i].status==0){
				Public.tip('不能选择禁用的数据!');
				return;
			}
		}	
		UICtrl.moveSelectedRowsToOtherGrid(metaDataGridManager,existMetaDataGridManager);
	}else{
		Public.tip('请选择左侧功能!');
		return;
	}
	
}
//右表向左表移动
function deleteData(){
	var rightData=existMetaDataGridManager.getSelecteds();
	if(rightData){
		UICtrl.moveSelectedRowsToOtherGrid(existMetaDataGridManager,metaDataGridManager);
		//moveSelectedRowsToOtherGridByTree(existfileclassGridManager,fileclassGridManager);
	}else{
		Public.tip('请选择右侧功能!');
		return;
	}
	
}
//右表全部删除，并移动到左表
function doDeleteAll(){
	var records = existMetaDataGridManager.records;
	existMetaDataGridManager.selected = []; //清空selected 避免多次选中
	for (var rowid in records){
		existMetaDataGridManager.select(records[rowid]); //循环遍历全选
	}
	UICtrl.moveSelectedRowsToOtherGrid(existMetaDataGridManager,metaDataGridManager);	
}



function reloadGrid() {
	var params = $("#queryForm").formToJSON();
    UICtrl.gridSearch(metaDataGridManager, params);
    //fileclassGridManager.loadData();
}

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

function getTaskPropertyId(){
	return $("#taskPropertyId").val() || "";
}

function getTaskId(){
	return $("#taskId").val() || "";
}
function initReadOnly(){
	$('input,select,textarea', $('form[name="projectFileClassListForm"]')).attr('readonly', true);
	$("#ok").hide();
}

/*function getSelectData(){
	// var rows = UICtrl.checkSelectedRows(fileclassGridManager);
	 debugger
	 var rows = fileclassGridManager.getSelecteds();
	  if (rows) {
	      return rows;   	
	  } else {
		  return "";
	  }
}*/
//获取右表的数据
function getCheckedData(){
	var data = DataUtil.getGridData({gridManager:existMetaDataGridManager,isAllData:true});
	if(data){
		return data;
	}else{
		return "";
	}
	
}


//关闭对话框
function onDialogCloseHandler() {
    if (refreshFlag) {
        reloadGrid();
        refreshFlag = false;
    }
}


//使用方法相当于eval
Public.eval = function(fn) {
	var Fn = Function; // 一个变量指向Function，防止有些前端编译工具报错
	return new Fn('return ' + fn)();
}
//查询
function query(obj) {
    var param = $(obj).formToJSON();
    UICtrl.gridSearch(metaDataGridManager, param);
}
//重置查询条件
function resetForm(obj) {
    $(obj).formClean();
}