var treeManager = null, gridManager0 = null,gridManager = null,gridManager1 = null,gridManager2 = null,gridManager3=null,gridManager4=null,thisGridManager=null,
refreshFlag = false, lastSelectedId = 0; nodeTypes = 0,passValidator=1,nodeName="";
var toolbarOptions =null;
$(document).ready(function () {
    initUI();
    initTree();
   
});

function initUI() {
    UICtrl.initDefaultLayout();
}

function initTree() {
    $('#maintree').commonTree({
        loadTreesAction: 'dbSettings/queryDbTables.ajax',
        idFieldName: 'id',
        onClick: function (data) {
            if (data && lastSelectedId != data.id) {
            	nodeTypes = data.type;
            	
                onFolderTreeNodeClick(data.id, data.name,data.type);
            }
        },
        IsShowMenu: false
    });
    initGridTemplate(0);
}

function onFolderTreeNodeClick(id, name,nodeType) {
	//alert(id+"===="+nodeType);
	$('#layout').layout('setCenterTitle',"当前节点：<span class='tomato-color'>[" + name + "]</span>");
    lastSelectedId = id;
    var params = $("#queryMainForm").formToJSON();
    params.parentId = id;
    params.nodeType = nodeType;   
    nodeName=name;
     if(nodeType == '0'){  //点击数据库分类 
    	initGridTemplate(id);
    	UICtrl.gridSearch(gridManager, params);
    	thisGridManager=gridManager;
     }else  if(nodeType == '1'){ // 点击指定分类
    	initiGridByType(id);
        UICtrl.gridSearch(gridManager1, params);
        thisGridManager=gridManager1;
     }else  if(nodeType == '2'){ // 点击指定表
    	 initiGridByFields(id);
    	 UICtrl.gridSearch(gridManager2, params);
    	 thisGridManager=gridManager2;
    }
    UICtrl.setSearchAreaToggle(thisGridManager);
}
//初始化分类Grid
function initGridTemplate(id) {
	var nodeTypes = parentNodeTypes(); 
	    toolbarOptions = UICtrl.getDefaultToolbarOptions({
        addProjectHandler: {id:'addProjectTemplate',img:'fa-plus',text:'新增分类',click:function(){
        	showAddModelClassDialog();
		}},	        	 
        updateHandler: showUpdateModelClassDialog,
        deleteHandler: function(){
	    	deleteModelClassHandler();
        }
	});	
	    
	    UICtrl.clearGridDiv('#maingrid');
    gridManager = UICtrl.grid('#maingrid', {
        columns: [
			{ display: "编码", name: "tableName", width: "20%", type: "string", align: "left",frozen:1 },
			{ display: "分类名称", name: "name", width: "30%", type: "string", align: "left" },
            { display: "版本号", name: "version", width: "20%", type: "int", align: "left"},
           // { display: "关联项目数", name: "projectNums", width: "10%", type: "int", align: "center"},
            { display: "状态", name: "status", width: "20%", type: "string", align: "center",
            	//render: UICtrl.getStatusInfo(item.status)
            	render: function (item) {
            		if(item.status==1){
            			return "启用";
            		}else if(item.status==0){
            			return "禁用";
            		}
    			}
            }],
        dataAction: 'server',
        url: web_app.name + '/dbSettings/slicedQueryDbTables.ajax',
        parms: { parentId: '1' ,nodeType:0},
        sortName: "tableName",
        sortOrder: "asc",
        toolbar: toolbarOptions,
        width: '99.8%',
        height: '100%',
        heightDiff: -8,
        checkbox: true,
        isMultiSelect: true,
        rownumbers: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onDblClickRow: function (data, rowindex, rowobj) {
            doShowUpdateDialog(data.id, data.hasChildren,data.nodeType);
        },
        onBeforeShowData:function(){
           // var g = parent.$("#maintree").ligerGetTreeManager();
            $('#maintree').commonTree('refresh','1');
        },
        onAfterShowData:function(){
            //var g = $("#maintree").ligerGetTreeManager();
        	//$("#"+'1',g.element).click();
        	//$('#maintree').commonTree('refresh','1');
        }
    });
    UICtrl.setSearchAreaToggle(gridManager);
    thisGridManager=gridManager;
}

function showAddModelClassDialog(){
	if (lastSelectedId==""){
		//Public.tip("请选择一个类别！");
		//return false;
		lastSelectedId="0";
	}
	 UICtrl.showAjaxDialog({
         title: "添加分类",
         param: {parentId: lastSelectedId},
         url: web_app.name + '/dbSettings/loadModelClassDetail.load',
         width: 800, height: 460,
         init: function () {
            // initAddMdmMetaData(folderId);
         },
         ok: doSaveModelClassData,
         close: onDialogCloseHandler
     }
 );
	
}
//保存方法 ;
function doSaveModelClassData() {
    var _self = this;
    var id = getId();
    var url = '/dbSettings/saveModelClassData.ajax';
  

    $('#modelClassForm').ajaxSubmit({
            url: web_app.name + url, success: function (data) {
            	gridManager.loadData();
                refreshFlag = true;
                _self.close();
            }
        }
    );
}
//修改业务类别  
function showUpdateModelClassDialog(){
	
	  var row = UICtrl.checkSelectedRows(gridManager);
 if (row) {
	 UICtrl.showAjaxDialog({
	        width: 800,
	        title: "修改类别:("+row.name+")",
	        url: web_app.name + '/dbSettings/loadModelClassDetail.load',
	        param: {parentId: row.parentId ,id:row.id},
	        init: function () {
	        	//$('#selectTemplate').hide();
	        	//initParams(id);
	        },
	        ok: doSaveModelClassData,
	        close: onDialogCloseHandler
	    });
	} else {
		Public.tip("请选择业务类别！")
	}
}
//删除模型分类 
function deleteModelClassHandler(){
	 var rows = UICtrl.checkSelectedRows(gridManager);
     var action = "/dbSettings/deleteModelClassData.ajax";
		  /*  $('#userTablesForm').ajaxSubmit({
			       url: web_app.name +action,
			       success: function (data) {
			    	  gridTableManager.loadData();
			       	  refreshFlag = true;
			         // _self.close();
			      }
			   }); */
		    DataUtil.delSelectedRows({
		        action: action,
		        idFieldName: 'id',
	        gridManager : gridManager,
		        onSuccess: function(){
		         gridManager.loadData();
		        }
		    });
}


//初始化表Grid
function initiGridByType(id){ 
	var nodeTypes = parentNodeTypes();
	toolbarOptions = UICtrl.getDefaultToolbarOptions({
		additionalHandler: {id:'projectprojectStageDetail',img:'fa-plus',text:'添加模型',click:function(){
			addUserTables();
		}},
		
		updateHandler: function(){
			editUserTales();
		},
	    deleteHandler: function(){
	    	deleteUserTales();
        },
		addphaseAttribute: {id:'addphaseAttribute',img:'fa-cog',text:'生成表',click:function(){
			generateTable();
		}}
    });
	UICtrl.clearGridDiv('#maingrid');
  gridManager1 = UICtrl.grid('#maingrid', {
        columns: [
			{ display: "表名称", name: "tableName", width: "25%", type: "string", align: "left" },
			{ display: "中文名称", name: "name", width: "28%", type: "string", align: "left" },
            { display: "描述", name: "", width: "30%", type: "string", align: "left"},
           // { display: "显示顺序", name: "sequence", width: "10%", type: "string", align: "center"},
            { display: "是否发布", name: "published", width: "10%", type: "string", align: "center"
            	  ,render: function (item) {
                     	var html="";
                     	if (item.published=="1"){
                     		html="已发布";
                      	} else {
                      		html="未发布";
                      	}
                     	  return  html;
            }}
           ],
        dataAction: 'server',
        url: web_app.name + '/dbSettings/slicedQueryDbTables.ajax',
        parms: { parentId: id ,nodeType:1},
        sortName: "sequence",
        sortOrder: "asc",
        toolbar: toolbarOptions,
        width: '99.8%',
        height: '100%',
        heightDiff: -8,
        checkbox: true,
        rownumbers: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onBeforeShowData:function(){
            // var g = parent.$("#maintree").ligerGetTreeManager();
             $('#maintree').commonTree('refresh',id);
         },
        onDblClickRow: function (data, rowindex, rowobj) {
            doShowUpdateDialog(data.id, data.hasChildren,data.nodeType);
        }
    });
    UICtrl.setSearchAreaToggle(gridManager1);
	
}

//初始化表Grid 字段列表 
function initiGridByFields(id){ 
	var nodeTypes = parentNodeTypes();
	var toolbarOptions2 = UICtrl.getDefaultToolbarOptions({
		additionalHandler: {id:'projectprojectStageDetail',img:'fa-plus',text:'添加字段',click:function(){
			addUserTables();
		}},
	//	addphaseAttribute: {id:'addphaseAttribute',img:'fa-cog',text:'生成代码',click:function(){
	//	    showInsertPhaseAttribute();
	//	}},
		//updateHandler: function(){
		//	editUserTales();
		//},
	    deleteHandler: function(){
	    	deleteHandler();
        }
    });
	  UICtrl.clearGridDiv('#maingrid');
    gridManager2 = UICtrl.grid('#maingrid', {
        columns: [
			{ display: "字段名称", name: "fieldCode", width: "20%", type: "string", align: "left" },
			{ display: "字段中文名称", name: "fieldName", width: "18%", type: "string", align: "left" },
			//{ display: "字段中文名称", name: "fieldName", width: "30%", type: "string", align: "left" },
			{ display: "字段类型", name: "fieldDataType", width: "15%", type: "string", align: "left" },
            { display: "字段长度", name: "fieldLength", width: "15%", type: "string", align: "left"},
           // { display: "是否隐藏", name: "isHidden", width: "10%", type: "string", align: "left"},
            { display: "显示顺序", name: "sequence", width: "10%", type: "string", align: "center"}
           ],
        dataAction: 'server',
        url: web_app.name + '/dbSettings/slicedQueryDbTablesFields.ajax',
        parms: { tableId: id ,nodeType:1},
        sortName: "nums",
        sortOrder: "asc",
        toolbar: toolbarOptions2,
        width: '99.8%',
        height: '100%',
        heightDiff: -8,
        checkbox: true,
        rownumbers: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onBeforeShowData:function(){
            // var g = parent.$("#maintree").ligerGetTreeManager();
             $('#maintree').commonTree('refresh',id);
         },
        onDblClickRow: function (data, rowindex, rowobj) {
            doShowUpdateDialog(data.id, data.hasChildren,data.nodeType);
        }
    });
    UICtrl.setSearchAreaToggle(gridManager2);
	
}



function generateTable(){
	var row = UICtrl.checkSelectedRows(gridManager1);
	//if(row&&row.needAudit==1&&row.status!=3){
	//	Public.tip("模型需要审批完成后才能发布！");
	//	return;
	//}
  if(row&&row.published==0){
	var url = '/dbSettings/publishToModelRecordTable.ajax?id='+row.id;
	  $('#submitForm').ajaxSubmit({
	       url: web_app.name +url,
	       param : {
				tableId : row.id,
			},
	       success: function (data) {
	    	   if (data.result!=""){
	    	       Public.tip("发布失败："+data.result);
	    	   } else {
                   Public.tip("发布成功！");
                   reloadMdmModelRecordGrid();
                }
	      }
	   });
	}else {
		Public.tip("模型已经发布，不能重复发布！")
	}
}


//添加用户表
function addUserTables(){
	  if (lastSelectedId == "") {
		  Public.tip("请选择业务类别!");
		   return false;
	  }
	  var _self = this;
	 UICtrl.showAjaxDialog({
		  title:'添加模型',
		  url: web_app.name +'/dbSettings/forwardUserTables.load',
		      param: {parentId:lastSelectedId},
		      width: 1100,
		      height:480,
		      init:function(){
		         initUserTables();
		      },
		     resize:true,
		   //  ok: doSaveUserTables,
		     ok:function(){
			    doSaveUserTables.call(this,lastSelectedId);
			 },
		    // close: onDialogCloseHandler 
		     	close: function(){
					_self.close();
				},
				cancel: true
		 });
	/*
	 UICtrl.showFrameDialog({
			title: "添加模型",
			width: 900,
			height: 500,
			  url: web_app.name +'/dbSettings/forwardUserTables.load?parentId='+lastSelectedId,
			ok:function(){
				doSaveUserTables.call(this,lastSelectedId);
			},
			close: function(){
				_self.close();
			},
			cancel: true
		});*/
	 

	 
}
//保存 选择的表
function doSaveUserTables(parentId){   

	//var rows = DataUtil.getGridData({gridManager:existMetaDataGridManager,isAllData:true});
	var rows=existMetaDataGridManager.data.Rows;
	//debugger;
	var _self = this;
	var url = "/dbSettings/saveUserTables.ajax";
   $('#userTablesForm').ajaxSubmit({
       url: web_app.name + url,
       param:{detailData1:encodeURI($.toJSON(rows)),id:$("#id").val()},
       success: function () {
           refreshFlag = true;
           gridManager2.loadData();
           _self.close();
       }
   });
//
}
//修改
function editUserTales() {
    var row = UICtrl.checkSelectedRows(gridManager1);
    if (row) {
        doShowUpdateUserTalesDialog(row.id, row.hasChildren,row.nodeType,row.name);
    }
}

function doShowUpdateUserTalesDialog(id,hasChildren,nodeType,name) {
    UICtrl.showAjaxDialog({
        width: 1100,
        title: "修改模型:("+name+")",
        url: web_app.name + '/dbSettings/forwardUserTables.load',
        param: {parentId: id ,nodeType: nodeType},
        init: function () {
        	$('#selectTemplate').hide();
        	initParams(id);
        },
        ok: doSaveUserTables,
        close: onDialogCloseHandler
    });
}

function initUserTables(){ 
} 

//删除字段 
function deleteHandler(){
	 var rows = UICtrl.checkSelectedRows(gridManager2);
		// alert(rows.buttonType);
		// if (rows.buttonType==2) {
		    var action = "/dbSettings/deleteUserTableFields.ajax";
		    DataUtil.delSelectedRows({
		        action: action,
		        idFieldName: 'tmid',
	        gridManager : gridManager2,
		        onSuccess: function(){
		         gridManager2.loadData();
		        }
		    });
	
}
	 
//删除表 
function deleteUserTales(){
	 var rows = UICtrl.checkSelectedRows(gridManager1);
	// alert(rows.buttonType);
	// if (rows.buttonType==2) {
	    var action = "/dbSettings/deleteUserTables.ajax";
	  /*  $('#userTablesForm').ajaxSubmit({
		       url: web_app.name +action,
		       success: function (data) {
		    	  gridTableManager.loadData();
		       	  refreshFlag = true;
		         // _self.close();
		      }
		   }); */
	    DataUtil.delSelectedRows({
	        action: action,
	        idFieldName: 'id',
        gridManager : gridManager1,
	        onSuccess: function(){
	         gridManager1.loadData();
	        }
	    });
	// }else {
	//	 Public.tip("只能删除自定义按钮!")
	//}
}

//生成表的实体 
function showInsertPhaseAttribute() {
	var row = UICtrl.checkSelectedRows(gridManager1);
    if (row) {
    	//var _url = web_app.name + '/propertydefine/forwardStagePropertydefine.do?parentCode='+row.code+'&parentName='+row.name+'&parentId='+row.parentId+'&nodeId='+row.id+'&nodeType='+row.nodeType;
    	//UICtrl.showAjaxDialog({
    	/*top.addTabItem({
    		text: '设置阶段属性', 
    		url: _url,
    	   });*/
    	
    	   Public.ajax(web_app.name + '/dbSettings/produceEntityCode.ajax', {
   	          id:row.id,tableName:row.tableName
   	       }, function (data) { //alert(data);
   		       alert(data);
   	        });
    }else {
        Public.tip('请选择表名！');
    }
}
function getId() {
    return $("#id").val() || "";
}
function parentNodeTypes() {
	return $("#parentNodeType").val() || "";
}

// 查询
function query(obj) {
    var param = $(obj).formToJSON();
    UICtrl.gridSearch(thisGridManager, param);
}

function reloadGrid() {
    gridManager.loadData();
}

// 重置表单
function resetForm(obj) {
    $(obj).formClean();
}

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