package com.td.boss.game.comsnbapply.service;

import com.td.boss.common.service.*;
import com.td.boss.game.comsnbapply.pojo.ComSnbApply;
import com.td.boss.game.comsnbapply.vo.ComSnbApplyVo;
import com.td.boss.game.comsnbapply.repository.ComSnbApplyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
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.Date;
import java.util.List;

@Service
@Transactional
public class ComSnbApplyServiceImpl extends CommonServiceImpl<ComSnbApplyVo, ComSnbApply, String> implements ComSnbApplyService{

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private ComSnbApplyRepository comSnbApplyRepository;


    @Override
    public List<ComSnbApply> findAllByUserIdAndIsState(String userId, Integer isState) {
        return comSnbApplyRepository.findAllByUserIdAndIsState(userId, isState);
    }

    @Override
    public ComSnbApply findByUserIdAndSnbAndIsState(String userId, Integer snb, Integer isState) {
        return comSnbApplyRepository.findByUserIdAndSnbAndIsState(userId, snb, isState).orElse(null);
    }

    @Override
    public List<ComSnbApply> findAllByUserId(String userId) {
        return comSnbApplyRepository.findAllByUserId(userId);
    }


    @Override
    public List<ComSnbApply> findAllByIn(List<String> ids) {
        return comSnbApplyRepository.findAllByIdIn(ids);
    }

    @Override
    public List<ComSnbApply> saveAll(List<ComSnbApply> comSnbApplies) {
        return comSnbApplyRepository.saveAll(comSnbApplies);
    }

    @Override
    public List<ComSnbApply> getBetweenTimeList(Date begin, Date end) {
        Specification specification = new Specification<ComSnbApply>() {
            @Override
            public Predicate toPredicate(Root<ComSnbApply> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.between(root.get("createTime"), begin, end));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return comSnbApplyRepository.findAll(specification);
    }
}
