package com.yifu.cloud.plus.v1.yifu.process.util;

import com.alibaba.fastjson.JSON;
import com.googlecode.aviator.AviatorEvaluator;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.CheckedException;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther wangan
 * @date 2020/9/2
 * goole表达式
 */
@Slf4j
public class ExpressionUtil {
    private ExpressionUtil() {
    }

    /**
     * @param expression
     * @param obj
     * @Author: wangan
     * @Date: 2020/9/2
     * @Description: 根据表达式判断数据大小
     * @return: boolean
     **/
    public static boolean isMatchExpression(String expression, Object obj) {
        Map<String, Object> env = new HashMap<>();
        if (obj instanceof BigDecimal) {
            env.put("x", Double.parseDouble(obj.toString()));
        } else {
            env.put("x", obj.toString());
        }
        try {
            return (Boolean) AviatorEvaluator.execute(expression, env);
        } catch (Exception e) {
            log.error("表达式数据{},表达式{}",expression, JSON.toJSONString(env));
            log.error("执行异常",e);
            throw new CheckedException("表达式执行出错");
        }
    }

    /**
     * @param expression
     * @param obj1
     * @param obj2
     * @Author: wangan
     * @Date: 2020/9/2
     * @Description: 根据表达式判断数据大小
     * @return: boolean
     **/
    public static boolean isMatchExpression(String expression, Object obj1,Object obj2) {
        Map<String, Object> env = new HashMap<>();
        if (obj1 instanceof BigDecimal) {
            env.put("x", Double.parseDouble(obj1.toString()));
        } else {
            env.put("x", obj1.toString());
        }
        if (obj2 instanceof BigDecimal) {
            env.put("y", Double.parseDouble(obj2.toString()));
        } else {
            env.put("y", obj2.toString());
        }
        try {
            return (Boolean) AviatorEvaluator.execute(expression, env);
        } catch (Exception e) {
            log.error("表达式数据{},表达式{}",expression, JSON.toJSONString(env));
            log.error("执行异常",e);
            throw new CheckedException("表达式执行出错");
        }
    }
}
