package com.izouma.nineth.repo;

import com.izouma.nineth.domain.UserFundAccount;
import com.izouma.nineth.enums.AccountType;
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 UserFundAccountRepo  extends JpaRepository<UserFundAccount, Long>, JpaSpecificationExecutor<UserFundAccount> {

    List<UserFundAccount> findByUserId(Long userId);

    /**
     * 查询账户
     * @param userId
     * @param accountType
     * @return
     */
    Optional<UserFundAccount> findByUserIdAndAccountType(Long userId, AccountType accountType);

    @Transactional
    @Modifying
    int deleteByUserId(Long userId);


    /**
     * 查找锁定的账户
     * @param accountType
     * @return
     */
    @Query("select ufa from UserFundAccount ufa where ufa.accountType = ?1  " +
            " and ufa.accountStatus = com.izouma.nineth.enums.AccountStatus.LOCALED")
    List<UserFundAccount> findLockedAccount(AccountType accountType);


    /**
     * 查找资金账户
     * @param orderNo
     * @return
     */
    Optional<UserFundAccount>  findByOrderNo(String orderNo);

    /**
     * 查找账户
     * @return
     */
    Optional<UserFundAccount> findByAccountNo(String accountNo);

    /**
     * 昨天开通钱包数
     * @return 昨天开通钱包数
     */
    @Query(nativeQuery = true ,value = "select count(*) from user_fund_account ufa where  date(ufa.apply_time) = date_sub(curdate(),interval 1 day) and ufa.account_status  = 'NORMAL'")
    Integer lastDayOpenWalletNum();

    /**
     * 累计开通钱包数
     * @return 累计开通钱包数
     */
    @Query(nativeQuery = true ,value = "select count(*) from user_fund_account ufa where ufa.account_status  = 'NORMAL'")
    Integer openWalletNum();

    @Query(nativeQuery = true ,value = "select count(*) from user_fund_account ufa where  date(ufa.cancel_time) = date_sub(curdate(),interval 1 day) and ufa.account_status  = 'CANCEL'")
    Integer lastDayClosingWalletNum();
}
