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 RootMeanSquaredErrorR extends AbstractFunction {
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
        // 获取参数
        FormulaParam formulaParam = CommonUtil.getFormulaParam(env, arg1, arg2, arg3, null, null);
        Sequence seq = RuntimeUtils.seq(formulaParam.getFirst(), env);
        BigDecimal sum = BigDecimal.ZERO;
        // 循环集合获取实际功率、预测功率信息并计算
        for (Object obj : seq) {
            Map<String, Object> map = (Map<String, Object>) obj;
            String forExp = "math.pow((" + formulaParam.getSecond() + "-" + formulaParam.getThird() + ")/" + formulaParam.getSecond() + ",2)";
            BigDecimal forResult = new BigDecimal(String.valueOf(AviatorEvaluator.execute(forExp, map)));
            sum = sum.add(forResult);
        }
        // 上下文参数
        Map<String, Object> map = new HashMap<>();
        BigDecimal size = new BigDecimal(seq.hintSize());
        map.put("size", size);
        map.put("sum", sum);
        // 求开根号的结果
        BigDecimal sqrtSumSize = new BigDecimal(String.valueOf(AviatorEvaluator.execute("math.sqrt(sum/size)", map)));
        map.put("sqrtSumSize", sqrtSumSize);
        BigDecimal result = new BigDecimal(String.valueOf(AviatorEvaluator.execute("1-sqrtSumSize", map)));
        return new AviatorDecimal(result);
    }

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