package com.huigou.uasp.builder.filer;

import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.CaseFormat;
import com.huigou.uasp.builder.BuildFilerInter;
import com.huigou.uasp.builder.BuildTypeClass;
import com.huigou.uasp.builder.FieldTagTypeInter;
import com.huigou.uasp.builder.pagetag.CheckboxTagResult;
import com.huigou.uasp.builder.pagetag.DateTagResult;
import com.huigou.uasp.builder.pagetag.InputTagResult;
import com.huigou.uasp.builder.pagetag.RadiosTagResult;
import com.huigou.uasp.builder.pagetag.SelectTagResult;
import com.huigou.uasp.builder.pagetag.TextAreaTagResult;
import com.huigou.uasp.builder.vo.FieldAttributeVO;
import com.huigou.uasp.builder.vo.ParamFormVO;
import com.huigou.uasp.util.Utils;
import com.huigou.uasp.util.Constant;

/**
 * @author lxh
 * @DATE 2019年08月10日
 * @Description 生成明细页面 
 */

@Service("buildPageDetailFile")
public class BuildPageDetailFile implements BuildFilerInter {
	
	@Autowired 
	private BuildPageJSFile buildPageJSFile;


	@Override
	public String generateFile(ParamFormVO paraForm,List<Map<String, Object>> fieldList)  throws Exception{
		 
		    String entityName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName());
		    StringBuffer sb=generateContents(paraForm,entityName);
            String  filePathName=paraForm.getUploadPath()+"/"+paraForm.getFormPath()+"/"+entityName+"Detail.jsp";
	
		    return Utils.generateFile(filePathName,sb);
			
	  }
	
	public String generateFile(String filePathName,StringBuffer sb) throws Exception{
		 return Utils.generateFile(filePathName,sb);
	}
	
   //如果是不存在明细表的 则parentEntityName即entityName
	public StringBuffer generateContents(ParamFormVO paraForm,String mainTableName){
		
		  StringBuffer sb=new StringBuffer("");
		  sb.append("<%@ page contentType=\"text/html; charset=utf-8\" language=\"java\"%>\r\n");
		  sb.append("<%@ taglib uri=\"/WEB-INF/taglib.tld\" prefix=\"x\"%>\r\n");
		  sb.append("<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%>\r\n");

		 //存在属性多值的明细页面 
	     if (paraForm.getDetails()!=null&&paraForm.getDetails().size()>0){
		      generateDetailFile(paraForm,mainTableName,sb);
		 }
	     
	      String entityName=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,mainTableName);
	       
	     //if (paraForm.getIsform()==1){  //是表单生成器 则Form名称统一 dataRecordForm
		    //因为需要发起流程 必须固定表单名称为submitForm
	    	 sb.append("<form class=\"hg-form\" method=\"post\" action=\"\" id=\"submitForm\">\r\n");
	     //} else{
		  //   sb.append("<form class=\"hg-form\" method=\"post\" action=\"\" id=\"").append(entityName).append("Form\">\r\n");
	    // }
	     for (String hiddenField:paraForm.getHiddenFields()){ 
		     sb.append("   <x:hidden name=\"").append(hiddenField).append("\" />\r\n");
		  }

	     //存在流程的 添加固定的隐藏字段
		sb.append("   <x:hidden name=\"procId\" />\r\n");
		sb.append("   <x:hidden name=\"billCode\"/>\r\n");
		sb.append("   <x:hidden name=\"fillinDate\" type=\"datetime\"/>\r\n");
		sb.append("   <x:hidden name=\"fullId\"/>\r\n");
		sb.append("   <x:hidden name=\"organId\"/>\r\n");
		sb.append("   <x:hidden name=\"organName\"/>\r\n");
		sb.append("   <x:hidden name=\"deptId\"/>\r\n");
		sb.append("   <x:hidden name=\"deptName\"/>\r\n");
		sb.append("   <x:hidden name=\"positionId\"/>\r\n");
		sb.append("   <x:hidden name=\"positionName\"/>\r\n");
		sb.append("   <x:hidden name=\"personMemberId\"/>\r\n");
		sb.append("   <x:hidden name=\"personMemberName\"/>\r\n");

		  sb.append(" <div class=\"hg-form-cols\"> \r\n");
	      sb.append("  <div class=\"hg-form-row\">\r\n");
          sb.append("    </div>\r\n");
  
          //生成表单标签元素
          generateFieldTag(paraForm,sb);
         
       if (paraForm.getExistAttachment()==1){
          sb.append("<div class=\"hg-form-row\">\r\n");
      	  sb.append("   <x:fileList bizCode=\"").append(entityName).append("Id\" bizId=\"attbizid\" id=\"").append(entityName).append("List\" title=\"相关附件\" />\r\n");
      	  sb.append("</div>\r\n");
       }
        sb.append(" </div>\r\n");
 	    sb.append("</form>\r\n");
 	 
		//生成明细页面
	   if (paraForm.getDetails()!=null&&paraForm.getDetails().size()>0){
		     List <ParamFormVO> listDetails=paraForm.getDetails();
		     ParamFormVO paraDetail=null;
		     String gridName="";
			for (int j=0;j<listDetails.size();j++){
				paraDetail=listDetails.get(j);
			   gridName=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraDetail.getTableName());
			  sb.append("<div class=\"clearfix\"></div>\r\n");
			  sb.append("<div><font style=\"font-weight:bold;font-size:inherit\">&nbsp;&nbsp;").append(paraDetail.getFormName()).append("列表  </font><br></div>\r\n");
			  sb.append(" <div id=\"").append(gridName).append("Grid\" style=\"margin: 2px;\"></div>\r\n");
			}
		
		}
	
		return sb;
	}
	//生成主表单的标签元素
	public void generateFieldTag(ParamFormVO paraForm,StringBuffer sb){

		  String []fieldEns=paraForm.getFieldEns();
		 if (paraForm.getIsform()==0) {  //是代码生成器 获取真实字段名称
			 fieldEns=paraForm.getRealFieldEns();
			 String tfstr="";
			 for (int u=0;u<fieldEns.length;u++) {
				 tfstr= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, fieldEns[u]); //转驼峰法
				 fieldEns[u]=tfstr;
			 }
		 }
		  String []fieldChs=paraForm.getFieldChs();
		  String []fieldTags=paraForm.getFieldTags();
		  String []mustInputField=paraForm.getMustinputFields();
		  String []fieldsLengths=paraForm.getFieldsLengths();
		  String []defaultOperations=paraForm.getDefaultOperation();
		  
          String []validatorTypes=paraForm.getValidatorTypes();
          String []codeRuleIds=paraForm.getCodeRuleId();
          
        String fieldEn="";
        int rows=countRows(paraForm);
		 int cols=Integer.parseInt(paraForm.getPagedatailCols());//每行显示标签个数
	     int x=0;
	      
        Queue<String> queue = new ArrayDeque<String>();
        for (int y=0;y<fieldEns.length;y++){
     	    queue.add(fieldEns[y]);
        }
        List <String>list=new ArrayList<String>();
		   FieldTagTypeInter outResults=null;
	         FieldAttributeVO fieldAttributes=null;
	      for (int i=0;i<rows;i++){
		    	 if (queue.isEmpty())
		  	         break;
		  	    sb.append("  <div class=\"hg-form-row\">\r\n");
		 	   for (int r=0;r<cols;r++){
		 		    if (queue.isEmpty())
			  	      break;
		    	     fieldEn=queue.poll();
		    	  for (int y=0;y<fieldEns.length;y++){
	        	    if ((fieldEn).equals(fieldEns[y])){
	        		   x=y;
	        		   break;
	        	    }
	            }
				   outResults=getFieldTagType(fieldTags[x]);
				   fieldAttributes=new FieldAttributeVO();
				   fieldAttributes.setFieldEn(fieldEns[x]);
				   fieldAttributes.setFieldCh(fieldChs[x]);
				   if (codeRuleIds!=null){
				     fieldAttributes.setCodeRuleId(codeRuleIds[x]);
				   }
				   
				   fieldAttributes.setFieldLength(Integer.parseInt(!"".equals(fieldsLengths[x])?fieldsLengths[x]:"0"));
				   fieldAttributes.setDefaultOperation(defaultOperations[x]);
				   
				   fieldAttributes.setLabelCols(paraForm.getLabelCols());
				   fieldAttributes.setFieldCols(paraForm.getFieldCols());
				   fieldAttributes.setMustinputField("1".equals(mustInputField[x])?"true":"false");
				   fieldAttributes.setTextAreaRows(paraForm.getTextAreaRows());
				   fieldAttributes.setCols(cols);
				   fieldAttributes.setCurrCols(r);
				   if (validatorTypes.length>x){
				     fieldAttributes.setValidatorType(validatorTypes[x]);
				   }
				   if (paraForm.getDataSourceTypes().length>x){
				     fieldAttributes.setDataSourceType(paraForm.getDataSourceTypes()[x]);
				   }
				   if (paraForm.getDataSources().length>x){
				     fieldAttributes.setDataSource(paraForm.getDataSources()[x]);
				   }
				   if (paraForm.getCssStyle().length>x){
				     fieldAttributes.setCssStyle(paraForm.getCssStyle()[x]);
				   }
				   if (paraForm.getCheckFunction().length>x){
					   fieldAttributes.setCheckFunction(paraForm.getCheckFunction()[x]);
					}
				    list=outResults.processOutResult(sb,fieldAttributes);
				    r=Integer.parseInt(list.get(1));
	        
	             if  (x<fieldEns.length-1){; //
	               if (Constant.TEXTAREA_TAG.equals(fieldTags[x+1])){
	              	 r=cols;
	               }
	             }
			   }
			   sb.append("  </div>\r\n");
	       }  
	}
	
	
	//生成明细列表的JS文件  
	public void generateDetailFile(ParamFormVO paraForm,String mainTableName,StringBuffer sb){
		  // String tableName= paraForm.getTableName();
		  // String entityMainTable=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,tableName);//主表
		   sb.append(" <head> \r\n");
		   List <ParamFormVO> listDetails=paraForm.getDetails();
		     ParamFormVO paraDetail=null; 
		     sb.append(" <script type=\"text/javascript\">\r\n");
		   //  sb.append("  var isAudit=\"${isAudit}\"");
	
		     //组装字段效验事件
		      sb.append("    bindEvent();  \r\n");
			  Utils.composeMainFormCheckFunction(paraForm, sb);
			  
			  //明细表的列表  进行效验 ？？ 
			/*  onAfterEdit:totalArea,
			  function totalArea(data){
					data=data.record;
					var houseArea=data.field3||0;
					var houseNumber=data.field4||0;
					 var c = data.column;  alert(c);
				            if (c.name == 'field2') {//启用的数据value 不能编辑
				               alert(c.name);
							}
					alert(houseArea);
						smsOrderDetailGridManager.updateCell('ff', houseNumber, data);

				 }
			  */
			  
		     sb.append(" </script> \r\n");
		     String formNo=paraForm.getFormPath();
		     if (paraForm.getIsform()==1) {  //表单生成
			   formNo = formNo.substring(formNo.indexOf("customform") + 11);
		      }
		     String queryUrl="";
		 for (int j=0;j<listDetails.size();j++){
				paraDetail=listDetails.get(j);
				String entitySubTable=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraDetail.getTableName());
			  sb.append(" <script src='<c:url value=\"");
			  if (paraForm.getIsform()==1) {  //表单生成
				sb.append(paraForm.getSrcPath());
			  }
			  sb.append("/").append(formNo).append("/").append(entitySubTable)
				.append(".js\"/>' type=\"text/javascript\"></script>").append(Constant.SYSMBOL_LINE);

				//生成js文件
				String detailTableName=paraDetail.getTableName();
				paraDetail.setTableName(detailTableName.toLowerCase());

			    paraDetail.setBtnNames(new String[]{"新增行","删除行","保存行"});
			    paraDetail.setBtnMethodNames(new String[]{"addRow","deleteRow","saveRow"});
			   // BuildPageJSFile buildStringBuffer=new BuildPageJSFile(paraDetail);
				if (buildPageJSFile==null){
					buildPageJSFile=new BuildPageJSFile();
				}
				 if (paraForm.getIsform()==1){  //是表单生成器
					 queryUrl="'/dataManage/slicedQueryDataRecordDetail.ajax'";
				 } else {
			         queryUrl="'/dataManage/slicedQuery"+entitySubTable+"Detail.ajax";
				 }
			         queryUrl+="?maiTab="+mainTableName; 
			         queryUrl+="&subTab="+detailTableName;
			         queryUrl+="&formId="+"$(\"#formId\").val()";
			    	 queryUrl+="+'&id='+"+"$(\"#id\").val()";
			    	 
			      StringBuffer sbjs=buildPageJSFile.generateContents(paraDetail,mainTableName,paraForm.getRealFieldEns(),true,queryUrl);
			      if (paraForm.getIsform()==1) {  //表单生成页面
                      Utils.generateFile(paraForm.getFormPath()+"/"+entitySubTable+".js", sbjs);
			      } else {   // 代码生成
                      Utils.generateFile(paraForm.getSrcPath()+"/"+entitySubTable+".js", sbjs);

			      }
		   }
		  sb.append(" </head> \r\n");

	}
	
	//计算显示行数
	public int countRows(ParamFormVO paraForm){
		   int cols=Integer.parseInt(paraForm.getPagedatailCols());//每行显示标签个数
		   String []fieldTags=paraForm.getFieldTags();
		   String []fieldEns=paraForm.getFieldEns();
	       int areaCols=0;
			   //判断是否存在textarea标签，增加行数
			   for (int y=0;y<fieldTags.length;y++){
			     if ("textarea".equals(fieldTags[y]))
			    	 areaCols++;
			    	 if (y%cols!=0) //不在行的开始位置
			    		 areaCols++; 
			    }
			  int remainder=(fieldEns.length-areaCols)%cols; //余数
	          int rows=(fieldEns.length-areaCols)/cols; //行数
	         if (remainder!=0) //余数不是0
	      	    rows++;
	            rows+=areaCols;
	      return rows;
	}
	
	 //**获取页面标签类型
	  public  FieldTagTypeInter getFieldTagType(String condition){
		  FieldTagTypeInter inter=null;
	      switch(condition)
		   { 
		     case Constant.INPUT_TAG:
			   inter=new InputTagResult();
			   break;
			   
		     case Constant.SELECT_TAG:  
			   inter=new SelectTagResult();
			   break;		
				   
		     case Constant.TEXTAREA_TAG:  
			   inter=new TextAreaTagResult();
			   break;		
				   
		     case Constant.DATE_TAG: 
			   inter=new DateTagResult();
			   break;		
			   
		     case Constant.RADIOS_TAG: 
			   inter=new RadiosTagResult();
		       break;	
		       
		     case Constant.CHECKBOX_TAG: 
			   inter=new CheckboxTagResult();
			    break;	
			    
		      default:
		   }
		  return inter;
	  }

}
