package com.huigou.uasp.builder.jsbutton;

import java.util.ArrayList;
import java.util.List;

import com.google.common.base.CaseFormat;
import com.huigou.uasp.builder.ButtonTypeInter;
import com.huigou.uasp.builder.vo.ButtonAttributeVO;
import com.huigou.uasp.util.Utils;
import com.huigou.uasp.util.Constant;

public class SaveRowButtonResult implements ButtonTypeInter {
	
	public List<String> processOutResult(StringBuffer sb,ButtonAttributeVO btnAttr){
		List <String> list=new ArrayList<String>();
		   	    
   	   // sb.append(" //保存行数据方法 ").append(Constant.SYSMBOL_LINE);;
		sb.append("function saveRow").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("(mid){");
		sb.append("  if ($('#procId').val()!=\"\") { ");
		sb.append("   UICtrl.addGridRow(").append(btnAttr.getEntityName()).append("GridManager,{id:''} );");
		sb.append(" } else { ");
		sb.append("    var _self = this;   var id = getId();");
		//sb.append("  if (mid!=\"\") { id = mid; $(\"#id\").val(mid); }");
		
	//	sb.append("   if (id=='') {  id=doCallFunc(eval(\"doSaveMdmDataRecord\"),[]); $(\"#id\").val(id); } " );
		sb.append("   if (id=='') { Public.tip(\"").append(Constant.MUST_SAVE_MAIN_DATA).append("\");return false; } " );
	//	sb.append("	   return false;");
	//	sb.append("   }");
		
		sb.append("  var detailData = DataUtil.getGridData({ ");
		sb.append(" 	isAllData : true,");
		sb.append(" 	gridManager :").append(btnAttr.getEntityName()).append("GridManager");
		sb.append(" 	});");
		
		sb.append("	var param = false;");
		sb.append("	if(detailData && detailData instanceof Array && detailData.length >0){");
		sb.append("		param={detailData:encodeURI($.toJSON(detailData))}; }else{ ");
		//sb.append("	  if (mid==\"\") { Public.tip(\"").append(Constant.ADD_DETAIL_DATA).append("\");");
		//sb.append("	} else { ");
		sb.append("	 if (detailData==\"\"&&detailData!=false) { return true;");
		sb.append("	 }else if (detailData==false) { return param;");
		sb.append("	 } else {return param; }");
		sb.append("	 } ");
	
		if (btnAttr.getIsForm()==1){  //表单生成器
			sb.append("   var url = '/dataManage").append("/saveRowDataRecordDetail.ajax");
		} else {  //代码生成器 
		    sb.append("   var url = '/").append(btnAttr.getParentEntityName()).append("/saveRow");
		    sb.append(Utils.toUpperCaseFirstOne(btnAttr.getParentEntityName())).append("Detail.ajax");
		 }
		 sb.append("?maiTab=").append(btnAttr.getParentEntityName())
		   .append("&subTab=").append(btnAttr.getEntityName())
		   .append("&formId='+"+"$(\"#formId\").val()")
		   .append("+'&mid='+"+"$(\"#id\").val()");
		   sb.append(";");

		//sb.append("   if (id && id.length > 0)   ");
		/*sb.append("        url ='/").append(btnAttr.getParentEntityName()).append("/updateRow")
		   .append(Utils.toUpperCaseFirstOne(btnAttr.getParentEntityName())).append("Detail.ajax")
		   .append("?maiTab=").append(btnAttr.getParentEntityName())
		   .append("&subTab=").append(btnAttr.getEntityName())
		   .append("&modelId='+"+"$(\"#modelId\").val()")
		   .append("+'&id='+"+"$(\"#id\").val()");
		sb.append(";");
		*/
		
	//	sb.append("    $('#").append(btnAttr.getParentEntityName()).append("Form').ajaxSubmit({ ")
		sb.append("    $('#submitForm').ajaxSubmit({ ")   //表单有流程 则formName只能是submitForm
		.append("	        url: web_app.name + (url),");
		sb.append("	        param:param, ");
		sb.append("	        success: function (data) {")
		//sb.append("	        	$(\"#id\").val(data); ");
		.append("	            refreshFlag = true;")
		  //避免明细表修改后保存后提示 数据已经改变，关闭后数据丢失的提示
        .append("              ").append(btnAttr.getEntityName()).append("GridManager.isDataChanged=false;")
        .append("           if (data.result==\"success\") {	 ");
		//.append("	           reload").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("Grid();")

		sb.append("var ids=data.backIDs; var bid=ids.split(',');")
		  .append("var rows = smsOrderDetailGridManager.rows;")
		  .append("for (var i = 0,r = rows.length-1; i < r; i++) {")
 		  .append("	rows[i].id = bid[i];")
 		  .append("} ")
		  .append(btnAttr.getEntityName()).append("GridManager.reRender();");

		sb.append("           }")
	//	sb.append("	            _self.close();");
		.append("	        }")
		.append("	    });")
		.append(" return true;")
		.append(" } ");
		sb.append(" }  ");
		sb.append("	");
        sb.append(Constant.SYSMBOL_LINE);

        //如果是表单 带有流程 ，需要重新实现 保存主表的方法
		sb.append("function doSave").append(Utils.toUpperCaseFirstOne(btnAttr.getParentEntityName())).append("(grid){");
		sb.append(" var _self = this;");
		sb.append("   var id = getId();");

		sb.append("  if ($('#procId').val()!=\"\") { ");
		sb.append("   UICtrl.addGridRow(").append(btnAttr.getEntityName()).append("GridManager,{id:''} );");
		sb.append(" } else { ");

		if (btnAttr.getIsForm()==1){  //是表单生成器 则调用统一的添加方法
			sb.append("  var url= '/dataManage/saveDataRecord.ajax';");
			sb.append("  if (grid==1) { url+='?btntype=1';  } ");
			sb.append("  $('#submitForm').ajaxSubmit({");   //发起流程 必须固定表单名称为submitForm
		} else {
			sb.append("   var url = '/").append(Utils.toLowerCaseFirstOne(btnAttr.getEntityName()))
					.append("/save").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append(".ajax';");
			// sb.append("  $('#").append(Utils.toLowerCaseFirstOne(btnAttr.getEntityName())).append("Form').ajaxSubmit({");
			sb.append("  $('#submitForm').ajaxSubmit({");
		}

		sb.append("       url: web_app.name +url,");
		sb.append("       success: function (data) {");

		sb.append("           $(\"#id\").val(data);");
		sb.append("           if (grid&&grid!=\"\") {UICtrl.addGridRow(eval(grid),{id:''}  );}");
		//sb.append("      	  reload").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("Grid();");
		//sb.append("       	  refreshFlag = true;");
		//sb.append("           _self.close();");
		sb.append("      }");
		sb.append("   });");

		sb.append(" }");
		sb.append(" } ");
		sb.append(Constant.SYSMBOL_LINE);

		//增加带有流程的获取数据保存的参数
		sb.append("function getExtendedData(processAction) { ");
		//回退、打回、转交时，不需要验证必填项是否已经填写；
		sb.append("if (processAction == ProcessAction.BACK||processAction == ProcessAction.REPLENISH")
				.append(" ||processAction == ProcessAction.TRANSMIT) { ");
			//不验证
		sb.append("	$('#submitForm').attr('check', false); 	} ");
		sb.append("const isAllData = $('#oldId') || !getId();");
		sb.append("var extendedData = {};");

		//sb.append("var _grid = UICtrl.getGridManager('").append(btnAttr.getEntityName()).append("GridManager');");
		sb.append("var detailData = DataUtil.getGridData({ ");
		sb.append("		isAllData : true,");
		sb.append("		gridManager :").append(btnAttr.getEntityName()).append("GridManager");
		sb.append("		});");
		sb.append(" if(detailData && detailData instanceof Array && detailData.length >0){");
		sb.append("	if (!detailData) {");
		sb.append("		return false;");
		sb.append("	} ");

		sb.append("extendedData.").append(btnAttr.getEntityName()).append("data=Public.encodeJSONURI(detailData);");
		sb.append("	}");
		sb.append("return extendedData;");
		sb.append("}");
		sb.append(Constant.SYSMBOL_LINE);

		//含有流程 保存前的回调方法
		sb.append("function beforeSave() { ");

		sb.append("}");
		sb.append(Constant.SYSMBOL_LINE);

       //含有流程 保存后的回调方法
		sb.append("function afterSave(bizData) {");
		//sb.append("		var mid=getId(); ");
		sb.append("	var params=[];");
		sb.append(btnAttr.getEntityName()).append("GridManager.options.url=web_app.name + '/dataManage/slicedQueryDataRecordDetail.ajax?id='+getId();");
		//sb.append(btnAttr.getEntityName()).append("GridManager.isDataChanged=flase;");  //但是页面有提示？
		sb.append("UICtrl.gridSearch(").append(btnAttr.getEntityName()).append("GridManager, params);");
		sb.append("}");
		sb.append(Constant.SYSMBOL_LINE);

	     list.add(sb.toString());
		 // list.add(Integer.toString(fieldAttributes.getCurrCols()));
		return list;
	}
	
	
}
