package com.connor.mail;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class FindCshSql {

	public static void main(String[] args) {
		SqlUtil.getMySqlConnection();
		String nameString = args[0];
//		String nameString = "00085";
		String formula = args[1];
		String value = "";
//		String formula = "(%HW#^2+(2*%MO#+2*%MO#)^2)^0.5";
		try {
			//			String codeString = args[1];	
			if(formula.contains("%") && formula.contains("#")) {
				while (formula.contains("%") && formula.contains("#")) {
					int indexOf = formula.indexOf('%');
					int indexOf2 = formula.indexOf('#');
					String format = formula.substring(indexOf + 1, indexOf2);
					String oldChar = formula.substring(indexOf, indexOf2 + 1);
//					System.out.println("format====" + format);
					String sql = "select param_value from design_params_history where project_name like '%"+nameString+"%' and param_code = ? order by commit_num desc ";
					ResultSet read = SqlUtil.read(sql,new String[] {format});
					if(read.next()) {
						String paramVal = read.getString(1);
						//这里加上去数据库取值的逻辑 用format去数据库去相应的值
						formula = formula.replace(oldChar, paramVal);
					}else {
						return;
					}
				}
				if(formula.contains("(")) {
					Map<String,String> formulaMap = new HashMap<String, String>();
					//遍历分别计算括号里面的公式获得新的公式
					substring(formula, formula, formulaMap);
					formula = formulaMap.get("formula");
//					System.out.println("formula====" + formula);
					value = getVal(formula);
				}else {
					value = getVal(formula);
				}
			}else {
				String sql = "select param_value from design_params_history where project_name like '%"+nameString+"%' and param_code = ? order by commit_num desc ";
				ResultSet read = SqlUtil.read(sql,new String[] {formula});
				if(read.next()) {
					value = read.getString(1);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return;
		}finally {
			SqlUtil.freeAll();
		}

		double number = Double.parseDouble(value);
		DecimalFormat df = null;
		if(number > 1) {
			df = new DecimalFormat("#.00");
		}else {
			df = new DecimalFormat("0.00");
		}
		System.out.println(df.format(number));

	}
	
	private static int findMatchingParenthesis(String expression, int start) {
		int count = 0;
		for (int i = start + 1; i < expression.length(); i++) {
			if (expression.charAt(i) == '(') {
				count++;
			} else if (expression.charAt(i) == ')') {
				if (count == 0) {
					return i;
				}else {
					count--;
				}
			}
		}
		throw new IllegalArgumentException("Mismatched parentheses");
	}


	private static int getLastNumberLength(String expression, int start) {
		int length = start + 1;
		while (length < expression.length() 
				&& expression.charAt(length) != '*' 
				&& expression.charAt(length) != '+'
				&& expression.charAt(length) != '-'
				&& expression.charAt(length) != '/'
				&& expression.charAt(length) != '^') {
			length++;
		}
		return length - 1;
	}
	private static int getBeforeNumberLength(String expression, int start) {
		int length = start - 1;
		while (length >= 0 
				&& expression.charAt(length) != '*' 
				&& expression.charAt(length) != '+'
				&& expression.charAt(length) != '-'
				&& expression.charAt(length) != '/'
				&& expression.charAt(length) != '^') {
			length--;
		}
		return length + 1;
	}

	public static int countCharacter(String str, char characterToCount) {
		int count = 0;
		int index = str.indexOf(characterToCount);
		while (index >= 0) {
			count++;
			index = str.indexOf(characterToCount, index + 1);
		}
		return count;
	}
	public static void substring(String formula, String expression,Map<String,String> formulaMap) {
		//有括号
		if(formula.contains("(")) {	
			int indexStart = formula.indexOf("(");
			int indexEnd = findMatchingParenthesis(formula, indexStart);
			//截取括号内的公式
			String formula2 = formula.substring(indexStart + 1, indexEnd);
			if(formula2.contains("(")) {
				//获取括号内容如果还有括号继续获取括号里面的公式
				substring(formula2, expression,formulaMap);
			}else {
				//没有括号计算获得值替换原有公式
				String value = getVal(formula2);
				String formula3 = formula.replace("(" + formula2 + ")", value);
				expression = expression.replace("(" + formula2 + ")", value);

				//				expression = expression.replace("(" + formula + ")", formula3);
				//判断替换过后的公式是否还有括号
				if(expression.contains("(")) {
					int indexStart2 = expression.indexOf("(");
					int indexEnd2 = findMatchingParenthesis(expression, indexStart2);
					String formula4 = expression.substring(indexStart2 + 1, indexEnd2);
					substring(formula4, expression,formulaMap);
				}
			}
		}else {
			//没有括号直接计算获得值替换原有公式
			String value = getVal(formula);
			expression = expression.replace("(" + formula + ")", value);
			//判断替换过后的公式是否还有括号
			if(expression.contains("(")) {
				int indexStart2 = expression.indexOf("(");
				int indexEnd2 = findMatchingParenthesis(expression, indexStart2);
				String formula4 = expression.substring(indexStart2 + 1, indexEnd2);
				substring(formula4, expression,formulaMap);
			}else {
				if(expression.contains("^") 
						|| expression.contains("*")
						|| expression.contains("/")
						|| expression.contains("+")
						|| expression.contains("-")) {
					expression = getVal(expression);
					formulaMap.put("formula", expression);	
				}else {
					formulaMap.put("formula", expression);			
				}
			}

		}
	}
	public static String getVal(String formula2) {
		int indexOfStart = 0;
		int nextIndex = 0;
		int beforeIndex = 0;
		while (formula2.contains("^")) {
			indexOfStart = formula2.indexOf("^");
			nextIndex = getLastNumberLength(formula2, indexOfStart);
			beforeIndex = getBeforeNumberLength(formula2, indexOfStart);
			formula2 = jisuan(formula2, indexOfStart, beforeIndex, nextIndex, "^");
		}
		while (formula2.contains("*") || formula2.contains("/")) {
			int indexOfStart2 = formula2.indexOf("*");
			int indexOfStart3 = formula2.indexOf("/");
			if(indexOfStart2 < 0) {
				nextIndex = getLastNumberLength(formula2, indexOfStart3);
				beforeIndex = getBeforeNumberLength(formula2, indexOfStart3);
				formula2 = jisuan(formula2,indexOfStart3,beforeIndex, nextIndex,"/");
			}else if(indexOfStart3 < 0) {
				nextIndex = getLastNumberLength(formula2, indexOfStart2);
				beforeIndex = getBeforeNumberLength(formula2, indexOfStart2);
				formula2 = jisuan(formula2,indexOfStart2,beforeIndex, nextIndex,"*");
			}else if(indexOfStart2 > indexOfStart3) {
				nextIndex = getLastNumberLength(formula2, indexOfStart3);
				beforeIndex = getBeforeNumberLength(formula2, indexOfStart3);
				formula2 = jisuan(formula2,indexOfStart3,beforeIndex, nextIndex,"/");
			}else {
				nextIndex = getLastNumberLength(formula2, indexOfStart2);
				beforeIndex = getBeforeNumberLength(formula2, indexOfStart2);
				formula2 = jisuan(formula2,indexOfStart2,beforeIndex, nextIndex,"*");
			}

		}
		while (formula2.contains("+")) {
			indexOfStart = formula2.indexOf("+");
			nextIndex = getLastNumberLength(formula2, indexOfStart);
			beforeIndex = getBeforeNumberLength(formula2, indexOfStart);
			formula2 = jisuan(formula2, indexOfStart, beforeIndex, nextIndex, "+");
		}
		while (formula2.contains("-")) {
			indexOfStart = formula2.indexOf("-");
			nextIndex = getLastNumberLength(formula2, indexOfStart);
			beforeIndex = getBeforeNumberLength(formula2, indexOfStart);
			formula2 = jisuan(formula2, indexOfStart, beforeIndex, nextIndex, "-");
		}
		return formula2;
	}
	public static String jisuan(String formula, int index, int beforeIndex, int nextIndex, String operator) {
		String subValue = formula.substring(beforeIndex, nextIndex + 1);
//		System.out.println("subValue====" + subValue);
		double firstValue = Double.parseDouble(formula.substring(beforeIndex, index));
		double secondValue = Double.parseDouble(formula.substring(index + 1, nextIndex + 1));
		double value = 0; 
		switch (operator) {
		case "+":
			value = firstValue + secondValue;
			break;
		case "-":
			value = firstValue - secondValue;
			break;
		case "*":
			value = firstValue * secondValue;
			break;
		case "/":
			value = firstValue / secondValue;
			break;
			// Handle exponentiation
		case "^":
			value = Math.pow(firstValue, secondValue);
			break;
		default:
			throw new IllegalArgumentException("Unknown operator: " + operator);
		}
		String result = formula.replace(subValue, value + "");
		return result;
	}

}
