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

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

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
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.Exam;
import cn.com.qmth.stmms.common.enums.ExamStatus;
import cn.com.qmth.stmms.common.enums.ExamType;
import cn.com.qmth.stmms.common.enums.ObjectiveStatus;

public interface ExamDao extends PagingAndSortingRepository<Exam, Integer>, JpaSpecificationExecutor<Exam> {

    public Page<Exam> findAll(Pageable pageable);

    List<Exam> findByStatus(ExamStatus status);

    @Query("select e from Exam e where e.creatorId=?1 and e.status=?2 order by e.examTime desc")
    public List<Exam> findByCreatorAndStatus(Integer id, ExamStatus status);

    @Modifying
    @Query("update Exam e set e.status=?2 where e.id=?1")
    public void updateStatus(Integer examId, ExamStatus status);

    @Modifying
    @Query("update Exam e set e.sliceConfig=?2 where e.id=?1")
    public void updateSliceConfig(Integer examId, String configString);

    List<Exam> findBySchoolIdAndTypeAndStatusOrderByIdDesc(Integer schoolId, ExamType type, ExamStatus status);

    List<Exam> findBySchoolIdOrderByIdDesc(Integer schoolId);

    public Exam findFirstBySchoolIdAndCode(Integer schoolId, String code);

    @Query(value = "select * from eb_exam e where e.id in (select DISTINCT m.exam_id from eb_marker m where m.user_id=?1) and e.create_time >?2 "
            + "order by e.id desc", nativeQuery = true)
    public List<Exam> findByMarkerUserId(Integer userId, Date time);

    @Query(value = "select * from eb_exam e where e.school_id = ?1 and e.id in (select s.exam_id from eb_exam_subject s where s.code in (select su.subject_code from eb_subject_user su where su.user_id=?2) )"
            + "order by e.id desc", nativeQuery = true)
    public List<Exam> findBySubjectHeaderUserId(Integer schoolId, Integer userId);

    @Modifying
    @Query("update Exam e set e.objectiveStatus=?2 where e.id=?1")
    public int updateObjectiveStatus(int examId, ObjectiveStatus status);

    @Query(value = "select * from eb_exam e where e.school_id = ?1 and e.id in (select s.exam_id from eb_user_exam s where s.user_id=?2 )"
            + "order by e.id desc", nativeQuery = true)
    public List<Exam> findBySchoolViewUserId(Integer schoolId, Integer userId);

    @Modifying
    @Query("update Exam e set e.updateTime=?2 where e.id=?1")
    public int updateUpdateTime(int examId, Date date);

}
