package com.ssj.dao.kmt.kmt.dao;

import com.ssj.bean.kmt.kmt.domain.KmtCourseTemplate;
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;


@Repository
public interface KmtCourseTemplateDao extends JpaRepository<KmtCourseTemplate, String>{

	@Query(nativeQuery = true, value = " SELECT * from kmt_course_template t where t.teacher_id=?1 AND t.type=?2 and t.state = 1 ORDER BY t.num ASC  ")
	public List<KmtCourseTemplate> findTemplateByList(String teacherId, String type);

	@Query(nativeQuery = true, value = " SELECT teacher_id FROM (  select teacher_id from kmt_course_template where teacher_id in (?3) and state = 1 and val = ?1  and type=1" +
			" union all " +
			"select teacher_id from kmt_course_template where teacher_id in (?3) and state = 1 and left(val, 5) <= ?2 and right(val, 5) >= ?2 and type=2" +
			") TEMP GROUP BY teacher_id")
	public List<String> findTeacherCourseTime(int week, String courseTime, String[] teacherIds);

	@Query(nativeQuery = true, value = "SELECT teacher_id FROM ( select teacher_id from kmt_course_template where teacher_id in (?3) and state = 1 and val in (?1)  and type=1" +
			" union all " +
			"select teacher_id from kmt_course_template where teacher_id in (?3) and state = 1 and left(val, 5) <= ?2 and right(val, 5) >= ?2 and type=2" +
			") TEMP GROUP BY teacher_id")
	public List<String> findTeacherByWeek(int[] weeks, String courseTime, String[] teacherIds);

	@Query(nativeQuery = true, value = "select * from kmt_course_template where left(val, 5) <= ?2 and right(val, 5) >= ?2 and type=2 and teacher_id = ?1 and state=?3 limit 1")
	public KmtCourseTemplate findByTeacherIdAndState(String teacherId, String courseTime, int state);


	@Query(nativeQuery = true, value = "select * from kmt_course_template t1 where EXISTS" +
			" (select teacher_id from kmt_course_template t2 where t2.state = 1 and t1.teacher_id = t2.teacher_id " +
			" and t2.val=?2 and t2.type =1 and t2.teacher_id=?1) and t1.type = 2 and t1.state=1 ORDER BY t1.val asc")
	public List<KmtCourseTemplate> findByTeacherAndWeek(String teacherId, int week);

	@Query(nativeQuery = true, value = "select * from kmt_course_template  where   val=?3 and type =?2 and teacher_id=?1")
	public KmtCourseTemplate findTemplateByAnyThing(String teacherId, int type, String val);

	@Query(nativeQuery = true, value = "update kmt_course_template  set   state=?2  where  teacher_id=?1")
	@Modifying
	public void setTeacherDataState(String teacherId, int type);
}
