package com.syjy.calculate.function;

import com.googlecode.aviator.AviatorEvaluator;
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 PointU 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);
        // 拼接公式
        String exp = "sumDifferenceAbsolute(list," + formulaParam.getSecond() + "," + formulaParam.getThird() + ")";
        // 获取Σ|实际-预测|
        BigDecimal sumDifferenceAbsolute = new BigDecimal(String.valueOf(AviatorEvaluator.execute(exp, env)));

        // 将参数转为集合
        Sequence seq = CommonUtil.getSeq(formulaParam.getFirst(), env);
        BigDecimal sum = BigDecimal.ZERO;
        // 循环集合
        for (Object obj : seq) {
            Map<String, Object> map = (Map<String, Object>) obj;
            map.put("sumDifferenceAbsolute", sumDifferenceAbsolute);
            String forExp = "math.abs((" + formulaParam.getSecond() + "/(" + formulaParam.getSecond() + "+" + formulaParam.getThird() + ")-0.5M)) * (math.abs(" + formulaParam.getSecond() + "-" + formulaParam.getThird() + ")/sumDifferenceAbsolute)";
            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 result = new BigDecimal(String.valueOf(AviatorEvaluator.execute("1-(2*sum)", map)));
        return new AviatorDecimal(result);
    }

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