package com.hotent.util;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;

/**
 * 提供表达式及参数结合计算结果
 */
public class ExpressionCalculator {

    /**
     * 计算包含变量的表达式
     * @param expression 表达式，如 "(c1+c2)*(c1/c2)+c1"
     * @param variables 变量映射表，如 {c1=10, c2=5}
     * @return 计算结果
     */
    public static double calculateExpression(String expression, Map<String, Double> variables) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        try {
            // 将变量放入引擎
            for (Map.Entry<String, Double> entry : variables.entrySet()) {
                engine.put(entry.getKey().replace(".","_"), entry.getValue());
            }

            // 计算表达式
            Object result = engine.eval(expression.replace(".","_"));

            if (result instanceof Number) {
                return ((Number) result).doubleValue();
            } else {
                throw new RuntimeException("表达式计算结果不是数字: " + result);
            }
        } catch (ScriptException e) {
            throw new RuntimeException("表达式计算错误: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        String expression = "(taiyuan.c1+taiyuan.c2)*(c1/c2)+c1";

        // 方式1：手动指定变量值
        Map<String, Double> variables1 = new HashMap<>();
        variables1.put("c1", 10.0);
        variables1.put("c2", 5.0);
        variables1.put("taiyuan.c1",1.0);
        variables1.put("taiyuan.c2",2.0);

        double result1 = calculateExpression(expression, variables1);
        System.out.println("表达式: " + expression);
        System.out.println("结果: " + result1);
        System.out.println();
    }
}
