package com.ff.weijinxiao.service;


import com.ff.weijinxiao.domain.SmsJour;
import com.ff.weijinxiao.repository.SmsJourRepository;
import com.ff.weijinxiao.util.SpecificationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class SmsJourService {

    @Resource
    private SmsJourRepository smsJourRepository;

    /**
     * 创建实体
     *
     * @param smsJour
     */
    public SmsJour saveSmsJour(SmsJour smsJour) {
        return smsJourRepository.save(smsJour);
    }

    /**
     * 查找实体
     *
     * @param id
     * @return
     */
    public SmsJour findById(Integer id) {
        Optional<SmsJour> optional = smsJourRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

    public void deleteById(Integer id) {
        smsJourRepository.deleteById(id);
    }

    /**
     * 分页条件查询
     *
     * @param page
     * @param size
     * @param param
     * @return
     */
    public Page<SmsJour> findPage(int page, int size, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "id";
        Pageable pageable = new PageRequest(page - 1, size, direction, sort);
        return smsJourRepository.findAll(SpecificationUtil.buildSpecification(param, SmsJour.class), pageable);
    }

    /**
     * 根据条件查询List
     */
    public List<SmsJour> findList(Map<String, Object> param) {
        return smsJourRepository.findAll(SpecificationUtil.buildSpecification(param, SmsJour.class));
    }


    public Integer countAllByPhoneAndCreateTimeGreaterThanEqual(String phone, Date createTime) {
        return smsJourRepository.countAllByPhoneAndCreateTimeGreaterThanEqual(phone, createTime);
    }

    public SmsJour findFirstByPhoneOrderByCreateTimeDesc(String phone) {
        return smsJourRepository.findFirstByPhoneOrderByCreateTimeDesc(phone);
    }

    public SmsJour findByPhoneAndSmsCode(String phone, String smsCode) {
        return smsJourRepository.findByPhoneAndSmsCode(phone, smsCode);
    }
}
