package com.huigou.uasp.builder.filer;

import java.io.File;
import java.util.List;
import java.util.Map;

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.vo.ParamFormVO;
import com.huigou.uasp.builder.vo.SeleListCustomVO;
import com.huigou.uasp.util.Constant;
import com.huigou.uasp.util.Utils;

@Service("buildXMLFile")
public class BuildXMLFile implements BuildFilerInter {
	
	private ParamFormVO paraForm;
		

	@Override
	public String generateFile(ParamFormVO paraForm,List<Map<String, Object>> fieldList)  throws Exception{
		  File file=new File(paraForm.getUploadPath()+"/config");
		  if (!file.exists()){
			  file.mkdir();
		  }
		  String filePaths[]=paraForm.getFormPath().split("/");
		  file=new File(paraForm.getUploadPath()+"/config/"+filePaths[0]);
		  if (!file.exists()){
			  file.mkdir();
		  }

		  String clsName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName());
		  String fileName=clsName; // 首字母小写
		
		   StringBuffer sb=new StringBuffer("");
   
		   //jpa通过外部orm文件中定义访问数据库
		  sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n ");
		  sb.append("  <query-mappings>\r\n ");
		  sb.append("  	 <query name=\"").append(fileName).append("\" label=\"").append(paraForm.getFormName())
		    .append("\" table=\"").append(paraForm.getTableName()).append("\">\r\n ");
		  sb.append(" 		<sql-query>\r\n ");
		  sb.append(" 		  select t.* from ").append(paraForm.getTableName()).append(" t where 1 = 1 \r\n ");
		  sb.append(" 		</sql-query>\r\n ");
		  
		 if (paraForm.getSearchFields()!=null&&paraForm.getSearchFields().length>0){
		     String searchField="";
		   for (int i=0;i<paraForm.getSearchFields().length;i++){
			  if ("1".equals(paraForm.getSearchFields()[i])){ //
				  searchField=paraForm.getFieldEns()[i];
			      searchField=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,searchField);//转成下划线
			    if  ("date".equals(paraForm.getFieldTags()[i])){ //日期格式的条件  只能在application中单独处理
			    	/*  sb.append(" 		<condition column=\"").append(searchField).append("\" name=\"")
			           .append("start"+Utils.toUpperCaseFirstOne(paraForm.getFieldEns()[i]))
			           .append("\" type=\"java.lang.String\" symbol=\"&gt;=\" alias=\"t\"/>\r\n ");
			    	  sb.append(" 		<condition column=\"").append(searchField).append("\" name=\"")
			           .append("end"+Utils.toUpperCaseFirstOne(paraForm.getFieldEns()[i]))
			           .append("\" type=\"java.lang.String\" symbol=\"&lt;=\" alias=\"t\"/>\r\n ");
			    	  */
			    } else {
		         sb.append(" 		<condition column=\"").append(searchField).append("\" name=\"")
		           .append(paraForm.getFieldEns()[i]).append("\" type=\"java.lang.String\" symbol=\"like\" alias=\"t\"/>\r\n ");
			    }
		  //  sb.append("  		<condition column=\"TABLE_NAME\" name=\"tableName\" type=\"java.lang.String\" symbol=\"=\" alias=\"t\"/>\r\n ");
			   }
		   }
		 }
		  sb.append("    </query>\r\n ");
		  sb.append("  </query-mappings>\r\n ");
							 
		  String filePathName=paraForm.getUploadPath()+"/config/"+filePaths[0]+"/"+fileName+".xml";
		     Utils.generateFile(filePathName,sb);

		/**
		 * 生成下拉选择框的 xml    
		 */
		  //如果存在自定义的 下拉选择框
	   		boolean existCustomSelect=false;
	   		 for (int i=0;i<paraForm.getDataSourceTypes().length;i++){
	   			 if (Constant.DATASOURCETYPE_SQL.equals(paraForm.getDataSourceTypes()[i])){
	   				existCustomSelect=true;
	   				 break;
	   			 }
	   		 }
	   		 //dataSouce: [searchName:;type:;id:;displayField:{};conditionField:{};ordeby:]
	   	    if  (existCustomSelect){
	   	    	sb=new StringBuffer("");
	   	       sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n ");
	   	       sb.append("<easy-search-mappings>\r\n ");
		    	SeleListCustomVO selectCustom=null;
	   	    	List <SeleListCustomVO>  customLists= paraForm.getSelectCustoms();
	   	      for (int i=0;i<paraForm.getDataSourceTypes().length;i++){
	      		if (Constant.DATASOURCETYPE_SQL.equals(paraForm.getDataSourceTypes()[i])){  //是集合类型的
	      		   String  targetField=paraForm.getFieldEns()[i];
	      		   selectCustom=null;
	      		   for (int u=0;u<customLists.size();u++){
	      	 		   if (targetField.equals(customLists.get(u).getTargetField())){
	      				   selectCustom=customLists.get(u);
	     				   break;
	      			   }
	      		   }
	      	   if (selectCustom!=null){
	     	   	     fileName="easy-search-"+selectCustom.getSearchboxType();
	     	    	sb.append("<easy-search name=\"").append(selectCustom.getSearchName())
	     	    	  .append("\" desc=\"").append(selectCustom.getSearchDesc()).append("\">\r\n ");
	     	   	    sb.append("<sql>\r\n ");
	     	   		sb.append(selectCustom.getSearchSql()).append("\r\n");
	     	   		sb.append("</sql>\r\n ");
	     	   	   String []fieldCodes=selectCustom.getFieldCodes().split(",");
	     	   	   String []fieldNames=selectCustom.getFieldNames().split(",");
	     	   	   String []fieldTypes=selectCustom.getFieldTypes().split(",");
	     	       String []fieldWidths=selectCustom.getFieldWidths().split(",");
	     	    
	     	   	  for (int j=0;j<fieldCodes.length;j++){
	     	     	sb.append("<field name=\"").append(fieldNames[j])
	     	     	  .append("\" code=\"").append(fieldCodes[j]).append("\"");
	     	     	if (!"0".equals(fieldTypes[j])){
	     	     	   sb.append(" type=\"").append(fieldTypes[j]).append("\" /> \r\n");
	     	     	} else {
	     	     	   sb.append(" width=\"").append(fieldWidths[j]).append("\"/> \r\n");
	     	     	}
	     	   	  }
	     	   	if (selectCustom.getCondiColumns()!=null&&!"".equals(selectCustom.getCondiColumns())){
	      			 String []condiCols=selectCustom.getCondiColumns().split(",");
	      			 String []condiNames=selectCustom.getCondiNames().split(",");
	      			 String []condiTypes=selectCustom.getCondiTypes().split(",");
	      			 String []condiSymbols=selectCustom.getCondiSymbols().split(",");
	      			 String []condiAlias=selectCustom.getCondiAlias().split(",");
	      		   for (int x=0;x<condiCols.length;x++){
	    		    sb.append("<condition column=\"").append(condiCols[x])
	    		      .append("\" name=\"").append(condiNames[x])
	    		      .append("\" type=\"").append(condiTypes[x])
	    		      .append("\" symbol=\"").append(condiSymbols[x])
	    		      .append("\" alias=\"").append(condiAlias[x]).append("\"/> \r\n");
	      		    }
	     	   	 }
	     		 if (selectCustom.getOrderby()!=null&&!"".equals(selectCustom.getOrderby())){
			       sb.append("<orderby>").append(selectCustom.getOrderby()).append("</orderby>\r\n ");
	     		 }
	    		  sb.append("</easy-search>\r\n ");
	    		  
	      		 } // selectCustom!=null结束
	      		} //是集合类型的
	   	      } //for end
	   	      sb.append("</easy-search-mappings>\r\n");
	   	    }
		/*    <sql>
		       select t.id,t.contracts_code,t.contracts_name  from PM_CONTRACTS_LIST t where 1=1 
				</sql>
		<field name="id" code="id" type="hidden" />
		    <field name="项目模板编号" code="code" width="100" />
		    <field name="项目模板名称" code="name" width="100" />
		    <field name="版本号" code="version" width="100" />
		    <field name="是否启用" code="status" width="60"  />
		    <field name="node_type" code="node_type" type="hidden" />
		    <field name="parent_id" code="parent_id" type="hidden" />
		    <field name="full_id" code="full_id" type="hidden" />
		    <field name="full_name" code="full_name" type="hidden" />
		    <field name="sequence" code="sequence" type="hidden" />
		    	<condition column="NODE_TYPE" name="parentNodeType" type="java.lang.String" symbol="=" alias="t"/>
				<orderby>id asc</orderby>
		    <orderby>proc_id,proc_unit_id,sub_proc_unit_Id</orderby>
		    
			*/
	   	 

	  	   filePathName=paraForm.getUploadPath()+"/config/"+filePaths[0]+"/"+fileName+".xml";
		     Utils.generateFile(filePathName,sb);
	   	    return "";
	}

}
