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.CalculateResult;
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 Pass extends AbstractFunction {
    /**
     * @param env
     * @param arg1
     * @param arg2
     * @return
     */
    @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 compare = new BigDecimal(formulaParam.getSecond());
        compare = compare.divide(CalculateResult.ONE_HUNDRED, 8, BigDecimal.ROUND_HALF_UP);
        BigDecimal sum = BigDecimal.ZERO;
        Sequence seq = RuntimeUtils.seq(formulaParam.getFirst(), env);
        // 循环集合获取实际功率、预测功率信息并计算
        for (Object obj : seq) {
            Map<String, Object> map = (Map<String, Object>) obj;
            String forExp = "1-math.abs((" + formulaParam.getThird() + "-" + formulaParam.getFourth() + ")/" + formulaParam.getFifth() + ")";
            BigDecimal calculateResult = new BigDecimal(String.valueOf(AviatorEvaluator.execute(forExp, map)));
            Map<String, Object> passMap = new HashMap<>();
            passMap.put("calculateResult", calculateResult);
            passMap.put("compare", compare);
            BigDecimal forResult = new BigDecimal(String.valueOf(AviatorEvaluator.execute("if(calculateResult>=compare){ return 1M; } else{return 0M;}", passMap)));
            sum = sum.add(forResult);
        }
        BigDecimal size = new BigDecimal(seq.hintSize());
        Map<String, Object> map = new HashMap<>();
        map.put("sum", sum);
        map.put("size", size);
        BigDecimal result = new BigDecimal(String.valueOf(AviatorEvaluator.execute("sum/size", map)));
        return new AviatorDecimal(result);
    }

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