package org.springblade.dataextraction.kit;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @Desc 实体类生成器
 * @Author William
 * @DateTime 2022 下午4:17:55
 */
public class CodeGen {
	private static Connection connection = null;
	static {
		try {
//			Class.forName("oracle.jdbc.OracleDriver");
//			String url = "jdbc:mysql://39.103.207.159:3306/digital_operation";
			String url = "jdbc:oracle:thin:@10.0.17.108:8093/cs1747";
//			String url = "jdbc:clickhouse://39.103.133.74:8123/ads";
			Properties prop = new Properties();
			prop.put("user", "YYOS");
			prop.put("password", "Mldsi3_hsyE9_8ekV_234dsLP");

//			prop.put("user", "digital");
//			prop.put("password", "Dgb6inMBYtsMT#rS");

//			prop.put("user", "default");
//			prop.put("password", "LiantongbiYidonghao66");

			prop.put("serverTimezone", "GMT+8");
			prop.put("remarks", "true");
			prop.put("useInformationSchema", "true");
			prop.put("remarksReporting", "true");
			connection = DriverManager.getConnection(url, prop);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static List<Map> getOracleTable(String Table) throws SQLException {
		List<Map> list = new ArrayList<Map>();
		try {
			DatabaseMetaData metaData = connection.getMetaData();
			// getColumns(java.lang.String catalog, java.lang.String schema,java.lang.String
			// table, java.lang.String col)
			ResultSet cols = metaData.getColumns(null, "YYOS", "V_FCT_FETCHED_ORDERS_HZ", null);
			while (cols.next()) {
				Map map = new HashMap();
				String columnName = cols.getString("COLUMN_NAME");
				String columnType = cols.getString("TYPE_NAME");
				int datasize = cols.getInt("COLUMN_SIZE");
				int digits = cols.getInt("DECIMAL_DIGITS");
				int nullable = cols.getInt("NULLABLE");
				String remarks = cols.getString("REMARKS");
				map.put("columnName", columnName);
				map.put("columnType", columnType);
				map.put("datasize", datasize);
				map.put("remarks", remarks);
				list.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			connection.close();
		}
		return list;
	}

	/**
	 * 把Oracle字段类型 转化为 java类型
	 * 
	 * @param sqlType 字段类型
	 * @param size    字段大小
	 * @param scale   默认=0
	 * @return
	 */
	public static String oracleSqlType2JavaType(String sqlType, int size, int scale) {
		if (sqlType.equals("integer")) {
			return "Integer";
		} else if (sqlType.equals("long")) {
			return "Long";
		} else if (sqlType.equals("float") || sqlType.equals("float precision") || sqlType.equals("double")
				|| sqlType.equals("double precision")) {
			return "BigDecimal";
		} else if (sqlType.equals("number") || sqlType.equals("decimal") || sqlType.equals("numeric")
				|| sqlType.equals("real")) {
			return scale == 0 ? (size < 10 ? "Integer" : "Long") : "BigDecimal";
		} else if (sqlType.equals("varchar") || sqlType.equals("varchar2") || sqlType.equals("char")
				|| sqlType.equals("nvarchar") || sqlType.equals("nchar")) {
			return "String";
		} else if (sqlType.equals("datetime") || sqlType.equals("date") || sqlType.equals("timestamp")) {
			return "Date";
		}
		return "String";
	}

	public static String getItems(List<Map> map, String tablename) {
		String className = StrKit.convertToCamelCase(tablename);
		
		// 记得转化成小写
		StringBuffer sb = new StringBuffer();
		sb.append("package org.springblade.dataextraction.enity;\n");
		sb.append("\r\n");
		sb.append("import java.util.Date;\r\n");
		sb.append("import com.baomidou.mybatisplus.annotation.TableField;\r\n");
		sb.append("import com.baomidou.mybatisplus.annotation.TableName;\r\n");
		sb.append("import lombok.Data;\r\n");
		sb.append("\r\n");
		sb.append("/** \r\n " + " *  \r\n" + " * @author William Lin  \r\n" + " *\r\n" + "*/\r\n");
		sb.append("\r\n");
		sb.append("@Data\n");
		sb.append("@TableName(\"" + tablename + "\")\n");
		sb.append("public class " + className + "  implements java.io.Serializable  {\r\n");
		sb.append("\r\n");
		sb.append("private static final long serialVersionUID = 1L;\r\n");
		// 得到私有属性
		for (Map map0 : map) {
			String columnname = map0.get("columnName").toString();
			String columntype = map0.get("columnType").toString();
			String columnsize = map0.get("datasize").toString();
			String remarks = map0.get("remarks") == null ? "" : map0.get("remarks").toString();
			String javaType = oracleSqlType2JavaType(columntype.toLowerCase(), Integer.parseInt(columnsize), 0);

			String temp = "@TableField(value=\"" + columnname + "\")";
			String fieldName = StrKit.toUnderScoreCase(columnname.toLowerCase());
			temp += "\nprivate " + javaType + " " + fieldName + "; //" + remarks + "\r\n";
			sb.append("\r\n");
			sb.append(temp);
		}
		// 得到getter和setter
//		for (Map map0 : map) {
//			String columnname = map0.get("columnName").toString();
//			String columntype = map0.get("columnType").toString();
//			String columnsize = map0.get("datasize").toString();
//			String javaType = oracleSqlType2JavaType(columntype.toLowerCase(), Integer.parseInt(columnsize), 0);
//			String temp = "\tpublic " + javaType + " " + "get" + getUpperOne(columnname.toLowerCase()) + "(){\r\n";
//			String temp1 = "\t\treturn " + columnname.toLowerCase() + ";\r\n";
//			String temp2 = "\t}\r\n";
//			sb.append(temp + temp1 + temp2);
//			temp = "\tpublic void " + "set" + getUpperOne(columnname.toLowerCase()) + "(" + javaType + " "
//					+ columnname.toLowerCase() + "){\r\n";
//			temp1 = "\t\tthis." + columnname.toLowerCase() + " = " + columnname.toLowerCase() + ";\r\n";
//			temp2 = "\t}\r\n";
//			sb.append(temp + temp1 + temp2);
//		}
		sb.append("}");
		return sb.toString();

	}

	/**
	 * 把输入字符串的首字母改成大写
	 * 
	 * @param str
	 * @return
	 */
	public static String getUpperOne(String str) {
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		return new String(ch);
	}

	public static void main(String[] args) throws IOException {

		try {
			String tables = "V_FCT_FETCHED_ORDERS_HZ";
			String[] arr = tables.split(",");
			for (String string : arr) {
				String name = getUpperOne(string.toLowerCase());
				List<Map> map = getOracleTable(string);
				String a = getItems(map, string);
				String className = StrKit.convertToCamelCase(name);
				File file = new File("D://Download/" + className + ".java");
				if (!file.exists()) {
					file.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(file, true);// true表示在文件末尾追加
				fos.write(a.getBytes());
				fos.close();// 流要及时关闭
			}
			System.out.println("生成java完成");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
