package com.jsc.oscm.service;

import com.jsc.oscm.dao.TargetSocialRepository;
import com.jsc.oscm.entity.TargetSocial;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

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

@Service
public class TargetSocialService {
    @Resource
    TargetSocialRepository targetSocialRepository;

    public boolean deleteById(Integer id) {
        targetSocialRepository.deleteById(id);
        return true;
    }

    public boolean save(TargetSocial targetSocial) {
        targetSocialRepository.save(targetSocial);
        return true;
    }

    public List<TargetSocial> queryAll(TargetSocial targetSocial, String sortBy, Boolean shuffleResult) {
        Example<TargetSocial> example = Example.of(targetSocial);
        List<TargetSocial> resultList = targetSocialRepository.findAll(example, Sort.by(Sort.Order.asc(sortBy)));
        if (shuffleResult) {
            Collections.shuffle(resultList);
        }
        return resultList;
    }

    public List<TargetSocial> queryPageable(int index, int size, TargetSocial targetSocial) {
        Example<TargetSocial> example = Example.of(targetSocial);
        if (targetSocial.getUserName() != null) {
            ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("userName", ExampleMatcher.GenericPropertyMatchers.contains());
            example = Example.of(targetSocial, matcher);
        }
        Pageable pageable = PageRequest.of(index, size, Sort.by(Sort.Order.desc("id")));
        return targetSocialRepository.findAll(example, pageable).getContent();
    }

    public long queryCount(TargetSocial targetSocial) {
        Example<TargetSocial> example = Example.of(targetSocial);
        if (targetSocial.getUserName() != null) {
            ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("userName", ExampleMatcher.GenericPropertyMatchers.contains());
            example = Example.of(targetSocial, matcher);
        }
        return targetSocialRepository.count(example);
    }


}
