package com.syjy.calculate.function;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.RuntimeUtils;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorDecimal;
import com.googlecode.aviator.runtime.type.AviatorJavaType;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.Sequence;
import com.syjy.calculate.entity.FormulaParam;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 计算准确率 :均方根准确率绝对值
 *
 * @author zcl
 * @version 1.0
 * @since 2022/9/8 9:30
 */
public class RootMeanSquaredErrorS extends AbstractFunction {
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3, AviatorObject arg4) {
        // 获取参数
        FormulaParam formulaParam = CommonUtil.getFormulaParam(env, arg1, arg2, arg3, arg4, null);
        // 将参数转为集合
        Sequence seq = RuntimeUtils.seq(formulaParam.getFirst(), env);
        // 拼接参数
        String sumExp = "sumDifferenceSquare(list" + "," + formulaParam.getSecond() + "," + formulaParam.getThird() + ")";
        // 获取Σ(实际-预测)²
        BigDecimal sumDifferenceSquare = new BigDecimal(String.valueOf(AviatorEvaluator.execute(sumExp, env)));
        Map<String, Object> map = new HashMap<>();
        map.put("sumDifferenceSquare", sumDifferenceSquare);
        // 求开根号的结果
        BigDecimal sqrtSum = new BigDecimal(String.valueOf(AviatorEvaluator.execute("math.sqrt(sumDifferenceSquare)", map)));
        map.put("sqrtSum", sqrtSum);
        BigDecimal size = new BigDecimal(seq.hintSize());
        map.put("size", size);
        // 求开根号的结果
        BigDecimal sqrtSize = new BigDecimal(String.valueOf(AviatorEvaluator.execute("math.sqrt(size)", map)));
        map.put("sqrtSize", sqrtSize);
        // 放入装机容量和最大开机容量
        map.put("electricCapacity", env.get("electricCapacity"));
        BigDecimal maxCapacity = (BigDecimal) env.get("maxCapacity");
        map.put("maxCapacity", maxCapacity);
        String expFinal = "1-sqrtSum/(" + formulaParam.getFourth() + "*sqrtSize)";
        BigDecimal result = new BigDecimal(String.valueOf(AviatorEvaluator.execute(expFinal, map)));
        return new AviatorDecimal(result);
    }

    @Override
    public String getName() {
        return "rootMeanSquaredErrorS";
    }
}
