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 RootMeanSquaredErrorSouthernPowerGrid extends AbstractFunction {
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3, AviatorObject arg4, AviatorObject arg5) {
        // 获取参数
        FormulaParam formulaParam = CommonUtil.getFormulaParam(env, arg1, arg2, arg3, arg4, arg5);
        BigDecimal sum = BigDecimal.ZERO;
        Sequence seq = RuntimeUtils.seq(formulaParam.getFirst(), env);
        // 可用功率
        BigDecimal ableValue ;
        // 获取容量
        BigDecimal electricCapacity = (BigDecimal) env.get("electricCapacity");
        String forExp;
        // 循环集合获取实际功率、预测功率信息并计算
        for (Object obj : seq) {
            Map<String, Object> map = (Map<String, Object>) obj;
            ableValue = new BigDecimal(String.valueOf(map.get("ableValue")));
            // 如果可用功率>=
            if(ableValue.compareTo(electricCapacity.multiply(new BigDecimal("0.02")))>-1){
                forExp = "math.pow((" + formulaParam.getSecond() + "-" + formulaParam.getThird() + ")/" + formulaParam.getSecond() + ",2)";
            }else{
                forExp = "math.pow((" + formulaParam.getSecond() + "-" + formulaParam.getThird() + ")/" + formulaParam.getFourth() +"*"+ formulaParam.getFifth() + ",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("sum", sum);
        map.put("size",size);

        // 求开根号的结果
        BigDecimal sqrtSum = new BigDecimal(String.valueOf(AviatorEvaluator.execute("math.sqrt(sum/size)", map)));
        map.put("sqrtSum", sqrtSum);
        BigDecimal result = new BigDecimal(String.valueOf(AviatorEvaluator.execute("1-sqrtSum", map)));
        return new AviatorDecimal(result);
    }

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