package com.jsc.oscm.service;

import com.jsc.oscm.dao.RulesFilterRepository;
import com.jsc.oscm.entity.RulesFilter;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RulesFilterService {

    @Resource
    RulesFilterRepository rulesFilterRepository;

    public RulesFilter save(RulesFilter rulesFilter) {
        return rulesFilterRepository.save(rulesFilter);
    }

    public void delete(RulesFilter rulesFilter) {
        rulesFilterRepository.delete(rulesFilter);
    }

    public RulesFilter findById(Integer id) {
        return rulesFilterRepository.findById(id).orElse(null);
    }

    public List<RulesFilter> findAll() {
        return rulesFilterRepository.findAll();
    }

    public List<RulesFilter> queryPageable(RulesFilter rulesFilter, Integer index, Integer size) {
        Example<RulesFilter> example = Example.of(rulesFilter);
        Pageable pageable = PageRequest.of(index, size, Sort.by(Sort.Order.desc("id")));
        if (rulesFilter.getFilterName() != null) {
            ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("filterName", ExampleMatcher.GenericPropertyMatchers.contains());
            example = Example.of(rulesFilter, matcher);
        }
        return rulesFilterRepository.findAll(example, pageable).getContent();
    }

    public long queryCount(RulesFilter rulesFilter) {
        Example<RulesFilter> example = Example.of(rulesFilter);
        if (rulesFilter.getFilterName() != null) {
            ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("filterName", ExampleMatcher.GenericPropertyMatchers.contains());
            example = Example.of(rulesFilter, matcher);
        }
        return rulesFilterRepository.count(example);
    }

}
