package com.lz.flt;


import com.lz.common.utils.StringUtil;
import org.springframework.util.ResourceUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 代码生成器
 */
public class Create {
	private static String url = "jdbc:mysql://172.16.157.238:3306/lz_management?useUnicode=true&characterEncoding=utf8&useInformationSchema=true";
	private static String mysqlUser = "ldd_biz";
	private static String mysqlPassword = "Hello1234";
	private static String dbClass = "com.mysql.jdbc.Driver";
	private static Connection conn ;
	public static File file =null;
	public static String generator_props = "/src/test/java/com/lz/flt/generator.properties";
	public static String fileSavePath = "src/test/tmp";

	static {
		try {
			conn = getDblink(dbClass,url,mysqlUser,mysqlPassword);
			String path = ResourceUtils.getURL("classpath:").getPath();
			System.out.println(path);
			String dir = null;
			if (StringUtil.isNotBlank(path)) {
				dir = path.split("target")[0];
			}
			file = new File(dir + generator_props);
			fileSavePath = dir + fileSavePath;
			System.out.println("===fileSavePath====="+fileSavePath);
			File newFile = new File(fileSavePath);
			if(!newFile.exists()){
				newFile.mkdirs();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}
	public static void main(String[] args) {
		Create ot=new Create();
		String [] tableNames = {"lz_flow_manager"};
		try {
			ot.generatorCode(tableNames);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void generatorCode(String[] tableNames) throws Exception{
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		for(String tableName : tableNames){
			//查询表信息
			Map<String, String> table = queryTable(tableName);
			//查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			//生成代码
			GenUtils.generatorCode(table, columns );
		}
	}

	private List<Map<String,String>> queryColumns(String tableName) {
		List<Map<String,String>> mapList = new ArrayList<>();
		try {
			String showColumn = "select column_name columnName, data_type dataType, column_comment columnComment, column_key columnKey, extra from information_schema.columns where table_name = '"+ tableName +"' and table_schema = (select database()) order by ordinal_position";
			Statement stateMent_table = (Statement) conn.createStatement();
			// 查询该数据库所有的表名
			ResultSet rs = stateMent_table.executeQuery(showColumn);
			ResultSetMetaData rsmd = rs.getMetaData();
//			int colCount=rsmd.getColumnCount();
//			List<String> colNameList=new ArrayList<String>();
//			for(int i=0;i<colCount;i++){
//				colNameList.add(rsmd.getColumnName(i+1));
//			}
			while (rs.next()){
				Map<String,String>map = new HashMap<>();
				for(int i = 0 ; i < rsmd.getColumnCount() ; i++){
					String col_name = lineToHump(rsmd.getColumnName(i+1));
					String col_value = rs.getString(col_name);
					if(col_value == null){
						col_value = "";
					}
					map.put(col_name, col_value);
				}
				mapList.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return mapList;
	}

	private Map<String,String> queryTable(String tableName) {
		Map<String,String> map = null;
		try {
			String executeSql = "select TABLE_NAME, ENGINE, TABLE_COMMENT , CREATE_TIME  from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = (select database()) and TABLE_NAME = '"+tableName+"'";
			Statement stateMent_table = (Statement) conn.createStatement();
			// 查询该数据库所有的表名
			ResultSet rs = stateMent_table.executeQuery(executeSql);
			ResultSetMetaData rsmd = rs.getMetaData();
			int colCount=rsmd.getColumnCount();
			map = new HashMap<>();
			List<String> colNameList=new ArrayList<String>();
			for(int i=0;i<colCount;i++){
				colNameList.add(rsmd.getColumnName(i+1));
			}
			while (rs.next()){
				for(int i=0;i<colCount;i++) {
					String key = colNameList.get(i);
					Object value = rs.getString(colNameList.get(i));
					map.put(key, value.toString());
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return map;
	}


	/**
	 * 连接数据库
	 *
	 * @param dbClass
	 * @param url
	 * @param MysqlUser
	 * @param mysqlPassword
	 * @return
	 */
	public static Connection getDblink(String dbClass, String url, String MysqlUser, String mysqlPassword) {
		Connection conn = null;
		try {
			Class.forName(dbClass); // 加载驱动
			conn = DriverManager.getConnection(url, MysqlUser, mysqlPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	private static Pattern linePattern = Pattern.compile("_(\\w)");
	/**下划线转驼峰*/
	public static String lineToHump(String str) {
		str = str.toLowerCase();
		Matcher matcher = linePattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
		}
		matcher.appendTail(sb);
		return sb.toString();
	}
}
