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.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 RootMeanSquaredErrorC 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);
        BigDecimal sum = BigDecimal.ZERO;
        // 循环集合获取实际功率、预测功率信息并计算
        for (Object obj : seq) {
            String forExp = "math.pow((" + formulaParam.getSecond() + "-" + formulaParam.getThird() + ")/" + formulaParam.getFourth() + ",2)";
            Map<String, Object> map = (Map<String, Object>) obj;
            BigDecimal forResult = new BigDecimal(String.valueOf( AviatorEvaluator.execute(forExp,map)));
            sum = sum.add(forResult);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sum",sum);
        BigDecimal size = new BigDecimal(seq.hintSize());
        map.put("size",size);
        // 求开根号的结果
        BigDecimal sqrtValue =new BigDecimal(String.valueOf(AviatorEvaluator.execute("math.sqrt(sum/size)",map)));
        map.put("sqrtValue",sqrtValue);
        BigDecimal result = new BigDecimal(String.valueOf( AviatorEvaluator.execute("1-sqrtValue",map)));
        return new AviatorDecimal(result);
    }
    @Override
    public String getName() {
        return "rootMeanSquaredErrorC";
    }
}
