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.util.Utils;

@Service("buildEntityFile")
public class BuildEntityFile implements BuildFilerInter {
	

	private List<Map<String, Object>> fieldList;

	
	@Override
	public String generateFile(ParamFormVO paraForm,List<Map<String, Object>> fieldList) throws Exception{
		  File file=new File(paraForm.getSrcPath()+"/domain");
		  if (!file.exists()){
			  file.mkdir();
			  file=new File(paraForm.getSrcPath()+"/domain/model");
			  file.mkdir();
		  }
		  String clsName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName());
		  clsName=Utils.toUpperCaseFirstOne(clsName);
		// Java 源代码
		       StringBuffer sb=new StringBuffer("");
				sb.append("package ").append(paraForm.getPackageName()).append(".domain.model;\r\n ");
				
				sb.append("import java.util.Date;\r\n ");
				sb.append("import java.lang.Double;\r\n ");

				sb.append("import javax.persistence.Column;\r\n ");
				sb.append("import javax.persistence.Embedded;\r\n ");
				sb.append("import javax.persistence.Entity;\r\n ");
				sb.append("import javax.persistence.EntityListeners;\r\n ");
				sb.append("import javax.persistence.Table;\r\n ");
				sb.append("import javax.persistence.Transient;\r\n ");

				sb.append("import com.huigou.data.domain.listener.CreatorAndModifierListener;\r\n ");
				sb.append("import com.huigou.data.domain.model.AbstractEntity;\r\n ");
				sb.append("import com.huigou.data.domain.model.Creator;\r\n ");
				sb.append(" \r\n");
				
				String colName="",dataType="",comments="",dataLength="",dtype="String";
		    	int dataScale=0;
		    	Map map=null;
				boolean isCreator=false;
				
				for (int u=0;u<fieldList.size();u++){
					map=fieldList.get(u);
					colName=map.get("attrCode").toString(); //columnName-->attrCcode
					if ("created_by_id".equals(colName)){
						isCreator=true;
						break;
					}
				}
				sb.append(" @Entity\r\n ");
				sb.append("@Table(name = \"").append(paraForm.getTableName()).append("\") \r\n");
				if (isCreator){
				  sb.append("@EntityListeners({ CreatorAndModifierListener.class }) \r\n");
				}
				sb.append("public class "+clsName+" extends AbstractEntity{ \r\n ");
				sb.append("  private static final long serialVersionUID = 1L; \r\n ");
				    	
			for (int u=0;u<fieldList.size();u++){
				map=fieldList.get(u);
				colName=map.get("attrCode").toString();
				dataType=map.get("fieldType").toString();
				dataLength=map.get("fieldLength").toString();
				comments=map.get("attrName").toString();
				dataScale=!"".equals(map.get("fieldDecimal"))?Integer.parseInt(map.get("fieldDecimal").toString()):0;
				//改在sql中去掉不生成的字段  ？？
			  if (!"id".equals(colName)&&!"version".equals(colName)
				  &&!"created_date".equals(colName)&&!"created_by_name".equals(colName)&&!"created_by_id".equals(colName)
					  ) {
			   sb.append("/** \r\n").append("  * ").append(comments).append("\r\n */\r\n ");
			   sb.append( " @Column(name=\"").append(colName).append("\",length=").append(dataLength)
			   .append(") \r\n ");
			
			   colName=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,colName);
			
			   // if ("VARCHAR2".equals(dataType)){
				//  dtype="String";
			  //  }   
			     // 字段类型统一为小写  string,date,number...
			    if ("date".equals(dataType)){
				  dtype="Date";
			    }
			    if ("number".equals(dataType)){   
				   if (dataScale>0){
				     dtype="Double";   //数据库如果是mysql ... ？？？？
				   } else {
					 dtype="Integer";
				   }
			     }
			
			   sb.append(" private ").append(dtype).append(" ").append(colName).append("; \r\n "); 
			   sb.append(" \r\n");
			   sb.append(" public ").append(dtype).append(" get").append(Utils.toUpperCaseFirstOne(colName)).append("() { \r\n ");
			   sb.append("    return ").append(colName).append("; \r\n } \r\n ");
				
			   sb.append("public void set").append(Utils.toUpperCaseFirstOne(colName)).append("(").append(dtype).append("  ").append(colName).append(") { \r\n ");
			   sb.append("  this.").append(colName).append(" = ").append(colName).append("; \r\n  } \r\n ");
			
			 }

			} // for ended
			 if (isCreator){
					sb.append(" /** \r\n");
				    sb.append(" * 创建人信息 \r\n");
				    sb.append(" */ \r\n "); 
				    sb.append(" @Embedded \r\n");
				    sb.append(" private Creator creator; \r\n" );
			 }
			sb.append("}");
	
			
			String realPath=paraForm.getUploadPath()+"/"+paraForm.getPackageName().replaceAll("\\.","/");
			realPath+="/domain/model/"+clsName+".java";
			return	Utils.generateJava(realPath, sb);
				
			///	String strs=Utils.generateClass(realPath,clsName);
		/*     Class<? extends Object> cls = null;
		    try {
			//   DynamicCompile dynamicCompile = new DynamicCompile();
			 //  cls = dynamicCompile.compileToClass("com.pm." + clsName,
				//	sb.toString());
			   // System.out.println("==sdfsd====" + cls.newInstance());
							
						// 生成对象
					  Object obj = Class.forName(packageName+".domain.model."+clsName).newInstance();
						cls = obj.getClass();
						// 调用sayHello方法
						String methodName="setId"; 
						Method m = cls.getMethod(methodName, String.class);
					//	Object obj=cls.newInstance();
						String str = (String) m.invoke(obj, "ss19181758701");
						
						 methodName="getId"; 
						 m=cls.getMethod(methodName);
						 str = (String) m.invoke(obj);
						System.out.println("动态编译成功   调用：=="+str);
					//}
				} catch (Exception e1) {
					// TODO 自动生成 catch 块
					 e1.printStackTrace();;
				
				}
          */
	}

}
