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.data.query.model.QueryModel;
import com.huigou.data.repository.GeneralRepository;
import com.huigou.uasp.builder.BuildFilerInter;
import com.huigou.uasp.builder.vo.ParamFormVO;

import com.huigou.uasp.util.Utils;

@Service("buildApplicationFile")
public class BuildApplicationFile implements BuildFilerInter {


	
	@Override
	public String generateFile(ParamFormVO paraForm,List<Map<String, Object>> fieldList)  throws Exception{
		  File file=new File(paraForm.getSrcPath()+"/application");
		  if (!file.exists()){
			  file.mkdir();
		  }
		  file=new File(paraForm.getSrcPath()+"/application/impl");
		  if (!file.exists()){
			  file.mkdir();
		  }

		  String clsName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName());
		  String serviceName=clsName;  //首字母小写
		  clsName=Utils.toUpperCaseFirstOne(clsName); // 首字母大写
		  String entityName=clsName;
		  clsName+="Application";
		   StringBuffer sb=new StringBuffer("");
		  
		   sb.append("package ").append(paraForm.getPackageName()).append(".application;\r\n ");

		   sb.append("import java.util.List;\r\n");
		   sb.append("import java.util.Map;\r\n");

		   sb.append("import ").append(paraForm.getPackageName()).append(".domain.model.").append(entityName).append(";\r\n");
		   sb.append("import ").append(paraForm.getPackageName()).append(".domain.query.").append(entityName).append("QueryRequest;\r\n");
		   sb.append("\r\n");

		   sb.append("public interface ").append(clsName).append(" { \r\n");
		   sb.append("//查询方法\r\n");
		   sb.append(" Map<String,Object> query").append(entityName).append("(").append(entityName).append("QueryRequest queryRequest);\r\n");
		   sb.append("//加载实体\r\n");
		   sb.append(" ").append(entityName).append("  load").append(entityName).append("(String id);\r\n");
		   sb.append("//删除对象 \r\n");
		   sb.append("  void delete").append(entityName).append("ByIds(List<String> ids);\r\n");
		   sb.append("\r\n");
		   sb.append("}");
		     
			   
		 	//CompileUtil Utils=new CompileUtil();
			String realPath=paraForm.getUploadPath()+"/"+paraForm.getPackageName().replaceAll("\\.","/");
			realPath+="/application/"+clsName+".java";
			Utils.generateJava(realPath, sb);
			
			//String strs=Utils.generateClass(realPath,clsName);
			
			//**生成实现的接口**/
			
			   sb=new StringBuffer("");
			   clsName=entityName+"ApplicationImpl";
			   
			   sb.append("package ").append(paraForm.getPackageName()).append(".application.impl;\r\n ");

			   sb.append("import java.util.List;\r\n");
			   sb.append("import java.util.Map;\r\n");
			   
			   sb.append("import org.springframework.util.Assert;\r\n");
			   sb.append("import com.huigou.util.SDO;\r\n");
		
			   sb.append("import com.huigou.uasp.util.Constant;\r\n");
			   sb.append("import org.springframework.transaction.annotation.Transactional;\r\n");
			   
			   sb.append("import com.huigou.uasp.bmp.common.application.BaseApplication;\r\n");
			   sb.append("import com.huigou.data.query.model.QueryDescriptor;\r\n");
			   sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
			   sb.append("import org.springframework.stereotype.Service;\r\n");
			   sb.append("import com.huigou.data.query.model.QueryModel;\r\n");
			   sb.append("import ").append(paraForm.getPackageName()).append(".domain.model.").append(entityName).append(";\r\n");
			   sb.append("import ").append(paraForm.getPackageName()).append(".domain.query.").append(entityName).append("QueryRequest;\r\n");
			   sb.append("import ").append(paraForm.getPackageName()).append(".repository.").append(entityName).append("Repository;\r\n");
			   sb.append("import ").append(paraForm.getPackageName()).append(".application.").append(entityName).append("Application;\r\n");
			   
			   sb.append("\r\n");
               sb.append("@Service(\"").append(serviceName).append("Application\")\r\n");
				
               sb.append("public class ").append(clsName).append(" extends BaseApplication implements ")
               .append(entityName).append("Application").append(" { \r\n");
                 sb.append("\r\n");
				// config文件路径
                 String filePaths[]=paraForm.getFormPath().split("/");
				sb.append(" static String QUERY_XML_FILE_PATH = \"config/").append(filePaths[0]).append("/")
				.append(serviceName).append(".xml\";\r\n");

				sb.append("@Autowired\r\n");
				sb.append(" private ").append(entityName).append("Repository ").append(serviceName).append("Repository;\r\n");
				sb.append("\r\n");
				
				sb.append("@Override\r\n");
				sb.append("public Map<String, Object> query").append(entityName).append("(").append(entityName).append("QueryRequest queryRequest) { \r\n ");
				boolean hasDateSearchCond=false;
			   if (paraForm.getSearchFields()!=null&&paraForm.getSearchFields().length>0){//有查询条件
				   for (int i=0;i<paraForm.getSearchFields().length;i++){
					  if ("1".equals(paraForm.getSearchFields()[i])){ //
						 if  ("date".equals(paraForm.getFieldTags()[i])){ //日期格式的条件
							 hasDateSearchCond=true;
							 break; 
						 }
					  }
				   }
			   }
			   if (hasDateSearchCond){  //如果有date类型的  其它条件  也只能在此添加 
				   sb.append("	  String sql=getQueryDescriptor(\"").append(serviceName).append("\").getSql();\r\n");
				   sb.append("	 QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor(\"").append(serviceName).append("\"), queryRequest);\r\n");
				   for (int i=0;i<paraForm.getSearchFields().length;i++){
					           String searchField="";
					  if ("1".equals(paraForm.getSearchFields()[i])){ //
					  	  searchField=paraForm.getFieldEns()[i];
						  String search_Field=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,searchField);//转成下划线
						if  ("date".equals(paraForm.getFieldTags()[i])){ //日期格式的条件
							sb.append("	 if  (queryRequest.getStart").append(Utils.toUpperCaseFirstOne(searchField))
							.append("()!=null){ \r\n");
				  
							sb.append("	 	  sql+=\" and t.").append(search_Field).append(" >= to_date('\"+queryRequest.getStart")
							.append(Utils.toUpperCaseFirstOne(searchField)).append("()+\"','yyyy-mm-dd')\";\r\n"); 
							sb.append("	  } \r\n");
				    
							sb.append("	 if  (queryRequest.getEnd").append(Utils.toUpperCaseFirstOne(searchField))
							.append("()!=null){ \r\n");
				   
							sb.append("	 	  sql+=\" and t.").append(search_Field).append(" <= to_date('\"+queryRequest.getEnd")
							.append(Utils.toUpperCaseFirstOne(searchField)).append("()+\"','yyyy-mm-dd')\";\r\n"); 
							sb.append("	   } \r\n");
						  } else { //非日期格式的 
							  sb.append("	 if  (queryRequest.get").append(Utils.toUpperCaseFirstOne(searchField))
							     .append("()!=null){ \r\n");
							  if (paraForm.getValidatorTypes().length>i){
							   if  ("string".equals(paraForm.getValidatorTypes()[i])){  //字符型 使用like 
					              sb.append("	 	  sql+=\" and t.").append(search_Field).append(" like '%\"+queryRequest.get")
				                    .append(Utils.toUpperCaseFirstOne(searchField)).append("()+\"%'\";\r\n");
							   } else {  
			                      sb.append("	 	  sql+=\" and t.").append(search_Field).append(" =\"+queryRequest.get")
			                        .append(Utils.toUpperCaseFirstOne(searchField)).append("();\r\n");
							   }
							  }
							  sb.append("	   } \r\n"); 
						  }
						 }
				   }
			       sb.append("	  queryModel.setSql(sql);\r\n");
				   sb.append("  return this.sqlExecutorDao.executeSlicedQuery(queryModel);\r\n");
				   
			   } else {  //默认查询  不用拼装sql
				   sb.append("	 return this.sqlExecutorDao.executeSlicedQuery(getQueryDescriptor(\"").append(serviceName).append("\"), queryRequest);\r\n");
			   }
				sb.append("}\r\n");
				
			
			    
				sb.append(" \r\n");
				sb.append("private QueryDescriptor getQueryDescriptor(String  queryName) {\r\n");
				sb.append("   return this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, queryName);\r\n");
				sb.append(" } \r\n");
				sb.append(" \r\n");
				
				sb.append("@Override\r\n");
				sb.append("public ").append(entityName).append("  load").append(entityName).append("(String id) {\r\n");
				sb.append("  Assert.hasText(id, Constant.ID_NOT_BLANK);\r\n");
				sb.append("	 return this.").append(serviceName).append("Repository.findOne(id);\r\n");
				sb.append("}\r\n");
				sb.append(" \r\n");
				
				sb.append(" @Transactional\r\n");
				sb.append(" @Override\r\n");
				sb.append("public void delete").append(entityName).append("ByIds(List<String> ids) {\r\n");
				sb.append("   List<").append(entityName).append("> list = this.").append(serviceName).append("Repository.findAll(ids); \r\n");
				sb.append("   this.").append(serviceName).append("Repository.delete(list);\r\n");
				sb.append("  }\r\n");
				sb.append(" \r\n");
				
				
				  sb.append("}");
			     
			 			 	
				 realPath=paraForm.getUploadPath()+"/"+paraForm.getPackageName().replaceAll("\\.","/");
				 realPath+="/application/impl/"+clsName+".java";
				return Utils.generateJava(realPath, sb);

	}

}
