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

import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Stack;

public class CustomRoundFunction extends PostfixMathCommand {
    public CustomRoundFunction() {
        this.numberOfParameters = -1;
    }

    public void run(Stack inStack) throws ParseException {
        this.checkStack(inStack);
        Object param;
        if (this.curNumberOfParameters == 1) {
            param = inStack.pop();
            inStack.push(this.round(param));
        } else {
            param = inStack.pop();
            Object l = inStack.pop();
            inStack.push(this.round(l, param));
        }

    }

    private Object round(Object l, Object r) throws ParseException {
        if (l instanceof Number && r instanceof Number) {
            int dp = ((Number)r).intValue();
            return new BigDecimal(l.toString()).setScale(dp, RoundingMode.HALF_UP);
        } else {
            throw new ParseException("Invalid parameter type");
        }
    }

    public Object round(Object param) throws ParseException {
        if (param instanceof Number) {
            return Math.round(((Number) param).doubleValue());
        } else {
            throw new ParseException("Invalid parameter type");
        }
    }


    public static String formatNumberWithDecimal(double number, int decimalDigits) {
        double roundedNumber = Math.round(number * Math.pow(10, decimalDigits)) / Math.pow(10, decimalDigits);
        DecimalFormat df = new DecimalFormat("#." + repeatString(decimalDigits));
        df.setRoundingMode(RoundingMode.HALF_UP);
        return df.format(roundedNumber);
    }

    private static String repeatString(int count) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            sb.append("#");
        }
        return sb.toString();
    }
}
