package com.sunyard.lmas.expression;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

import com.sunyard.lmas.Base;

public abstract class ExpreCountAmt extends Base {
 private ArrayList<String> middle = new ArrayList<String>();// 存储中序表达式
 private ArrayList<String> right = new ArrayList<String>();// 存储右序表达式 
 protected String getExpression(){
  return middle.toString();
 }
 protected String getRight(){
  return right.toString();
 }
 /**
  * 获取中序表达式
  */
 private void setMiddle(String expression)throws Exception{
  middle.clear();
  right.clear();
  expression = expression==null ? "" : expression.trim();
  if(expression.length()>0&&Calculate.isOperator(expression.substring(0,1))){
   middle.add("0");
  }
  StringTokenizer st = new StringTokenizer(expression, "+-*/()%", true);
  while (st.hasMoreElements()) {
   String item = st.nextToken();
   if(Calculate.isOperator(item))
//   if(item.endsWith("+")||item.endsWith("-")||item.endsWith("*")||item.endsWith("/")||item.endsWith("(")||item.endsWith(")")||item.endsWith("%"))
    middle.add(item);
   else
    middle.add(getAmt(item).toString());
  }
 }
 /**
  * 将中序表达式转换为右序表达式
  */
 private void toRight() {
  if(middle.size()<=0)
   return;
  Stacks aStack = new Stacks();
  String operator;
  int position = 0;
  while (true) {
   if (Calculate.isOperator((String) middle.get(position))) {
    if (aStack.top == -1
      || ((String) middle.get(position)).equals("(")) {
     aStack.push(middle.get(position));
    } else {
     if (((String) middle.get(position)).equals(")")) {
      if (!((String) aStack.top()).equals("(")) {
       operator = (String) aStack.pop();
       right.add(operator);
      }
     } else {
      if (Calculate.priority((String) middle
        .get(position)) <= Calculate
        .priority((String) aStack.top())
        && aStack.top != -1) {
       operator = (String) aStack.pop();
       if (!operator.equals("("))
        right.add(operator);
      }
      aStack.push(middle.get(position));
     }
    }
   } else
    right.add(middle.get(position));
   position++;
   if (position >= middle.size())
    break;
  }
  while (aStack.top != -1) {
   operator = (String) aStack.pop();
   right.add(operator);
  }
 }
 /**
  * 获取结果
  * @return
  */
 private double getResult(){
  if(right.size()==0)
   return 0.0;
  String result;
  Stacks aStack = new Stacks();
  String op1, op2, is = null;
  Iterator<String> it = right.iterator();
  while (it.hasNext()) {
   is = (String) it.next();
   if (Calculate.isOperator(is)) {
    op1 = (String) aStack.pop();
    op2 = (String) aStack.pop();
    aStack.push(Calculate.twoResult(is, op1, op2));
   } else
    aStack.push(is);
  }
  result = (String) aStack.pop();
  return Double.parseDouble(result);
 }
 public final double getCountAmt(String expression)throws Exception{  
  setMiddle(expression);
  toRight();
  return getResult();
 }
 public abstract Double getAmt(String subjectno)throws Exception;
}