|
@@ -0,0 +1,61 @@
|
|
|
+package org.eco.als.service.impl;
|
|
|
+
|
|
|
+import cn.hutool.core.collection.CollUtil;
|
|
|
+import com.ql.util.express.DefaultContext;
|
|
|
+import com.ql.util.express.ExpressRunner;
|
|
|
+import org.eco.als.service.IFormulaService;
|
|
|
+import org.eco.common.core.exception.BusinessException;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.regex.Matcher;
|
|
|
+import java.util.regex.Pattern;
|
|
|
+
|
|
|
+@Service
|
|
|
+public class FormulaService implements IFormulaService {
|
|
|
+ private final ExpressRunner runner = new ExpressRunner();
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public Object evaluateExpression(String expression, Map<String, Object> variablesMap) throws Exception {
|
|
|
+ DefaultContext<String, Object> context = new DefaultContext<>();
|
|
|
+ Map<String, Object> variables = CollUtil.isEmpty(variablesMap) ? buildVariableContext(expression) : variablesMap;
|
|
|
+ context.putAll(variables);
|
|
|
+ return runner.execute(expression, context, null, true, false);
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> buildVariableContext(String expression) {
|
|
|
+ String[] variableNames = parseVariableNames(expression);
|
|
|
+ Map<String, Object> variables = new HashMap<>();
|
|
|
+ // 字段属性自定义值
|
|
|
+ for (String fieldName : variableNames) {
|
|
|
+ switch (fieldName) {
|
|
|
+ case "ratedLife":
|
|
|
+ variables.put(fieldName, 14);
|
|
|
+ break;
|
|
|
+ case "usedLife":
|
|
|
+ variables.put(fieldName, 8);
|
|
|
+ break;
|
|
|
+ case "uu":
|
|
|
+ variables.put(fieldName, 2);
|
|
|
+ break;
|
|
|
+ default:
|
|
|
+ throw new BusinessException("无此属性公式的配置,请检查: {0}", fieldName);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return variables;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 解析表达式中的变量名。
|
|
|
+ */
|
|
|
+ private String[] parseVariableNames(String expression) {
|
|
|
+ Pattern pattern = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]*");
|
|
|
+ Matcher matcher = pattern.matcher(expression);
|
|
|
+ Map<String, Boolean> variables = new HashMap<>();
|
|
|
+ while (matcher.find()) {
|
|
|
+ variables.put(matcher.group(), true);
|
|
|
+ }
|
|
|
+ return variables.keySet().toArray(new String[0]);
|
|
|
+ }
|
|
|
+}
|