package cn.autocode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class AutoCreateBeanXML_M_BASE {	
	
	public static String basePackage = "cn";
	public static String secondPackage = "im";
	//public static String IP = "192.168.8.57";
	public static String URL = "jdbc:mysql://10.10.10.203:3306/zndb?useUnicode=true&characterEncoding=UTF-8";
	public static String USER = "zn06";
	public static String PWD = "znznzn8";
	public static String PROJECT = "ext";
	public static String localPROJECT = "ext";
	public static String WEBCONFIG = "";//WebRoot
	private String model = "";
	String baseDir=System.getProperty("user.dir")+File.separator;
	String srcDir=System.getProperty("user.dir")+File.separator+"/src";
	String sourceDir=System.getProperty("user.dir")+File.separator+"/src/cn/autocode";
	private Map<String, ArrayList> subPackageData =Collections.synchronizedMap(new TreeMap());
	private Map<String, ArrayList> nameData =Collections.synchronizedMap(new TreeMap());
	private Map<String, List> usetable =Collections.synchronizedMap(new TreeMap());
	public static void main(String[] args) {
		AutoCreateBeanXML_M_BASE c=new AutoCreateBeanXML_M_BASE();
		//不启用功能
		//c.loadCreate();
		c.init();
		c.dealConnAndTable();
	}	
	//加载模块及表格
	//加载模块及表格
	public void loadCreate(){	
		try{
			ArrayList list =new ArrayList();				
			ArrayList nameList =new ArrayList();	
			String fullPathName = sourceDir +"/db.txt";
			FileInputStream fis = new FileInputStream(fullPathName); //创建文件输入流
			InputStreamReader isr = new InputStreamReader(fis,"GBK"); //指定读取流为UTF-8编码格式
			BufferedReader br = new BufferedReader(isr);
			StringBuffer sb = new StringBuffer();
			String line = br.readLine();
			String model = "";
			while (line != null) {
				line = br.readLine();
				if (line != null) {
					int basepackage_n = line.indexOf("basepackage");
					int secondpackage_n = line.indexOf("secondpackage");
					int dburl_n = line.indexOf("dburl");
					int dbuser_n = line.indexOf("dbuser");
					int dbpwd = line.indexOf("dbpwd");
					int value = line.indexOf("value");
					if(basepackage_n!=-1){
						basePackage = line.substring(value+7,line.length()-1);
					}
					if(secondpackage_n!=-1){
						secondPackage = line.substring(value+7,line.length()-1);
					}
					if(dburl_n!=-1){
						URL = line.substring(value+7,line.length()-1);
					}
					if(dbuser_n!=-1){
						USER = line.substring(value+7,line.length()-1);
					}
					if(dbpwd!=-1){
						PWD = line.substring(value+7,line.length()-1);
					}
				}
			}
			br.close();
			isr.close();
			fis.close();
		}catch(Exception e){
			System.out.println("==读取文件异常="+e.getLocalizedMessage());
		}
	}
	//加载模块及表格
	public void init(){	
		try{
			ArrayList list =new ArrayList();				
			ArrayList nameList =new ArrayList();	
			list =new ArrayList();
			nameList =new ArrayList();
			//String sourcePath = System.getProperty("user.dir")+File.separator+"source/";
			String fullPathName = sourceDir +"/source.txt";
			FileInputStream fis = new FileInputStream(fullPathName); //创建文件输入流
			InputStreamReader isr = new InputStreamReader(fis,"GBK"); //指定读取流为UTF-8编码格式
			BufferedReader br = new BufferedReader(isr);
			StringBuffer sb = new StringBuffer();
			String line = br.readLine();
			String model = "";
			while (line != null) {
				line = br.readLine();
				if (line != null) {
					//System.out.println("=line="+line);
					int nModel = line.indexOf("model");
					int nCount = line.indexOf("count");
					int nTable = line.indexOf("table");
					int nName = line.indexOf("name");
					if(nModel!=-1&&nCount!=-1){
						if(model != ""){
							this.subPackageData.put(model,list);
							this.nameData.put(model,nameList);
						}
						model = line.substring(nModel+7,nCount-2);
						//System.out.println("=model="+model);
						list =new ArrayList();				
						nameList =new ArrayList();
					}
					if(nTable!=-1&&nName!=-1){
						String table = line.substring(nTable+7,nName-2);	
						String name = line.substring(nName+6,line.length()-1);
						//System.out.println("=table="+table+"=name="+name);
						if(table.length()>0&&name.length()>0){
							list.add(table);
							nameList.add(name);
						}
					}
				}
			}
			br.close();
			isr.close();
			fis.close();
			//System.out.println(list.toString());
			//System.out.println(nameList.toString());
			this.subPackageData.put(model,list);
			this.nameData.put(model,nameList);
		}catch(Exception e){
			System.out.println("==读取文件异常="+e.getLocalizedMessage());
		}
	}
	
	public  void dealConnAndTable(){
        Connection connection = null;
        PreparedStatement pstmt = null;
        List tablelist = new ArrayList();
        List allcreatetablelist = new ArrayList();
        //AutoModelCONFIG autoModel = new AutoModelCONFIG();
        int tableCount = 1;
        try {
            //mysql
        	Class.forName("org.gjt.mm.mysql.Driver");
        	connection = (Connection) DriverManager.getConnection(URL, USER, PWD);
            DatabaseMetaData dbMetaData=connection.getMetaData();
            ResultSet tableRet=dbMetaData.getTables(null, "%","%",new String[]{"TABLE"});
            Map zjmap = new HashMap();
            Map modelmap = new HashMap();
            ArrayList readOnlyFieldList=new ArrayList();
            List alltableList = new ArrayList();
            Map allmap = new HashMap();
            boolean bb = true;
            while(tableRet.next()) {
            	String tablename= tableRet.getString("TABLE_NAME");
            	//tablename = tablename.toLowerCase();
            	//System.out.println("=tablename="+tablename);
            	allmap.put(tablename, tablename);
            }
            Set<String> subPackageSet= this.subPackageData.keySet();
    		Iterator it=subPackageSet.iterator();
    		String chinaName = "";
    		while(it.hasNext()){
    			String key=(String) it.next();
    			ArrayList list= subPackageData.get(key);
    			ArrayList namelist= nameData.get(key);
    			List hastableList = new ArrayList();
    			for(int i=0;i<list.size();i++){
    				String storeTableName = (String)list.get(i);
    				chinaName = (String)namelist.get(i);
    				System.out.println("=tableCount="+tableCount+"=table="+storeTableName+"=chinaName="+chinaName+(i+1));
    				if(allmap.containsKey(storeTableName)){
    					hastableList.add(storeTableName);
    					allcreatetablelist.add(storeTableName);
    	            	dealStruct(dbMetaData,basePackage,secondPackage,key,storeTableName,readOnlyFieldList,chinaName);
    				}
    				tableCount++;
    			}
    			modelmap.put(key, hastableList);    			
    			//autoModel.initMode(basePackage,secondPackage, key,PROJECT,localPROJECT);
    		}
    		/*
    		autoModel.createModelService(basePackage,secondPackage,modelmap);
    		autoModel.createAllMapConfig(basePackage,secondPackage,modelmap);
    		//autoModel.createAllDWRConfig(basePackage,secondPackage,modelmap);
    		//autoModel.createAllSpringDaoConfig(basePackage,secondPackage,modelmap);
    		autoModel.createConfMapConfig(basePackage,secondPackage,modelmap);
    		//c2.createAllSpringServiceConfig(basePackage,secondPackage,modelmap); 
    		 */
    		System.out.println("任务执行完成");
        }
        catch (Exception e){
        	e.printStackTrace();
        }
    }
	
	public void dealStruct(DatabaseMetaData dbMetaData,String basePackage,String secondPackage,String key,String tableName,ArrayList readOnlyFieldList,String chinaName) throws Exception{
		String tableName1 = tableName;//tableName.toUpperCase();		
		List pkList = new ArrayList();
		List fieldList = new ArrayList();
		List fieldChineseList = new ArrayList();
		List typeList = new ArrayList();
		List fieldSizeList = new ArrayList();
		List defaultList = new ArrayList();
		ResultSet colRet = dbMetaData.getColumns(null,"%", tableName1,"%");		
		ResultSet pkRSet = dbMetaData.getPrimaryKeys(null,null,tableName1);		
		while(pkRSet.next()){
			String dbColumnName = (String) pkRSet.getObject(4);
			pkList.add(dbColumnName);
		}		
    	while(colRet.next()) {
    	   String columnName = colRet.getString("COLUMN_NAME");
    	   String columnType = colRet.getString("TYPE_NAME");  
    	   String columnSize = colRet.getString("COLUMN_SIZE");
    	   String remarks = colRet.getString("REMARKS");    
    	   String defaultValue = colRet.getString("COLUMN_DEF");    	  
    	   fieldList.add(columnName);
    	   fieldChineseList.add(remarks);
    	   typeList.add(columnType);
    	   fieldSizeList.add(columnSize); 
    	   defaultList.add(defaultValue);
    	}
    	AutoModelJAVA aj = new AutoModelJAVA();
    	aj.initMode(basePackage,secondPackage,key,PROJECT,localPROJECT);
    	aj.createClassJavaBean(basePackage,secondPackage,key,tableName,fieldList,typeList,fieldSizeList,fieldChineseList,chinaName);
    	aj.createDAOJava(basePackage, secondPackage,key, tableName, fieldList, typeList);
    	aj.createServiceJava(basePackage,secondPackage, key, tableName, fieldList, typeList,pkList,chinaName);
    	aj.createActionJava(basePackage,secondPackage, key, tableName, fieldList, typeList,pkList,chinaName);
    	aj.createObjXml(basePackage,secondPackage, key, tableName, fieldList, typeList,pkList);
    	//aj.createObjXml_new(basePackage,secondPackage, key, tableName, fieldList, typeList,pkList,defaultList);
    	//aj.createObjXml_ext(basePackage,secondPackage, key, tableName, fieldList, typeList,pkList);
    	/**/
    	AutoModelWEB cw = new AutoModelWEB();
    	cw.initMode(secondPackage,key);
    	cw.createWebJSP(basePackage,secondPackage,key, tableName, fieldList, typeList,fieldSizeList,pkList,fieldChineseList,chinaName);
    	cw.createWebJSP_show(basePackage,secondPackage,key, tableName, fieldList,typeList,fieldSizeList,pkList,fieldChineseList);
    	cw.createWebJS(basePackage, secondPackage,key, tableName, fieldList, typeList,pkList,fieldChineseList,chinaName);
    }
	
	//检查数据库中是否存在表
	public boolean tableIn(String tableName){
		boolean ret=false;
		Set<String> subPackageSet= this.subPackageData.keySet();
		Iterator it=subPackageSet.iterator();
		while(it.hasNext()){
			String key=(String) it.next();
			model = key;
			ArrayList list= subPackageData.get(key);
			Iterator sit=list.iterator();
			while(sit.hasNext()){
				String storeTableName=(String) sit.next();
				//System.out.println(storeTableName + "==tableIn=="+ tableName);
				if(storeTableName.equalsIgnoreCase(tableName)==true) 
					return true;
			}
		}
		return ret;
	}
}
