package com.izouma.nineth.repo;

import com.izouma.nineth.domain.UserBankCard;
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 javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

public interface UserBankCardRepo extends JpaRepository<UserBankCard, Long>, JpaSpecificationExecutor<UserBankCard> {

    @Query("select ubc from UserBankCard  ubc where ubc.del = false and ubc.userId = ?1")
    List<UserBankCard> findByUserId(Long userId);

    /**
     * 限定平台
     * @param userId
     * @param payPlatform
     * @return
     */
    @Query("select ubc from UserBankCard  ubc where  ubc.del = false and ubc.userId = ?1 and ubc.payPlatform = ?2")
    List<UserBankCard> findByUserIdWithPlatform(Long userId, String payPlatform);

    @Transactional
    @Modifying
    int deleteByUserIdAndPayPlatform(Long userId, String payPlatform);

    @Transactional
    @Modifying
    int deleteByUserId(Long userId);

    @Transactional
    @Modifying
    @Query("update UserBankCard  ubc set ubc.del = true where ubc.userId = ?1 ")
    int softDeleteByUserId(Long userId);

    @Transactional
    @Modifying
    @Query("update UserBankCard  ubc set ubc.del = true where ubc.id = ?1 ")
    int softDeleteById(Long id);

    @Query(nativeQuery = true,value ="select count(*) from user_bank_card  where bank_no =?1 and user_id <> ?2 ")
    Integer findByBankNo(String bank_no, Long excludeUserId);


    @Query(nativeQuery = true,value ="select count(*) from user_bank_card  where id_no =?1 and user_id <> ?2 ")
    Integer findByidNo(String id_no, Long excludeUserId);


    @Query("select count(ubc) from UserBankCard  ubc where  ubc.del = false and  ubc.userId = ?1")
    Integer countByUserId(Long userId);

    @Query("select count(ubc) from UserBankCard  ubc where  ubc.del = false and  ubc.userId = ?1 and ubc.bankNo = ?2 ")
    Integer countByUserIdAndBankNo(Long userId, String bankNo);

    /**
     * 查找银行卡
     * @param bindOrderNo
     * @return
     */
    Optional<UserBankCard> findByBindOrderNo(String bindOrderNo);

    /**
     * 查找银行卡
     * @param unbindOrderNo
     * @return
     */
    Optional<UserBankCard> findByUnbindOrderNo(String unbindOrderNo);

}
