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

import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 特殊查询条件的容器
 * 
 * @author yingp
 * 
 * @param <T>
 */
public class PredicateFactory<T> implements Specification<T> {

	private List<CriterionExpression> expressions = new ArrayList<CriterionExpression>();

	@Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
                                 CriteriaBuilder builder) {
		if (!expressions.isEmpty()) {
			List<Predicate> predicates = new ArrayList<Predicate>();
			for (CriterionExpression c : expressions) {
				predicates.add(c.toPredicate(root, query, builder));
			}
			// 将所有条件用 and 联合起来
			if (predicates.size() > 0) {
				return builder.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}
		return builder.conjunction();
	}

	/**
	 * 增加简单条件表达式
	 * 
	 */
	public PredicateFactory<T> add(CriterionExpression expression) {
		if (expression != null) {
			expressions.add(expression);
		}
		return this;
	}

}
