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

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import cn.com.qmth.stmms.biz.exam.model.MarkGroupStudent;
import cn.com.qmth.stmms.biz.exam.model.MarkGroupStudentPK;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.enums.SubjectiveStatus;

public interface MarkGroupStudentDao extends JpaRepository<MarkGroupStudent, MarkGroupStudentPK>,
        PagingAndSortingRepository<MarkGroupStudent, MarkGroupStudentPK> {

    @Query("select s from MarkGroupStudent s where s.pk.studentId=?1 and s.pk.groupNumber=?2")
    MarkGroupStudent findByStudentIdAndGroupNumber(Integer studentId, Integer groupNumber);

    @Query("select s.pk.studentId from MarkGroupStudent s where "
            + "s.examId=?1 and s.subjectCode=?2 and s.pk.groupNumber=?3 and s.status=?4")
    List<Integer> findStudentIdByGroupNumberAndStatus(Integer examId, String subjectCode, Integer groupNumber,
            SubjectiveStatus status);

    @Query("select count(s) from MarkGroupStudent s where s.pk.studentId=?1 and s.status=?2")
    long countByStudentIdAndStatus(Integer studentId, SubjectiveStatus status);

    @Modifying(clearAutomatically = true)
    @Query("delete MarkGroupStudent s where s.pk.studentId=?1")
    void deleteByStudentId(Integer studentId);

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

    @Modifying(clearAutomatically = true)
    @Query("update MarkGroupStudent s set s.status=?4 where s.examId=?1 and s.subjectCode=?2 and s.pk.groupNumber=?3")
    void updateStatusByExamIdAndSubjectCodeAndGroupNumber(Integer examId, String subjectCode, Integer groupNumber,
            SubjectiveStatus status);

    @Modifying(clearAutomatically = true)
    @Query("update MarkGroupStudent s set s.status=?4 where s.examId=?1 and s.subjectCode=?2 and s.pk.groupNumber=?3 and exists "
            + "(select l.id from MarkLibrary l where l.studentId=s.pk.studentId and l.groupNumber=s.pk.groupNumber and l.status in (?5))")
    void updateStatusByMarkLibraryStatus(Integer examId, String subjectCode, Integer groupNumber,
            SubjectiveStatus status, LibraryStatus... libraryStatus);

    @Modifying(clearAutomatically = true)
    @Query("update MarkGroupStudent s set s.status=?3 where s.examId=?1 and s.subjectCode=?2")
    void updateStatusByExamIdAndSubjectCode(Integer examId, String subjectCode, SubjectiveStatus status);
}
