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

import cn.reghao.autodop.dmaster.app.model.po.AppRunning;
import cn.reghao.autodop.dmaster.app.db.repository.AppRunningRepository;
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 AppRunningQuery {
    private AppRunningRepository runningRepository;

    public AppRunningQuery(AppRunningRepository runningRepository) {
        this.runningRepository = runningRepository;
    }

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

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

    private Specification<AppRunning> 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]));
        };
    }
}
