package cn.quantgroup.customer.repo;
import cn.quantgroup.customer.entity.TransactionReceiptRecord;
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;

public interface TransactionReceiptRecordRepo extends JpaRepository<TransactionReceiptRecord, Long>, JpaSpecificationExecutor<TransactionReceiptRecord> {

    @Query(value = "select max(batch_no) from transaction_receipt_record where export_status =?1 ", nativeQuery = true)
    Integer findMaxBatchNo(Integer status);

    @Query(value = "select max(export_batch_no) from transaction_receipt_record where import_status = ?1 ", nativeQuery = true)
    Integer findExportMaxBatchNo(Integer status);

    @Query(value = "select count(1) from transaction_receipt_record where user_id =?1 and user_name =?2 and order_no =?3 ", nativeQuery = true)
    Integer selectCountByUserIdAndOrderNo(Integer userId,String userName,String orderNo);

    @Query(value = "select * from transaction_receipt_record where import_status = ?1", nativeQuery = true)
    List<TransactionReceiptRecord> selectRecordsByImportStatus(Integer status);

    @Query(value = "select * from transaction_receipt_record where order_no = ?1 and user_id =?2 and user_name =?3 and import_status != 2 and export_status = 0 ", nativeQuery = true)
    List<TransactionReceiptRecord> selectRecordsByOrderNo(String orderNo,Integer userId,String userName);

    @Query(value = "select * from transaction_receipt_record where import_status = ?1 and (export_status = 0 or export_status = 2) limit ?2 ", nativeQuery = true)
    List<TransactionReceiptRecord> selectRecordsByImportStatusAndExportStatus(Integer status,Integer limit);

    @Query(value = "select count(1) from transaction_receipt_record where import_status =?1 ", nativeQuery = true)
    Long selectCountByImportStatus(Integer status);

    @Modifying
    @Transactional
    @Query(value = "update  transaction_receipt_record set import_status = ?1 where import_status = 0 and  order_no =?2 ", nativeQuery = true)
    int updateTransactionStatusByImportStatus(Integer status,String orderNo);

    @Query(value = "select * from transaction_receipt_record where order_no = ?1 and import_status = 1 and  export_status != 1 order by id desc", nativeQuery = true)
    List<TransactionReceiptRecord> selectRecords(String orderNo);

    @Query(value = "select * from transaction_receipt_record where consume_no = ?1 and import_status = 1 and  export_status != 1 order by id desc", nativeQuery = true)
    List<TransactionReceiptRecord> selectRecordsConsumeNo(String orderNo);


}
