package com.uas.platform.b2b.manage.page.criteria;

import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;

/**
 * 条件表达式
 * 
 * @author yingp
 * 
 */
public class SimpleExpression implements CriterionExpression {

	/**
	 * 属性
	 */
	private String param;
	/**
	 * 值
	 */
	private Object value;
	
	/*
	 * 是否忽略大小写
	 */
	private boolean ignoreCase;
	/**
	 * 运算符
	 */
	private Operator operator;
	
	public SimpleExpression(String param, Object value, Operator operator) {
		this.param = param;
		this.value = value;
		this.operator = operator;
		this.ignoreCase = false;
	}

	public SimpleExpression(String param, Object value, Operator operator, boolean ignoreCase) {
		this.param = param;
		this.value = value;
		this.operator = operator;
		this.ignoreCase = ignoreCase;
	}

	protected SimpleExpression(String param, Operator operator) {
		this.param = param;
		this.operator = operator;
	}

	public String getParam() {
		return param;
	}

	public Object getValue() {
		return value;
	}

	public Operator getOperator() {
		return operator;
	}

	@Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
		Path expression = null;
		if (param.contains(".")) {
			String[] names = StringUtils.split(param, ".");
			expression = root.get(names[0]);
			for (int i = 1; i < names.length; i++) {
				expression = expression.get(names[i]);
			}
		} else {
			expression = root.get(param);
		}

		switch (operator) {
		case EQ:
			return builder.equal(expression, value);
		case NE:
			return builder.notEqual(expression, value);
		case LIKE:
				if(ignoreCase) {
					return builder.like(builder.upper((Expression<String>) expression), "%" + value.toString().toUpperCase() + "%");
				}else {
					return builder.like((Expression<String>) expression, "%" + value + "%");
				}
			
		case LT:
			return builder.lessThan(expression, (Comparable) value);
		case GT:
			return builder.greaterThan(expression, (Comparable) value);
		case LTE:
			return builder.lessThanOrEqualTo(expression, (Comparable) value);
		case GTE:
			return builder.greaterThanOrEqualTo(expression, (Comparable) value);
		case IS_NULL:
			return builder.isNull(expression);
		case IS_NOT_NULL:
			return builder.isNotNull(expression);
		default:
			return null;
		}
	}

}
