package cn.com.qmth.stmms.biz.mark.dao;

import java.util.Date;
import java.util.List;

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 cn.com.qmth.stmms.biz.mark.model.ProblemHistory;
import cn.com.qmth.stmms.common.enums.HistoryStatus;

public interface ProblemHistoryDao extends JpaRepository<ProblemHistory, Integer>,
        JpaSpecificationExecutor<ProblemHistory> {

    @Modifying
    @Query("delete ProblemHistory m where m.studentId=?1")
    void deleteByStudentId(Integer studentId);

    @Query("select count(s) from ProblemHistory s where s.examId=?1 and s.problemId=?2 ")
    long countByExamIdAndProblemId(Integer examId, Integer problemId);

    @Query("select distinct l.subjectCode from ProblemHistory l where l.examId=?1 and l.status=?2")
    List<String> findProblemSubjectCodeAndHistoryStatus(Integer examId, HistoryStatus status);

    @Modifying
    @Query("delete from ProblemHistory s where s.studentId in (select m.studentId from MarkLibrary m where m.markerId=?1 ) ")
    void deleteByMarkerId(Integer markerId);

    @Modifying
    @Query("delete from ProblemHistory s where s.examId=?1 and s.subjectCode=?2 and s.groupNumber=?3  ")
    void deleteByExamIdAndSubjectCodeAndGroupNumber(Integer examId, String subjectCode, Integer groupNumber);

    ProblemHistory findByLibraryIdAndStatus(Integer libraryId, HistoryStatus status);

    @Modifying
    @Query("update ProblemHistory s set s.userId=?3, s.status=?4, s.updateTime=?5 where s.libraryId=?1 and s.status=?2")
    int resetByLibraryId(Integer libraryId, HistoryStatus previousStatus, Integer userId, HistoryStatus newStatus,
            Date time);

    @Modifying
    @Query("delete ProblemHistory m where m.libraryId=?1")
    void deleteByLibraryId(Integer libraryId);

}
