package cn.quantgroup.xyqb.repository;

import cn.quantgroup.xyqb.entity.UserDetail;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author mengfan.feng
 * @time 2015-09-11 11:22
 */
public interface IUserDetailRepository extends JpaRepository<UserDetail, Long>, JpaSpecificationExecutor<UserDetail> {

    UserDetail findByUserId(Long userId);

    UserDetail findByPhoneNo(String phone);

    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query(value = "update user_detail set qq = ?1 where user_id = ?2", nativeQuery = true)
    void updateUserQq(String qq, Long userId);

    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query(value = "update user_detail set email = ?1 where user_id = ?2", nativeQuery = true)
    void updateUserEmail(String email, Long userId);

    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query(value = "update user_detail set gender = ?1 where user_id = ?2", nativeQuery = true)
    void updateGender(int gender, Long userId);

    List<UserDetail> findAll(Specification<UserDetail> specification);

    /**
     * 修复线上身份证问题，后续误用
     *
     * @return
     */
    @Query(value = "select * from user_detail where gender!=1 and gender!=2 and id_no is not null", nativeQuery = true)
    List<UserDetail> selectUserDetailsBy();

    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query(value = "update user_detail set name=?1,id_no=?2,gender=?3 where phone_no=?4", nativeQuery = true)
    int updateNameAndIdNoByPhoneNo(String name, String idNo, int gender, String phoneNo);

    /**
     * 按照身份证号和手机号 - 模糊查询
     *
     * @param phoneNo - 手机号
     * @param idNo    - 身份证号
     * @return List<UserDetail>
     */
    @Query(value = "select * from user_detail where phone_no like ?1 and id_no like ?2", nativeQuery = true)
    List<UserDetail> fuzzyQueryByPhoneNoAndIdNo(String phoneNo, String idNo);

    List<UserDetail> findTop20ByIdNoStartingWith(String idNo);

    List<UserDetail> findTop20ByPhoneNoStartingWith(String phoneNo);

    List<UserDetail> findByIdBetween(Long id, Long endId);

    UserDetail findByUserIdAndPhoneNoAndNameAndIdNo(Long userId, String phoneNo, String name, String idNo);
}
