package com.ff.weijinxiao.service;


import com.ff.weijinxiao.domain.CUser;
import com.ff.weijinxiao.repository.CUserRepository;
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.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class CUserService {

    @Resource
    private CUserRepository cUserRepository;

    /**
     * 创建实体
     *
     * @param cUser
     */
    public CUser saveCUser(CUser cUser) {
        return cUserRepository.save(cUser);
    }

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

    public CUser findByOpenId(String openId) {
        Optional<CUser> optional = cUserRepository.findOne(new Specification<CUser>() {
            @Override
            public Predicate toPredicate(Root<CUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate p = criteriaBuilder.and(criteriaBuilder.equal(root.get("openId").as(String.class), openId));
                return p;
            }
        });
        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

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

    /**
     * 分页条件查询
     *
     * @param page
     * @param size
     * @param param
     * @return
     */
    public Page<CUser> 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 cUserRepository.findAll(SpecificationUtil.buildSpecification(param, CUser.class), pageable);
    }

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

}
