/*** Created by Teddy on 2017/10/23.*/
public classExpressionUtil {/*** 计算List配置了公式的值
*@parambeanList
*@return
*/
public static List workOutListBean(List extends BaseEntity>beanList){if(CollectionUtils.isEmpty(beanList)){returnCollections.EMPTY_LIST;
}else{
Class extends BaseEntity> beanClass = beanList.get(0).getClass();
Table table= beanClass.getAnnotation(Table.class);//在实体中通过JPA注解获取表名
String tableCode =table.name();if(StringUtil.isEmpty(tableCode)){
System.out.println("无法计算,该bean没有表名信息");
}
List mapList =BeanUtil.convertBeansToMaps(beanList);
FormulaService formulaService= SpringContext.getBean(FormulaService.class);
List formulas =formulaService.queryByTableCode(tableCode);for(Map map : mapList) {
JEP jep=getJEP(map);for(Formula formula : formulas) {
String conditionExpr=formula.getConditionExpr();
String formulaExpr=formula.getFormulaExpr();
String evaluate=formula.getEvaluate();
workOutKey(jep,map,conditionExpr,formulaExpr,evaluate);
}
}returnmapList;
}
}/*** 非动态配置公式方式
*@parammapList
*@paramconditionExpr
*@paramformulaExpr
*@paramevaluate*/
public static void workOutListMap(ListmapList,String conditionExpr,String formulaExpr, String evaluate){for(Map map : mapList) {
JEP jep=getJEP(map);
workOutKey(jep,map,conditionExpr,formulaExpr,evaluate);
}
}/*** 计算出表达式并填充
*@paramjep
*@parammap
*@paramconditionExpr
*@paramformulaExpr
*@paramevaluate*/
private static voidworkOutKey(JEP jep,Map map,String conditionExpr, String formulaExpr, String evaluate){//如果没有条件
if(StringUtil.isEmpty(conditionExpr)){
map.put(evaluate,workOutSingle(jep,formulaExpr));//如果有条件 且条件为true
}else if(workOutBool(jep,conditionExpr)){
map.put(evaluate,workOutSingle(jep,formulaExpr));
}
}/*** 判断条件表达式
*@paramjep
*@paramexpression
*@return
*/
private static booleanworkOutBool(JEP jep,String expression){return (Double)workOutSingle(jep,expression) > 0;
}/*** 计算表达式的值
*@paramjep
*@paramexpression
*@return
*/
private staticObject workOutSingle(JEP jep,String expression){
Object result= null;try { //执行
Node parse =jep.parse(expression);
result=jep.evaluate(parse);
}catch(ParseException e) {throw new BaseRunTimeException("公式表达式解析失败",e);
}if(result == null){throw new BaseRunTimeException("公式表达式解析失败");
}returnresult;
}/*** 获取填充好变量的JEP对象
*@paramparam
*@return
*/
private staticJEP getJEP(Map param){
JEP jep= newJEP();
Set set =param.entrySet();for(Map.Entry entry : set) {
Object entryValue=entry.getValue();
String entryKey=(String) entry.getKey();
jep.addVariable(entryKey, entryValue);
}returnjep;
}
}