package com.liangjian.dataplatform.member.service;

import com.liangjian.dataplatform.member.entity.vo.request.BirdGirdRequest;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 黄子奇
 * @Date: 2019/11/20
 *
 * birdgird动态查询的接口
 */
public interface BirdGirdQueryRequest<A> {

    default List<Predicate> buildConditionByFilters(BirdGirdRequest request, Root<A> root, CriteriaBuilder criteriaBuilder) {
        List<Predicate> where = request.getFilters()
                .stream()
                .filter(f -> f.getValue() != null && !f.getValue().isEmpty())
                .map(f -> {
                    switch (f.getOperate()) {
                        case "equal": {
                            Path path = root.get(f.getField());
                            return criteriaBuilder.equal(path, f.transportType(path.getJavaType()));
                        }
                        case "notequal": {
                            Path path = root.get(f.getField());
                            return criteriaBuilder.notEqual(root.get(f.getField()), f.transportType(path.getJavaType()));
                        }
                        case "less": return criteriaBuilder.lt(root.get(f.getField()).as(Double.class), Double.valueOf(f.getValue()));
                        case "lessorequal": return criteriaBuilder.le(root.get(f.getField()).as(Double.class), Double.valueOf(f.getValue()));
                        case "greater": return criteriaBuilder.gt(root.get(f.getField()).as(Double.class), Double.valueOf(f.getValue()));
                        case "greateroreeuqal": return criteriaBuilder.ge(root.get(f.getField()).as(Double.class), Double.valueOf(f.getValue()));
                        case "contains": return criteriaBuilder.like(root.get(f.getField()), "%"+f.getValue()+"%");
                        case "startswith": return criteriaBuilder.like(root.get(f.getField()), f.getValue()+"%");
                        case "endswith": return criteriaBuilder.like(root.get(f.getField()), "%"+f.getValue());
                        default: throw new RuntimeException("未知对应判断操作符");
                    }
                })
                .collect(Collectors.toList());
        return where;
    }
}
