package cn.reghao.autodop.dmaster.app.db.query;

import cn.reghao.autodop.dmaster.app.model.po.AppBuilding;
import cn.reghao.autodop.dmaster.app.db.repository.AppBuildingRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2021-06-02 15:01:18
 */
@Service
public class AppBuildingQuery {
    private AppBuildingRepository buildingRepository;

    public AppBuildingQuery(AppBuildingRepository buildingRepository) {
        this.buildingRepository = buildingRepository;
    }

    public List<AppBuilding> queryAll(Map<String, String> kv) {
        Specification<AppBuilding> specification = specification(kv);
        return buildingRepository.findAll(specification);
    }

    public Page<AppBuilding> queryByPage(Map<String, String> kv, Pageable pageable) {
        Specification<AppBuilding> specification = specification(kv);
        return buildingRepository.findAll(specification, pageable);
    }

    private Specification<AppBuilding> specification(Map<String, String> kv) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            kv.forEach((name, value) -> {
                predicates.add(cb.like(root.get(name), "%" + value + "%"));
            });

            // select * from app_building where app_id like '%test%' and app_name like '%测试%'
            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }
}
