package com.ruoyi.project.business.dto.JEPCustomFunction;

import org.nfunk.jep.EvaluatorI;
import org.nfunk.jep.Node;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.CallbackEvaluationI;
import org.nfunk.jep.function.PostfixMathCommand;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jubs
 */
public class IFSFunction extends PostfixMathCommand implements CallbackEvaluationI {
    public IFSFunction() {
        this.numberOfParameters = -1;
    }

    public boolean checkNumberOfParameters(int n) {
        return n >= 2;
    }


    @Override
    public Object evaluate(Node node, EvaluatorI pv) throws ParseException {
        int num = node.jjtGetNumChildren();
        if (!this.checkNumberOfParameters(num)) {
            throw new ParseException("If operator at least have 2 arguments.");
        }
        //模拟实现 excel的IFS函数
        //奇数位 为条件  偶数位 为 返回值
        //IFS函数的返回值是 第一个条件为真时返回的值
        Object value = null;
        List<Integer> oddNum = new ArrayList<>();
        List<Integer> evenNum = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            if (i % 2 == 0) {
                oddNum.add(i);
            } else {
                evenNum.add(i);
            }
        }
        if (oddNum.size() != evenNum.size()) {
            throw new ParseException("If operator arguments must be even.");
        }
        for (Integer odd : oddNum) {
            Object oddValue = pv.eval(node.jjtGetChild(odd));
            if ((double) oddValue == 1.0) {
                value = pv.eval(node.jjtGetChild(odd + 1));
                break;
            }
        }
        if (value == null) {
            //todo: 待确定 是否所有条件都不满足时返回空
            return "";
        }
        return value;
    }
}
