package com.zjty.inspect.service.impl;

import com.zjty.inspect.dao.EvaReportDao;
import com.zjty.inspect.entity.EvaReport;
import com.zjty.inspect.entity.Evaluation;
import com.zjty.inspect.service.EvaReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

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;
import java.util.Map;
@Service
public class EvaReportServiceImpl implements EvaReportService {

    @Autowired
    private EvaReportDao evaReportDao;
    @Override
    public Page<EvaReport> findSearch(Map<String, String> searchMap, int page, int size) {
        Specification<EvaReport> specification = createSpecification(searchMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.Direction.DESC, "createDate");
        return evaReportDao.findAll(specification, pageRequest);
    }

    @Override
    public void save(EvaReport evaReport) {
        evaReportDao.save(evaReport);
    }

    private Specification<EvaReport> createSpecification(Map searchMap) {

        return new Specification<EvaReport>() {

            @Override
            public Predicate toPredicate(Root<EvaReport> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                    predicateList.add(cb.like(root.get("username").as(String.class), "%" + (String) searchMap.get("username") + "%"));
                }
                if (searchMap.get("projectName") != null && !"".equals(searchMap.get("projectName"))) {
                    predicateList.add(cb.like(root.get("projectName").as(String.class), "%" + (String) searchMap.get("projectName") + "%"));
                }
                predicateList.add(cb.equal(root.get("del").as(Integer.class),0));
                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}
