package com.crm.ucard.dao.repository;

import com.crm.rely.backend.core.pojo.table.FinanceDepositTable;
import com.crm.rely.backend.dao.repository.BaseRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.LockModeType;
import java.util.Date;
import java.util.List;


@Repository
public interface FinanceDepositRepository extends BaseRepository<FinanceDepositTable> {

    /**
     * 根据入金流水号获取入金信息(加锁-行级锁)
     *
     * @param serial
     * @return
     */
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    FinanceDepositTable findFirstBySerial(String serial);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    FinanceDepositTable findFirstByChannelSerial(String ticket);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    FinanceDepositTable getFirstBySerial(String serial);

    List<FinanceDepositTable> getAllByCustomId(Long customId);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    FinanceDepositTable findFirstById(Long id);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    List<FinanceDepositTable> findAllByIdIn(List<Long> ids);

    boolean existsByCustomIdAndPayTypeAndAddTimeGreaterThanEqual(Long customId, String payType, Date date);

    @Query(value = "SELECT count(*) from finance_deposit where custom_id=?1 and callback_status=1 and status in (0,1," +
            "2)",
            nativeQuery = true)
    Integer countByCustomIdAndCallbackStatus(Long customId);

    @Query(value = "SELECT count(*) from finance_deposit where custom_id=?1 " +
            "and callback_status=1 and status in (0," +
            "1,2) and serial!=?2",
            nativeQuery = true)
    Integer countByCustomIdAndCallbackStatusAndSerialNot(Long customId, String serial);
}
