package com.ssj.dao.sys.game.dao;

import com.ssj.bean.sys.game.domain.GameRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Mount Liu
 * @date 2018/2/19
 */
@Repository
public interface GameRecordDao extends JpaRepository<GameRecord, String> {

    /**
     * 按照关卡数倒序查找游戏记录
     * @param userId
     * @return
     */
    @Query(value = "select * from tb_game_record where is_delete=0 order by level desc ", nativeQuery = true)
    List<GameRecord> findByUserId(String userId);

    @Query(nativeQuery = true, value = "update tb_game_record set is_delete =1 where user_id = ?1 and is_delete = 0 ")
    @Modifying
    void deleteRecordsByUserId(String userId);

    /**
     * 查询最新的单关测试结果
     * @param userId 用户id
     * @return 测试结果
     */
    @Query(nativeQuery = true, value = "select * from tb_game_record where user_id = ?1 and is_delete = 0 order by create_time desc limit 1 ")
    GameRecord findNewest(String userId);

    /**
     * 根据用户和关卡查询单关测试结果
     * @param userId 用户id
     * @param level 关卡
     * @return 测试结果
     */
    @Query(nativeQuery = true, value = "select * from tb_game_record where user_id = ?1 and level = ?2 and is_delete = 0 limit 1")
    GameRecord findByUserIdAndLevel(String userId, int level);

    /**
     * 根据用户、答题人id、关卡查询单关测试结果
     * @param userId 用户id
     * @param gameRespondentId 答题人id
     * @param level 关卡
     * @return 测试结果
     */
    @Query(nativeQuery = true, value = "select * from tb_game_record where user_id = ?1 and game_respondent_id = ?2 and level = ?3 and is_delete = 0 limit 1")
    GameRecord findByUserIdAndGameRespondentIdAndLevel(String userId, String gameRespondentId, Integer level);
}
