var gridManager = null, refreshFlag = false, lastSelectedId = 0,gridDetailManager = null;
var passValidator=1;
$(document).ready(function() {
	initUI();
	initGrid();
});

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

function initGrid() {
	//注：集合格式形如 A;B;C,JSON格式 [{};{};{}]
	var toolbarOptions = null;
	  toolbarOptions=UICtrl.getDefaultToolbarOptions({
			 addHandler: {id:'doSave',img:'fa-plus',text:'保存',click:function(){
				 showdoSave();
			}}
	  });

	gridManager = UICtrl.grid('#maingrid', {
		checkbox: true,
		columns : [ 
		    { display: "字段名称", name: "columnName", width: 100, type: "string", align: "left"},
			{ display: "字段长度", name: "dataLength", width: 60, type: "int", align: "left"},
			{ display: "显示名称", name: "comments", width: 150, type: "string", align: "left"
				//editor: { type:'text',maxLength:'20'}
		    },
		   // { display: "允许为空", name: "nullable", width: 60, type: "int", align: "left"},
            { display: "属性类型", name: "dataType", width: 40, type: "int", align: "left",hide:true},
            { display: "是否必输", name: "yesornoTextView", width: 90, type: "string", align: "center",
            	editor: { type:'dictionary',data:{name: 'yesorno'},textField:'yesornoTextView',valueField:'yesorno'}},
        	{ display: "是否列表显示", name: "listdisplayFieldTextView", width: 90, type: "string", align: "center",
        		editor: { type:'dictionary',data:{name: 'listdisplayField'},textField:'listdisplayFieldTextView',valueField:'listdisplayField'}},
          	{ display: "是否查询条件", name: "listdisplaySearchFieldTextView", width:90, type: "string", align: "center",
            	editor: { type:'dictionary',data:{name: 'listdisplaySearchField'},textField:'listdisplaySearchFieldTextView',valueField:'listdisplaySearchField'}},
			{ display: "显示控件类型", name: "xmControlTypeTextView", width:90, type: "string", align: "left",
    			editor: { type:'dictionary',data:{name: 'xmControlType'},textField:'xmControlTypeTextView',valueField:'xmControlType'}	
			},
			{ display: "设置字段类型", name: "validatorTypeTextView", width:90, type: "string", align: "left",
				editor: { type:'dictionary',data:{name: 'validatorType'},textField:'validatorTypeTextView',valueField:'validatorType'}
			},
			{ display: "选择框数据来源", name: "dataSourceTypeTextView", width: 100, type: "string", align: "left",
				editor: { type:'dictionary',data:{name: 'dataSourceType'},
					title:'注：集合表示自定义数据来源，JSON格式 [{};{};{}]',
					textField:'dataSourceTypeTextView',valueField:'dataSourceType'}
			},
			{ display: "数据来源内容", name: "dataSource", width:130, type: "string", align: "left",
				//editor: { type:'text',maxLength:'50'},title:'注：集合定义：[searchName:;type:;id:;displayField:{};conditionField:{};orderby:]，JSON格式 [{};{};{}]'
				render: function (item,index) {
		                   	var html="";// alert(item.dataSourceType);
		                   	if (item.dataSource!=""||item.dataSourceType=="3"){
		                       html="<input type='text' id='dsval_"+index+"' name='dsval_"+index+"' maxlength=20 value='"+item.dataSource+"'/>";
		                       //html="<a href='#' class='GridStyle' onclick='editDataSource(\"" + item.id +"\",\"" + item.dataSourceType+"\",\"" +item.columnName+"\")'><font color=blue><u>"+item.dataSource+"</u></font></a>";
		                   	} else	if (item.dataSourceType!=""&&item.dataSourceType=="2"){
		                   	   html="<a href='#' class='GridStyle' onclick='editDataSource(\"" + item.id +"\",\"" + item.dataSourceType+"\",\"" +item.columnName+"\")'><font color=blue><u>数据来源</u></font></a>";		                   		
		                   	}  
		                   	 return  html;
		         }	
			},
			{ display: "*顺序号", name: "sequence", width: 60, type: "int", align: "left",
				editor: { type:'text',required:true,mask:'999',maxLength:'3'}
			}
            ],
		dataAction : 'server',
		url : web_app.name + '/safForms/queryTableProperty.ajax',
		parms : {
			id : getId(),
			tableName : $("#tableName").val()
			
	},
		sortOrder : "asc",
		toolbar : toolbarOptions,
		width : '99.8%',
		height : '100%',
		heightDiff : -8,
		pageSize:100,
		checkbox : true,
		enabledEdit: true,
		rownumbers : true,
		fixedCellHeight : true,
		selectRowButtonOnly : true,
		//onBeforeEdit:validator_comments,
		onAfterEdit:validator_sequence,
		isChecked: f_isChecked,
	});
	function f_isChecked(data)
    {
        if (data.inb == 1){
        	return true;
        } 
        return false;
    }
	UICtrl.setSearchAreaToggle(gridManager);
}

//设置数据来源内容：
function editDataSource(id,dataSourceType,fieldEn){
	//alert(id);
	//var url=web_app.name + '/taskproperty/showProcessPropertyDetail.do';
	 UICtrl.showAjaxDialog({
	        title: "设置字段【"+fieldEn+"】数据来源：",
		    url: web_app.name + '/safForms/loadDataSourceDetail.load',
	        param: {id:id,tableName:$("#tableName").val(),targetField:fieldEn },
	        width: 900,
	       // ok: doSaveDataSource,
	        button:nextButton,
	        ok:false,
	        close: onDialogCloseHandler
	    });
}
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.substring(0,6)!="select"||searchSql.indexOf("from")<1){
		 Public.tip("SQL语句非法！");
		 return false;
	}
    var id = getId();
    var url = "/safForms/saveSelectCustom.ajax?type=1&&changed="+isChanged;
	$('#selectCustomForm').ajaxSubmit({
        url: web_app.name + url,
        success: function (data) {
        	addNext(targetField);
            refreshFlag = true;
        }
    });
}

function addNext(targetField){//跳转到下一步的页面
 	UICtrl.showAjaxDialog({
	      title: "设置字段【"+targetField+"】数据来源详细属性",
	      url: web_app.name + '/safForms/loadDataSourceDetailNext.load',
	      param: {tableName:$("#tableName").val(),targetField:targetField},
	      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 +'/safForms/loadDataSourceDetail.load',
        param: {tableName:$("#tableName").val(),targetField:$("#targetField").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();
    var id = getId();
    var url = "/safForms/saveSelectCustom.ajax?type=2";
	$('#selectCustomForm').ajaxSubmit({
        url: web_app.name + url,
        success: function (data) {
            refreshFlag = true;
        }
    });
}


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

function reloadGrid() {
    gridManager.loadData();
}
//关闭对话框
function onDialogCloseHandler() {
    if (refreshFlag) {
        reloadGrid();
        refreshFlag = false;
    }
}
//保存表属性
function showdoSave() {
	debugger
    var rows = gridManager.getSelectedRows();
    var noAccess=false;
    gridManager.endEdit();
    for (var i=0;i<rows.length;i++) {
		var a=rows[i];
	     if (Public.isBlank(a["sequence"])){
	    	Public.tip("请输入正确的数字顺序号码!!");
	    	noAccess=true;
	    	/*$(gridManager.columns).each(function (i, col){
	  		  if(col.columnname=='sequence'){
	  			  $(gridManager.getCellObj(a['__id'],col)).click();
	  		  } 
	  	     });*/
	    	break;
	     }
	     if (Public.isBlank(a["comments"])){
	    	 Public.tip("请输入正确的属性显示名称!!");
		     noAccess=true;
		     break;
	     }
	     if (a["dataSource"].indexOf(",")>-1){
	    	 Public.tip("数据来源名称/内容不能包含逗号!!");
		     noAccess=true;
		     break;
	     }
	    if (a["dataType"]=="DATE"&&a["xmControlType"]=="input") {
	    	 Public.tip("请将："+a["comments"]+" 的显示控件类型设置为日期型!");
	    	  noAccess=true;
			  break;
	    }
	    var ds='#dsval_'+i;
	    if ($(ds)){
	    	rows[i].dataSource=$(ds).val();
	    }
	}
//    DataUtil.getGridData({isAllData:true});
    if (!noAccess){
      if (rows) {
    	 doSave(rows);
      }
    }
}
function doSave(rows) {
	debugger
	var _self = this;
	var url = "/safForms/saveTableFieldAttributeList.ajax";
    $('#submitForm').ajaxSubmit({
        url: web_app.name + (url),
        param:{detailData1:encodeURI($.toJSON(rows)),id:$("#id").val(),tableName:$("#tableName").val()},
        success: function () {
            refreshFlag = true;
            gridManager.loadData();
            _self.close();
        }
    });
	 
}

//设置扩展字段的显示名称能修改
function validator_comments(data){
	if (data.column.columnname=="comments"){
		var columnName=data.record.columnName;
	 //if (data.record.columnName=="f1"||data.record.columnName=="f2"
	//	 ||data.record.columnName=="f3"||data.record.columnName=="f4"||data.record.columnName=="f5"
	  //){
	 if (columnName.substring(0,1)=='f'){
		return true;
	  } else {
		return false;
	  }
	}
	return true;
}

//设置属性类别的非基本属性的顺序号可以修改
function validator_comments_basic(data){
	if (data.column.columnname=="sequence"){  
	 if (data.record.propertyClasscode=="basic"){   
		return false;
	  } else {
		return true;
	  }
	}
	return true;
}
//效验模板设置顺序
function validator_sequence(data){ 
	//debugger
 	var allSelected=this.selected;
 	var gg=this.getRow(data.rowindex);
	var currSelectedId=this.getRow(data.rowindex).__id;
	var isSelected=false;
	for (var s=0;s<allSelected.length;s++){
		if  (currSelectedId==allSelected[s].__id){
			isSelected=true;
		}
	}
  if (isSelected){
	if (data.column.columnname=="sequence"){  
	  var res=Public.validator("number",data.record.sequence);
	  if (Public.isBlank(data.record.sequence)||data.record.sequence.length>3){
		 res=false;
	   }
	  if (res==false){
	    Public.tips({type: 1, content: "请输入正确的数字顺序号码！", time: 1500});
	        data.record.sequence="";
			passValidator=0;
	  } else {
			passValidator=1;
	  }
	}
	if (data.column.columnname=="dataSource"){ 
		if (data.record.dataSource.indexOf(",")>-1){
		  Public.tips({type: 1, content: "数据来源名称/内容不能包含逗号！【注：集合格式形如 A;B;C,JSON格式 [{};{};{}]】", time: 1500});
		  //集合格式 " A;B;C" JSON 格式  [{};{};{}]  
		  //data.record.dataSource="";
		}
	}
  }
 }
