package cn.quantgroup.xyqb.service.user.impl;

import cn.quantgroup.xyqb.entity.UserBtRegister;
import cn.quantgroup.xyqb.repository.IUserBtRegisterRepository;
import cn.quantgroup.xyqb.service.user.IUserBtRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/16.
 */
@Service
public class UserBtRegisterServiceImpl implements IUserBtRegisterService {
    @Autowired
    private IUserBtRegisterRepository userBtRegisterRepository;

    @Override
//    @Cacheable(value = "btRegisterCache", key = "'userId' + #userId", unless = "#result == null", cacheManager = "cacheManager")
    public UserBtRegister findByUserId(Long userId) {
        if (null != userId) {
            return userBtRegisterRepository.findOne((root, query, cb) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(cb.equal(root.get("isActive").as(Boolean.class), Boolean.TRUE));
                list.add(cb.equal(root.get("userId").as(Long.class), userId));
                Predicate[] p = new Predicate[list.size()];
                query.where(cb.and(list.toArray(p)));
                return query.getRestriction();
            });
        }
        return null;
    }

    @Override
    public UserBtRegister save(UserBtRegister userBtRegister) {
        return userBtRegisterRepository.saveAndFlush(userBtRegister);
    }
}
