package com.zjty.inspect.service.impl;

import com.zjty.inspect.dao.MasterEvaReportDao;
import com.zjty.inspect.entity.MasterEvaReport;
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 MasterEvaReportDao evaReportDao;
    @Override
    public Page<MasterEvaReport> findSearch(Map<String, String> searchMap, int page, int size) {
        Specification<MasterEvaReport> specification = createSpecification(searchMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.Direction.DESC, "createDate");
        return evaReportDao.findAll(specification, pageRequest);
    }

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

    private Specification<MasterEvaReport> createSpecification(Map searchMap) {

        return new Specification<MasterEvaReport>() {

            @Override
            public Predicate toPredicate(Root<MasterEvaReport> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                if (searchMap.get("username") != null && !"".equals(searchMap.get("username")) ) {
                    if(!"root".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()]));

            }
        };

    }
}
