package com.izouma.nineth.repo;

import com.izouma.nineth.domain.TokenHistory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

public interface TokenHistoryRepo extends JpaRepository<TokenHistory, Long>, JpaSpecificationExecutor<TokenHistory> {
    List<TokenHistory> findByTokenIdOrderByCreatedAtDesc(String tokenId);

    @Query("select t from TokenHistory t where t.toUserId = ?1 or t.fromUserId = ?1 order by t.createdAt desc")
    Page<TokenHistory> userHistory(Long userId, Pageable pageable);

    /**
     * 卖出 ，赠送他人
     * @param userId
     * @param projectId
     * @param operation
     * @return
     */
    @Query("select t from TokenHistory t where t.projectId = ?2 and t.fromUserId = ?1 and t.operation = ?3 and t.createdAt >=?4 order by t.createdAt desc")
    Page<TokenHistory> userHistoryAndProjectIdsale(Long userId, int projectId, String operation , LocalDateTime createdAt, Pageable pageable);

    /**
     * 买入 ，他人赠送
     * @param userId
     * @param projectId
     * @param operation
     * @return
     */
    @Query("select t from TokenHistory t where t.projectId = ?2 and t.toUserId = ?1  and (t.operation = ?3 or t.operation =?4) and t.createdAt >=?5 order by t.createdAt desc ")
    Page<TokenHistory> userHistoryAndProjectIdbuy(Long userId, int projectId, String operation , String operation1, LocalDateTime createdAt,Pageable pageable);


    /**
     * 按操作查询
     * @param userId
     * @param projectId
     * @param operation
     * @return
     */
    @Query("select t from TokenHistory t where t.projectId = ?2 and t.toUserId = ?1  and t.operation = ?3 and t.createdAt >=?4  order by t.createdAt desc ")
    Page<TokenHistory> userHistoryAndProjectIdoperation(Long userId, int projectId, String operation ,LocalDateTime createdAt,Pageable pageable);


    @Query("select t from TokenHistory t where t.projectId = ?2 and (t.toUserId = ?1 or t.fromUserId = ?1) and t.createdAt >=?3  order by t.createdAt desc")
    Page<TokenHistory> userHistoryAndProjectId(Long userId, int projectId,LocalDateTime createdAt, Pageable pageable);


    @Transactional
    @Modifying
    int deleteByTokenId(String tokenId);

    @Query("select t from TokenHistory t where t.fromUserId = t.toUserId")
    List<TokenHistory> findError();

    @Query("select t from TokenHistory t where t.assetId = ?1 ")
    Optional<TokenHistory> findByAssetId(Long assetId);

}
