var gridManager_formprompt = null, gridManager_easysearch=null,gridManager_checkfunction=null,gridManager_procduce=null,refreshFlag = false
$(document).ready(function() {
	initUI();
	init_formprompt();
	init_easysearch();
	init_checkfunction();
	init_procduce();
	initializateTab();	
});

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

function initializateTab(){
	 $('#tabPage').tab().bind('click', function (e) {
       var $clicked = $(e.target || e.srcElement);
       if ($clicked.is('li')) {
           var divid = $clicked.attr('divid');
           var div = $('#' + divid);
           curr_gridManager=divid.substr(4);
           eval("var gridName" + "=eval(gridManager_" + curr_gridManager+")");
          if (eval(gridName)==null){ 
             doCallFunc(eval("init_"+curr_gridManager),[]);
           } else {
             doCallFunc(eval("reloadGrid_"+curr_gridManager),[]);
          }
           div.show();
       }
   });
}
//表单提示配置列表 
function init_formprompt() {
	
	 var toolbarOptions =[];
	  toolbarOptions = UICtrl.getDefaultToolbarOptions({
		setFormBaseAttribute: {id:'setFormBaseAttribute',img:'fa-cog',text:'添加',click:function(){
			addCustomButton();
		}},
	   saveHandler:saveHandler,
	   deleteHandler:deleteHandler
	   });

	  gridManager_formprompt = UICtrl.grid('#dli_formprompt', {
		checkbox: true,
		columns : [ 
		    { display: "提示名称", name: "parmName", width: 220, type: "string", align: "left"},
			{ display: "提示编码", name: "parmCode", width: 200, type: "string", align: "left"},
			
           	{ display: "提示内容", name: "parmVals", width:220, type: "string", align: "left"}
			
	     ],
		dataAction : 'server',
		toolbar: toolbarOptions,
		url : web_app.name + '/safFormslist/slicedQueryFormParameter.ajax',
		parms : {
			formNo:$('#formNo').val(),parmType:1
	     },
		sortOrder : "asc",
		width : '99.8%',
		height : '88%',
		heightDiff : -8,
		pageSize:20,
		checkbox : true,
		enabledEdit: false,
		rownumbers : true,
		fixedCellHeight : true,
		selectRowButtonOnly : true,
		isChecked: f_isChecked,
	});
	function f_isChecked(data)
    {
        if (data.seled == 1){
        	return true;
        } 
        return false;
    }
	UICtrl.setSearchAreaToggle(gridManager_formprompt);
}
//检索SQL列表 
function  init_easysearch(){
	
	 var toolbarOptions =[];
	  toolbarOptions = UICtrl.getDefaultToolbarOptions({
         addFormSearchSQL: {id:'addFormSearchSQL',img:'fa-plus',text:'添加',click:function(){
			addFormSearchSQL();
		 }},
	    editFormSearchSQL: {id:'editFormSearchSQL',img:'fa-edit',text:'编辑',click:function(){
		     editFormSearchSQL();
		 }},
	     deleteHandler:deleteSearchSQLHandler
	   });

	  gridManager_easysearch = UICtrl.grid('#dli_easysearch', {
		checkbox: true,
		columns : [ 
		    { display: "检索描述", name: "searchDesc", width: 100, type: "string", align: "left"},
			{ display: "检索名称", name: "searchName", width: 150, type: "string", align: "left"},
			{ display: "关联表", name: "tableName", width: 100, type: "string", align: "left"},
			{ display: "关联字段", name: "targetField", width: 70, type: "string", align: "left"},
			{ display: "列显示名称", name: "fieldNames", width: 180, type: "string", align: "left"},
			//{ display: "列显示字段", name: "fieldCodes", width: 180, type: "string", align: "left"},
			{ display: "接收字段名称", name: "backFields", width: 180, type: "string", align: "left"},
			{ display: "值变量来源字段", name: "paramSourceFields", width: 180, type: "string", align: "left"}
			//{ display: "说明", name: "remark", width: 160, type: "string", align: "left"}
	     ],
		dataAction : 'server',
		toolbar: toolbarOptions,
		url : web_app.name + '/safFormslist/slicedQueryFormParameter.ajax',
		parms : {
			formNo:$('#formNo').val(),parmType:2
	     },
		sortOrder : "asc",
		width : '99.8%',
		height : '88%',
		heightDiff : -2,
		pageSize:20,
		checkbox : true,
		enabledEdit: false,
		rownumbers : true,
		fixedCellHeight : true,
		selectRowButtonOnly : true,
		isChecked: f_isChecked,
	});
	function f_isChecked(data)
    {
     if (data.seled == 1){
     	return true;
     } 
     return false;
     }
	UICtrl.setSearchAreaToggle(gridManager_easysearch);
}
/*****************************检索SQL的方法*********************************************************/

//设置数据来源内容：
function addFormSearchSQL(){
	//alert(id);
	//var url=web_app.name + '/taskproperty/showProcessPropertyDetail.do';
	 UICtrl.showAjaxDialog({
	        title: "添加表单【"+$("#formNo").val()+"】的检索SQL：",
		    url: web_app.name + '/safFormslist/loadDataSourceDetail.load',
	        param: {id:'',formNo:$("#formNo").val()},
	        width: 900,
	       // ok: doSaveDataSource,
	        button:nextButton,
	        ok:false,
	        close: onDialogCloseHandler
	    });
}
function  editFormSearchSQL(){
	 var row = UICtrl.checkSelectedRows(gridManager_easysearch);
	  if (row) {
		  UICtrl.showAjaxDialog({
		        title: "设置字段数据来源：",
			    url: web_app.name + '/safFormslist/loadDataSourceDetail.load',
		        param: {id:row.id,formNo:$("#formNo").val()},
		        width: 900,
		       // ok: doSaveDataSource,
		        button:nextButton,
		        ok:false,
		        close: onDialogCloseHandler
		    });
		 }else {
		     Public.tip('请选择一行数据！');
		 }
}
var nextButton=[{
    id:"nextButton",
    name:"下一步",
    callback:doSaveDataSource
}];

var lastButton=[{
   id:"lastButton",
   name:"上一步",
   callback:backLast
}];

function doSaveDataSource(){
	var _self = this;
	var _validate=$("#selectCustomForm").formToJSON();
	if(!_validate){
		return false;
	}
	var targetField=$("#targetField").val();
	var oldSearchSql=$("#oldSearchSql").val();
	var searchSql=$("#searchSql").val();
	var isChanged="1";
	if (oldSearchSql!=""&&oldSearchSql==searchSql){
		isChanged="0";
	}
	searchSql=$.trim(searchSql);
	searchSql=searchSql.toLowerCase();
	if (searchSql.indexOf("*")>0){
		 Public.tip("此处不能使用符号*！");
		 return false;
	}
	if (searchSql.substring(0,6)!="select"||("from")<1){
		 Public.tip("SQL语句非法！");
		 return false;
	}
    var id = getId();
    var url = "/safFormslist/saveSelectCustom.ajax?type=1&changed="+isChanged;
    //url+="&formNo="+$("#formNo").val();
	$('#selectCustomForm').ajaxSubmit({
        url: web_app.name + url,
        success: function (data) { 
        	addNext(data.id,targetField,$("#formNo").val());
           // refreshFlag = true;
            reloadGrid_easysearch();
        }
    });
}

function addNext(id,targetField,formNo){//跳转到下一步的页面
 	UICtrl.showAjaxDialog({
	      title: "设置字段【"+targetField+"】数据来源详细属性",
	      url: web_app.name + '/safFormslist/loadDataSourceDetailNext.load',
	      param: {id:id,targetField:targetField,formNo:formNo},
	      width: 800,
	      init:function(){
	    	  initAddSelect();
	      },
	      button:lastButton,
	      ok: saveNext,
	      close: onDialogCloseHandler
	  });
}
function initAddSelect(){
	
}
function backLast(){//返回上一步的页面
	//var id=$("#id").val();
	UICtrl.showAjaxDialog({
        title: "设置字段【"+$("#targetField").val()+"】数据来源：",
        url: web_app.name +'/safFormslist/loadDataSourceDetail.load',
        param: {id:$("#id").val(),targetField:$("#targetField").val(),formNo:$("#formNo").val()},
        width: 800,
        init: initAddSelect,
        button:nextButton,
        ok:false,
        close: onDialogCloseHandler
    });
}
//下一步页面的保存
function saveNext(){
	var _self = this;
	var _validate=$("#selectCustomForm").formToJSON();
	if(!_validate){
		return false;
	}
	var pmId=$("#targetField").val();
	$('#backFields').val($('#backFields_text').val());
	$('#paramSourceFields').val($('#paramSourceFields_text').val());
    var id = getId();
    var url = "/safFormslist/saveSelectCustom.ajax?type=2";
	$('#selectCustomForm').ajaxSubmit({
        url: web_app.name + url,
        success: function (data) {
            //refreshFlag = true;
        	reloadGrid_easysearch();
            Public.tip('保存成功！');
            
        }
    });
}


//删除检索SQL定义 
function deleteSearchSQLHandler(){
	 var rows = UICtrl.checkSelectedRows(gridManager_easysearch);
	 //alert(rows.buttonType);
	 //if (rows.buttonType==2) {
	  /*  var action = "/safFormslist/deleteFormSettings.ajax?type=easysearch"++"&id="+rows.id;
	    $('#syfFormsForm').ajaxSubmit({
		       url: web_app.name +action,
		       success: function (data) {
		      	  reloadGrid();
		       	  refreshFlag = true;
		         // _self.close();
		      }
		   });*/
	  //  var row = UICtrl.checkSelectedRows(syfFormsGridManager);
	    // alert(row.id);
	     var action = "/safFormslist/deleteFormSettings.ajax?type=easysearch";
	     DataUtil.delSelectedRows({
	             action: action,
	             idFieldName: 'id',
	             gridManager: gridManager_easysearch,
	             onSuccess: reloadGrid_easysearch
	         }
	     );
	  /*  DataUtil.delSelectedRows({
	        action: action,
	        idFieldName: 'id',
      gridManager : gridManagerBtn,
	        onSuccess: reloadGrid
	    });*/
	// }else {
	//	 Public.tip("只能删除自定义按钮!")
	 //}
}
/****************************检索SQL的方法结束*********************************************/
//校验函数列表 
function init_checkfunction() {
	
	 var toolbarOptions =[];
	  toolbarOptions = UICtrl.getDefaultToolbarOptions({

	   saveHandler:saveListHandler,
	   deleteHandler:deleteHandler
	   });

	  gridManager_checkfunction = UICtrl.grid('#dli_checkfunction', {
		checkbox: true,
		columns : [ 
		   	//{ display: "函数ID", name: "objectId", width: 180, type: "string", align: "left"},
		    { display: "函数名称", name: "objectName", width: 180, type: "string", align: "left"
		   		,render: function (item) {
		             html="<a href='#' class='GridStyle' onclick='viewContent(\"" + item.objectId +"\",\"" + item.objectName +"\")'><font color=blue><u>"+item.objectName+"</u></font></a>";
		           	  return  html;
		    	}	
		   	},
		
			{ display: "参数", name: "argumentName", width: 180, type: "string", align: "left"},
			{ display: "参数类型", name: "dataType", width: 180, type: "string", align: "left"},
			{ display: "参数模式", name: "inOut", width: 180, type: "string", align: "left"},
			{ display: "最后修改时间", name: "lastDdlTime", width: 110, type: "date", align: "left"}
			//{ display: "状态", name: "status", width: 60, type: "string", align: "left"}
	     ], 

	     
		dataAction : 'server',
		//toolbar: toolbarOptions,
		url : web_app.name + '/safFormslist/slicedQueryFormParameter.ajax',
		parms : {
			formNo:$('#formNo').val(),parmType:3
	     },
		sortOrder : "asc",
		width : '99.8%',
		height : '88%',
		heightDiff : -8,
		pageSize:20,
		checkbox : true,
		enabledEdit: false,
		rownumbers : true,
		fixedCellHeight : true,
		selectRowButtonOnly : true,
		isChecked: f_isChecked,
	});
	function f_isChecked(data)
   {
       if (data.seled == 1){
       	return true;
       } 
       return false;
   }
	UICtrl.setSearchAreaToggle(gridManager_checkfunction);
}

function viewContent(id,name){

 UICtrl.showAjaxDialog({
    title: "查看内容："+name,
   // param: {id: folderId},
     url: web_app.name + '/safFormslist/loadFunctionOrProcduceContent.load?name='+name,
    width: 700, height: 350,
    init: function () {
       // initAddMdmMetaData(folderId);
    },
    ok:false,
    close: onDialogCloseHandler
   });
}

//存储过程列表 
function init_procduce(){
	 var toolbarOptions =[];
	  toolbarOptions = UICtrl.getDefaultToolbarOptions({
	   saveHandler:saveSearchHandler,
	   deleteHandler:deleteHandler
	   });

	  gridManager_procduce = UICtrl.grid('#dli_procduce', {
		checkbox: true,
		columns : [ 
		        	//{ display: "过程ID", name: "objectId", width: 180, type: "string", align: "left"},
				    { display: "过程名称", name: "objectName", width: 180, type: "string", align: "left"
				   		,render: function (item) {
				             html="<a href='#' class='GridStyle' onclick='viewContent(\"" + item.objectId +"\",\"" + item.objectName +"\")'><font color=blue><u>"+item.objectName+"</u></font></a>";
				           	  return  html;
				    	}	
				   	},
				   	{ display: "过程参数", name: "argumentName", width: 180, type: "string", align: "left"},
					{ display: "参数类型", name: "dataType", width: 180, type: "string", align: "left"},
					{ display: "参数模式", name: "inOut", width: 180, type: "string", align: "left"},
					{ display: "最后修改时间", name: "lastDdlTime", width: 110, type: "date", align: "left"}
					//{ display: "状态", name: "status", width: 60, type: "string", align: "left"}
	     ],
		dataAction : 'server',
		//toolbar: toolbarOptions,
		url : web_app.name + '/safFormslist/slicedQueryFormParameter.ajax',
		parms : {
			formNo:$('#formNo').val(),parmType:4
	     },
		sortOrder : "asc",
		//toolbar : toolbarOptions,
		width : '99.8%',
		height : '88%',
		heightDiff : -8,
		pageSize:20,
		checkbox : true,
		enabledEdit: false,
		rownumbers : true,
		fixedCellHeight : true,
		selectRowButtonOnly : true,
		isChecked: f_isChecked,
	});
	function f_isChecked(data)
  {
      if (data.seled == 1){
      	return true;
      } 
      return false;
  }
	UICtrl.setSearchAreaToggle(gridManager_procduce);
}


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

function addCustomButton(){
	
	 UICtrl.showAjaxDialog({
		  title:'添加表单提示',
		  url: web_app.name +'/safFormslist/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 = "/safFormslist/saveFormButtonLists.ajax";
    $('#syfFormsForm').ajaxSubmit({
        url: web_app.name + (url),
        param:{detailData1:encodeURI($.toJSON(rows)),id:$("#id").val(),formId:$("#formId").val()},
        success: function () {
            refreshFlag = true;
            gridManagerBtn.loadData();
           // _self.close();
        }
    });
 //
}
 //保存列表显示字段
function saveListHandler(){
	 var rows = gridManagerDisplayList.getSelectedRows();
		var _self = this;
		var url = "/safFormslist/saveDisplayFields.ajax";
	    $('#syfFormsForm').ajaxSubmit({
	        url: web_app.name + (url),
	        param:{detailData1:encodeURI($.toJSON(rows)),id:$("#id").val(),formId:$("#formId").val()},
	        success: function () {
	            refreshFlag = true;
	            gridManagerDisplayList.loadData();
	           // _self.close();
	        }
	    });
	
}
//保存列表查询条件字段
function saveSearchHandler(){
	
	 var rows = gridManagerSearch.getSelectedRows();
		var _self = this;
		var url = "/safFormslist/saveSearchFields.ajax";
	    $('#syfFormsForm').ajaxSubmit({
	        url: web_app.name + (url),
	        param:{detailData1:encodeURI($.toJSON(rows)),id:$("#id").val(),formId:$("#formId").val()},
	        success: function () {
	            refreshFlag = true;
	            gridManagerSearch.loadData();
	           // _self.close();
	        }
	    });
}
function initCustomButton(){ 
} 
	 
//保存自定义按钮方法
function doSaveCustomButton(){
	 var _self = this;
	   var id = getId();
	   var url = '/safFormslist/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 = "/safFormslist/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_formprompt() {
   gridManager_formprompt.loadData();
}
function reloadGrid_easysearch() {
  gridManager_easysearch.loadData();
}
function reloadGrid_checkfunction() {
	gridManager_checkfunction.loadData();
}
function reloadGrid_procduce() {
	gridManager_procduce.loadData();
}
//关闭对话框
function onDialogCloseHandler() {
    if (refreshFlag) {
        reloadGrid();
        refreshFlag = false;
    }
}

