package cn.quantgroup.xyqb.repository;

import cn.quantgroup.user.enums.BizType;
import cn.quantgroup.user.enums.Relation;
import cn.quantgroup.xyqb.entity.Contact;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by 11 on 2016/12/30.
 */
public interface IContactRepository extends JpaRepository<Contact, Long> {
    List<Contact> findByUserId(Long userId);

    List<Contact> findByUserIdAndBizType(Long userId, BizType bizType);

    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query(value = "update contact set name=?1,phone_no=?2,relation=?3 where id = ?4", nativeQuery = true)
    void update(String name, String phoneNo, Integer relation, Long id);

//    @Query(value = "select  *, max(`id`) as mid from contact where user_id=?1 GROUP BY phone_no ORDER BY id desc limit 2", nativeQuery = true)
    @Query(value = "select * from contact, (select   max(`id`) as mid from contact where user_id=?1 GROUP BY phone_no ORDER BY id desc limit 2) as ids where contact.id=ids.mid", nativeQuery = true)
    List<Contact> findContactForUserId(Long userId);
}
